+ # have a CC surcharge portion --> one-time charge
+ if ( $options{'cc_surcharge'} > 0 ) {
+ my $invnum;
+ $invnum = $options{'invnum'} if $options{'invnum'};
+ unless ( $invnum ) { # probably from a payment screen
+ # do we have any open invoices? pick earliest
+ # uses the fact that cust_main->cust_bill sorts by date ascending
+ my @open = $self->open_cust_bill;
+ $invnum = $open[0]->invnum if scalar(@open);
+ }
+
+ unless ( $invnum ) { # still nothing? pick last closed invoice
+ # again uses fact that cust_main->cust_bill sorts by date ascending
+ my @closed = $self->cust_bill;
+ $invnum = $closed[$#closed]->invnum if scalar(@closed);
+ }
+
+ unless ( $invnum ) {
+ # XXX: unlikely case - pre-paying before any invoices generated
+ # what it should do is create a new invoice and pick it
+ warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
+ return '';
+ }
+
+ my $cust_pkg;
+ my $charge_error = $self->charge({
+ 'amount' => $options{'cc_surcharge'},
+ 'pkg' => 'Credit Card Surcharge',
+ 'setuptax' => 'Y',
+ 'cust_pkg_ref' => \$cust_pkg,
+ });
+ if($charge_error) {
+ warn 'Unable to add CC surcharge';
+ return '';
+ }
+
+ my $cust_bill_pkg = new FS::cust_bill_pkg({
+ 'invnum' => $invnum,
+ 'pkgnum' => $cust_pkg->pkgnum,
+ 'setup' => $options{'cc_surcharge'},
+ });
+ my $cbp_error = $cust_bill_pkg->insert;
+
+ if ( $cbp_error) {
+ warn 'Cannot add CC surcharge line item to invoice #'.$invnum;
+ return '';
+ } else {
+ my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
+ warn 'invoice for cc surcharge: ' . Dumper($cust_bill) if $DEBUG;
+ $cust_bill->apply_payments_and_credits;
+ }
+
+ }
+