RT# 83306 - fixed realtime refunds
[freeside.git] / httemplate / edit / process / cust_refund.cgi
index 1f96456..d582b12 100755 (executable)
@@ -39,6 +39,13 @@ $cgi->param('reasonnum') =~ /^(-?\d+)$/ or die "Illegal reasonnum";
 my ($reasonnum, $error) = $m->comp('/misc/process/elements/reason');
 $cgi->param('reasonnum', $reasonnum) unless $error;
 
+if ( $cgi->param('batch') ) {
+  $error = "No batch download format configured that allows electronic refunds via batch processing."
+    unless (FS::pay_batch->can_handle_electronic_refunds && !$error);
+}
+
+#die "my error\n".$error;
+
 if ( $error ) {
   # do nothing
 } elsif ( $payby =~ /^(CARD|CHEK)$/ ) { 
@@ -53,8 +60,19 @@ if ( $error ) {
              'CHEK' => 'electronic check (ACH)',
              );
 
-my( $cust_pay, $cust_payby, $payinfo, $paycvv, $month, $year, $payname );
+my( $cust_pay, $cust_payby, $payinfo, $paycvv, $month, $year, $payname, $paycardtype );
 my $paymask = '';
+
+## get cust pay info if paynum exists
+if ( $cgi->param('paynum') > 0) {
+  $cust_pay = qsearchs({
+    'table'     => 'cust_pay',
+    'hashref'   => { 'paynum' => $cgi->param('paynum') },
+    'select'    => 'cust_pay.*, cust_pay_batch.payname ',
+    'addl_from' => "left join cust_pay_batch on cust_pay_batch.batchnum = cust_pay.batchnum and cust_pay_batch.custnum = $custnum ",
+  });
+}
+
 if ( (my $custpaybynum = scalar($cgi->param('custpaybynum'))) > 0 ) {
 
   ##
@@ -75,13 +93,8 @@ if ( (my $custpaybynum = scalar($cgi->param('custpaybynum'))) > 0 ) {
 
 } elsif ( $cgi->param('paynum') > 0) {
 
-  $cust_pay = qsearchs({
-    'table'     => 'cust_pay',
-    'hashref'   => { 'paynum' => $cgi->param('paynum') },
-    'select'    => 'cust_pay.*, cust_pay_batch.payname ',
-    'addl_from' => "left join cust_pay_batch on cust_pay_batch.batchnum = cust_pay.batchnum and cust_pay_batch.custnum = $custnum ",
-  });
   $payinfo = $cust_pay->payinfo;
+  $paycardtype = $cust_pay->paycardtype;
   $payname = $cust_pay->payname;
 
 } else {
@@ -228,6 +241,19 @@ if ( (my $custpaybynum = scalar($cgi->param('custpaybynum'))) > 0 ) {
       $_, scalar($cgi->param($_))
     } fields('cust_refund');
 
+    $hash{'payinfo'} = $payinfo;
+    $hash{'paymask'} = $paymask;
+    $hash{'paycardtype'} = $paycardtype;
+
+    ## unapply payment before creating refund.
+    while ( $cust_pay && $cust_pay->unapplied < $refund ) {
+      my @cust_bill_pay = $cust_pay->cust_bill_pay;
+      last unless @cust_bill_pay;
+      my $cust_bill_pay = pop @cust_bill_pay;
+      my $error = $cust_bill_pay->delete;
+      last if $error;
+    }
+
     my $new = new FS::cust_refund ( { 'paynum' => $paynum,
                                       %hash,
                                   } );