RT# 74435 - fixed so payment would auto unapply when doing a batch refund
[freeside.git] / httemplate / edit / process / cust_refund.cgi
1 %if ( $error ) {
2 %  $cgi->param('error', $error);
3 <% $cgi->redirect(popurl(2). "cust_refund.cgi?". $cgi->query_string ) %>
4 %} else {
5 %
6 %  if ( $link eq 'popup' ) {
7 %
8 <% header('Refund entered') %>
9     <SCRIPT TYPE="text/javascript">
10       window.top.location.reload();
11     </SCRIPT>
12
13     </BODY></HTML>
14 %  } else {
15 <% $cgi->redirect(popurl(3). "view/cust_main.cgi?custnum=$custnum;show=payment_history") %>
16 %  }
17 %}
18 <%init>
19
20 die "access denied"
21   unless $FS::CurrentUser::CurrentUser->access_right('Refund payment')
22       || $FS::CurrentUser::CurrentUser->access_right('Post refund');
23
24 $cgi->param('custnum') =~ /^(\d*)$/ or die "Illegal custnum!";
25 my $custnum = $1;
26 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
27   or die "unknown custnum $custnum";
28
29 my $link    = $cgi->param('popup') ? 'popup' : '';
30
31 my $payby = $cgi->param('payby');
32
33 die "access denied"
34   unless $FS::CurrentUser::CurrentUser->refund_access_right($payby);
35
36 $cgi->param('reasonnum') =~ /^(-?\d+)$/ or die "Illegal reasonnum";
37 my ($reasonnum, $error) = $m->comp('/misc/process/elements/reason');
38 $cgi->param('reasonnum', $reasonnum) unless $error;
39
40 if ( $error ) {
41   # do nothing
42 } elsif ( $payby =~ /^(CARD|CHEK)$/ ) { 
43   my %options = ();
44   my $bop = $FS::payby::payby2bop{$1};
45
46   my %payby2fields = (
47   'CARD' => [ qw( address1 address2 city county state zip country ) ],
48   'CHEK' => [ qw( ss paytype paystate stateid stateid_state ) ],
49   );
50   my %type = ( 'CARD' => 'credit card',
51              'CHEK' => 'electronic check (ACH)',
52              );
53
54 my( $cust_pay, $cust_payby, $payinfo, $paycvv, $month, $year, $payname );
55 my $paymask = '';
56
57 ## get cust pay info if paynum exists
58 if ( $cgi->param('paynum') > 0) {
59   $cust_pay = qsearchs({
60     'table'     => 'cust_pay',
61     'hashref'   => { 'paynum' => $cgi->param('paynum') },
62     'select'    => 'cust_pay.*, cust_pay_batch.payname ',
63     'addl_from' => "left join cust_pay_batch on cust_pay_batch.batchnum = cust_pay.batchnum and cust_pay_batch.custnum = $custnum ",
64   });
65 }
66
67 if ( (my $custpaybynum = scalar($cgi->param('custpaybynum'))) > 0 ) {
68
69   ##
70   # use stored cust_payby info
71   ##
72
73   $cust_payby = qsearchs('cust_payby', { custnum      => $custnum,
74                                             custpaybynum => $custpaybynum, } )
75     or die "unknown custpaybynum $custpaybynum";
76
77   # not needed for realtime_bop, but still needed for batch_card
78   $payinfo = $cust_payby->payinfo;
79   $paymask = $cust_payby->paymask;
80   $paycvv = $cust_payby->paycvv; # pass it if we got it, running a transaction will clear it
81   ( $month, $year ) = $cust_payby->paydate_mon_year;
82   $payname = $cust_payby->payname;
83   $cgi->param(-name=>"paytype", -value=>$cust_payby->paytype) unless $cgi->param("paytype");
84
85 } elsif ( $cgi->param('paynum') > 0) {
86
87   $payinfo = $cust_pay->payinfo;
88   $payname = $cust_pay->payname;
89
90 } else {
91
92   ##
93   # use new info
94   ##
95
96   $cgi->param('year') =~ /^(\d+)$/
97     or errorpage("illegal year ". $cgi->param('year'));
98   $year = $1;
99
100   $cgi->param('month') =~ /^(\d+)$/
101     or errorpage("illegal month ". $cgi->param('month'));
102   $month = $1;
103
104   $cgi->param('payname') =~ /^([\w \,\.\-\']+)$/
105     or errorpage(gettext('illegal_name'). " payname: ". $cgi->param('payname'));
106   $payname = $1;
107
108   if ( $payby eq 'CHEK' ) {
109
110     $cgi->param('payinfo1') =~ /^(\d+)$/
111       or errorpage("Illegal account number ". $cgi->param('payinfo1'));
112     my $payinfo1 = $1;
113     $cgi->param('payinfo2') =~ /^(\d+)$/
114       or errorpage("Illegal ABA/routing number ". $cgi->param('payinfo2'));
115     my $payinfo2 = $1;
116     if ( $conf->config('echeck-country') eq 'CA' ) {
117       $cgi->param('payinfo3') =~ /^(\d{5})$/
118         or errorpage("Illegal branch number ". $cgi->param('payinfo2'));
119       $payinfo2 = "$1.$payinfo2";
120     }
121     $payinfo = $payinfo1 . '@'. $payinfo2;
122
123   } elsif ( $payby eq 'CARD' ) {
124
125     $payinfo = $cgi->param('payinfo');
126
127     $payinfo =~ s/\D//g;
128     $payinfo =~ /^(\d{13,19}|\d{8,9})$/
129       or errorpage(gettext('invalid_card'));
130     $payinfo = $1;
131     validate($payinfo)
132       or errorpage(gettext('invalid_card'));
133
134     unless ( $cust_main->tokenized($payinfo) ) { #token
135
136       my $cardtype = cardtype($payinfo);
137
138       errorpage(gettext('unknown_card_type'))
139         if $cardtype eq "Unknown";
140
141       my %bop_card_types = map { $_=>1 } values %{ card_types() };
142       errorpage("$cardtype not accepted") unless $bop_card_types{$cardtype};
143
144     }
145
146     if ( length($cgi->param('paycvv') ) ) {
147       if ( cardtype($payinfo) eq 'American Express card' ) {
148         $cgi->param('paycvv') =~ /^(\d{4})$/
149           or errorpage("CVV2 (CID) for American Express cards is four digits.");
150         $paycvv = $1;
151       } else {
152         $cgi->param('paycvv') =~ /^(\d{3})$/
153           or errorpage("CVV2 (CVC2/CID) is three digits.");
154         $paycvv = $1;
155       }
156     } elsif ( $conf->exists('backoffice-require_cvv') ){
157       errorpage("CVV2 is required");
158     }
159
160   } else {
161     die "unknown payby $payby";
162   }
163
164   # save first, for proper tokenization
165   if ( $cgi->param('save') ) {
166
167     my %saveopt;
168     if ( $payby eq 'CARD' ) {
169       my $bill_location = FS::cust_location->new;
170       $bill_location->set( $_ => scalar($cgi->param($_)) )
171         foreach @{$payby2fields{$payby}};
172       $saveopt{'bill_location'} = $bill_location;
173       $saveopt{'paycvv'} = $paycvv; # save_cust_payby contains conf logic for when to use this
174       $saveopt{'paydate'} = "$year-$month-01";
175     } else {
176       # ss/stateid/stateid_state won't be saved, but should be harmless to pass
177       %saveopt = map { $_ => scalar($cgi->param($_)) } @{$payby2fields{$payby}};
178     }
179
180     my $error = $cust_main->save_cust_payby(
181       'saved_cust_payby' => \$cust_payby,
182       'payment_payby' => $payby,
183       'auto'          => scalar($cgi->param('auto')),
184       'weight'        => scalar($cgi->param('weight')),
185       'payinfo'       => $payinfo,
186       'payname'       => $payname,
187       %saveopt
188     );
189
190     errorpage("error saving info, payment not processed: $error")
191       if $error;
192
193   } elsif ( $payby eq 'CARD' ) { # not saving
194
195     $paymask = FS::payinfo_Mixin->mask_payinfo('CARD',$payinfo); # for untokenized but tokenizable payinfo
196
197   }
198
199 }
200
201 ##
202 # now run the refund
203 ##
204
205   $cgi->param('refund') =~ /^(\d*)(\.\d{2})?$/
206     or die "illegal refund amount ". $cgi->param('refund');
207   my $refund = "$1$2";
208   $cgi->param('paynum') =~ /^(\d*)$/ or die "Illegal paynum!";
209   my $paynum = $1;
210   my $paydate = $cgi->param('exp_year'). '-'. $cgi->param('exp_month'). '-01';
211
212   if ( $cgi->param('batch') ) {
213     $paydate = "2037-12-01" unless $paydate;
214     $error ||= $cust_main->batch_card(
215                                      'payby'    => $payby,
216                                      'amount'   => $refund,
217                                      #'payinfo'  => $payinfo,
218                                      #'paydate'  => $paydate,
219                                      #'payname'  => $payname,
220                                      'paycode'  => 'C',
221                                      map { $_ => scalar($cgi->param($_)) }
222                                        @{$payby2fields{$payby}}
223                                    );
224     errorpage($error) if $error;
225
226     my %hash = map {
227       $_, scalar($cgi->param($_))
228     } fields('cust_refund');
229
230     ## unapply payment before creating refund.
231     while ( $cust_pay && $cust_pay->unapplied < $refund ) {
232       my @cust_bill_pay = $cust_pay->cust_bill_pay;
233       last unless @cust_bill_pay;
234       my $cust_bill_pay = pop @cust_bill_pay;
235       my $error = $cust_bill_pay->delete;
236       last if $error;
237     }
238
239     my $new = new FS::cust_refund ( { 'paynum' => $paynum,
240                                       %hash,
241                                   } );
242     $error = $new->insert;
243
244   # if not a batch refund run realtime.
245   } else {
246     $options{'paydate'} = $paydate if $paydate =~ /^\d{2,4}-\d{1,2}-01$/;
247     $error = $cust_main->realtime_refund_bop( $bop, 'amount' => $refund,
248                                                   'paynum' => $paynum,
249                                                   'reasonnum' => $reasonnum,
250                                                   %options );
251   }
252 } else { # run cash refund.
253   my %hash = map {
254     $_, scalar($cgi->param($_))
255   } fields('cust_refund');
256   my $paynum = $cgi->param('paynum');
257   $paynum =~ /^(\d*)$/ or die "Illegal paynum!";
258   if ($paynum) {
259     my $cust_pay = qsearchs('cust_pay',{ 'paynum' => $paynum });
260     die "Could not find paynum $paynum" unless $cust_pay;
261     $error = $cust_pay->refund(\%hash);
262   } else {
263     my $new = new FS::cust_refund ( \%hash );
264     $error = $new->insert;
265   }
266 }
267
268 </%init>