+ # if we unapplied any payments from line items, also unapply that
+ # amount from the invoice
+ foreach my $billpaynum (keys %unapplied_payments) {
+ my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
+ or die "broken payment application $billpaynum";
+ $error = $cust_bill_pay->delete; # can't replace
+
+ my $new_cust_bill_pay = FS::cust_bill_pay->new({
+ $cust_bill_pay->hash,
+ billpaynum => '',
+ amount => sprintf('%.2f',
+ $cust_bill_pay->get('amount') - $unapplied_payments{$billpaynum})
+ });
+
+ if ( $new_cust_bill_pay->amount > 0 ) {
+ $error ||= $new_cust_bill_pay->insert;
+ }
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return "Error unapplying payment: $error";
+ }
+ }
+
+ #NOW insert cust_credit_bill