manual echeck payment type, RT#26995
[freeside.git] / httemplate / search / elements / cust_pay_or_refund.html
1 <%doc>
2
3 Examples:
4
5   include( 'elements/cust_pay_or_refund.html',
6                'thing'          => 'pay',
7                'amount_field'   => 'paid',
8                'name_singular'  => 'payment',
9                'name_verb'      => 'paid',
10          )
11
12   include( 'elements/cust_pay_or_refund.html',
13                'thing'          => 'refund',
14                'amount_field'   => 'refund',
15                'name_singular'  => 'refund',
16                'name_verb'      => 'refunded',
17          )
18
19   include( 'elements/cust_pay_or_refund.html',
20                'thing'          => 'pay_pending',
21                'amount_field'   => 'paid',
22                'name_singular'  => 'pending payment',
23                'name_verb'      => 'pending',
24                'disable_link'   => 1,
25                'disable_by'     => 1,
26                'html_init'      => '',
27                'addl_header'    => [],
28                'addl_fields'    => [],
29                'redirect_empty' => $redirect_empty,
30           )
31
32   include( 'elements/cust_pay_or_refund.html',
33                'table'          => 'h_cust_pay',
34                'amount_field'   => 'paid',
35                'name_singular'  => 'payment',
36                'name_verb'      => 'paid',
37                'pre_header'     => [ 'Transaction',    'By' ],
38                'pre_fields'     => [ 'history_action', 'history_user' ],
39          )
40
41 </%doc>
42 <& search.html,
43                 'title'          => $title, # XXX: translate
44                 'name_singular'  => $name_singular,
45                 'query'          => $sql_query,
46                 'count_query'    => $count_query,
47                 'count_addl'     => \@count_addl,
48                 'redirect_empty' => $opt{'redirect_empty'},
49                 'header'         => \@header,
50                 'fields'         => \@fields,
51                 'sort_fields'    => \@sort_fields,
52                 'align'          => $align,
53                 'links'          => \@links,
54                 'link_onclicks'  => \@link_onclicks,
55                 'color'          => \@color,
56                 'style'          => \@style,
57 &>
58 <%init>
59
60 my %opt = @_;
61
62 my $curuser = $FS::CurrentUser::CurrentUser;
63
64 die "access denied"
65   unless $curuser->access_right('Financial reports');
66
67 my $table = $opt{'table'} || 'cust_'.$opt{'thing'};
68
69 my $amount_field = $opt{'amount_field'};
70 my $name_singular = $opt{'name_singular'};
71
72 my $unapplied = $cgi->param('unapplied');
73 my $title = '';
74 $title = 'Unapplied ' if $unapplied;
75 $title .= "\u$name_singular Search Results";
76
77 my $link = '';
78 if (    ( $curuser->access_right('View invoices') #remove in 2.5 (2.7?)
79           || ($curuser->access_right('View payments') && $table =~ /^cust_pay/)
80           || ($curuser->access_right('View refunds') && $table eq 'cust_refund')
81         )
82      && ! $opt{'disable_link'}
83    )
84 {
85
86   my $key;
87   my $q = '';
88   if ( $table eq 'cust_pay_void' ) {
89     $key = 'paynum';
90     $q .= 'void=1;';
91   } elsif ( $table eq /^cust_(\w+)$/ ) {
92     $key = $1.'num';
93   }
94   
95   if ( $key ) {
96     $q .= "$key=";
97     $link = [ "${p}view/$table.html?$q", $key ]
98   }
99 }
100
101 my $cust_link = sub {
102   my $cust_thing = shift;
103   $cust_thing->cust_main_custnum
104     ? [ "${p}view/cust_main.cgi?", 'custnum' ] 
105     : '';
106 };
107
108 # only valid for $table == 'cust_pay' atm
109 my  $tax_names = '';
110 if ( $cgi->param('tax_names') ) {
111   if ( dbh->{Driver}->{Name} =~ /^Pg/i ) {
112
113     $tax_names = "
114       array_to_string(
115         array(
116           SELECT itemdesc
117             FROM cust_bill_pay
118             LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
119             LEFT JOIN cust_bill_pkg USING ( billpkgnum )
120               WHERE cust_bill_pkg.pkgnum = 0
121                 AND cust_bill_pay.paynum = cust_pay.paynum
122         ), '|'
123       ) AS tax_names"
124     ;
125
126   } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
127
128     $tax_names = "GROUP_CONCAT(itemdesc SEPARATOR '|') AS tax_names";
129
130   } else {
131
132     warn "warning: unknown database type ". dbh->{Driver}->{Name}.
133          "omitting tax name information from report.";
134
135   }
136 }
137
138 my @header;
139 my @fields;
140 my @sort_fields;
141 my $align = '';
142 my @links;
143 my @link_onclicks;
144 if ( $opt{'pre_header'} ) {
145   push @header, @{ $opt{'pre_header'} };
146   $align .= 'c' x scalar(@{ $opt{'pre_header'} });
147   push @links, map '', @{ $opt{'pre_header'} };
148   push @fields, @{ $opt{'pre_fields'} };
149   push @sort_fields, @{ $opt{'pre_fields'} };
150 }
151
152 my $sub_receipt = sub {
153   my $obj = shift;
154   my $objnum = $obj->primary_key . '=' . $obj->get($obj->primary_key);
155
156   include('/elements/popup_link_onclick.html',
157     'action'  => $p.'view/cust_pay.html?link=popup;'.$objnum,
158     'actionlabel' => emt('Payment Receipt'),
159   );
160 };
161
162 push @header, "\u$name_singular",
163               'Amount',
164 ;
165 $align .= 'rr';
166 push @links, '', '';
167 push @fields, 'payby_payinfo_pretty',
168               sub { sprintf('$%.2f', shift->$amount_field() ) },
169 ;
170 push @link_onclicks, $sub_receipt, '';
171 push @sort_fields, '', $amount_field;
172
173 if ( $unapplied ) {
174   push @header, emt('Unapplied');
175   $align .= 'r';
176   push @links, '';
177   push @fields, sub { sprintf('$%.2f', shift->unapplied_amount) };
178   push @sort_fields, '';
179 }
180
181 push @header, emt('Date');
182 $align .= 'r';
183 push @links, '';
184 push @fields, sub { time2str('%b %d %Y', shift->_date ) };
185 push @sort_fields, '_date';
186
187 unless ( $opt{'disable_by'} ) {
188   push @header, emt('By');
189   $align .= 'c';
190   push @links, '';
191   push @fields, sub { my $o = shift->otaker;
192                       $o = 'auto billing'          if $o eq 'fs_daily';
193                       $o = 'customer self-service' if $o eq 'fs_selfservice';
194                       $o;
195                     };
196 }
197
198 if ( $tax_names ) {
199   push @header, (emt('Tax names'), emt('Tax province'));
200   $align .= 'cc';
201   push @links, ('','');
202   push @fields, sub { join (' + ', map { /^(.*?)(, \w\w)?$/; $1 }
203                                    split('\|', shift->tax_names)
204                            );
205                     };
206   push @fields, sub { join (' + ', map { if (/^(?:.*)(?:, )(\w\w)$/){ $1 }
207                                          else { () }
208                                        }
209                                    split('\|', shift->tax_names)
210                            );
211                     };
212 }
213
214 push @header, FS::UI::Web::cust_header();
215 $align .=  FS::UI::Web::cust_aligns();
216 push @links, map { $_ ne 'Cust. Status' ? $cust_link : '' }
217                  FS::UI::Web::cust_header();
218 my @color = ( ( map '', @fields ), FS::UI::Web::cust_colors() );
219 my @style = ( ( map '', @fields ), FS::UI::Web::cust_styles() );
220 push @fields, \&FS::UI::Web::cust_fields;
221
222 push @header, @{ $opt{'addl_header'} }
223   if $opt{'addl_header'};
224 push @fields, @{ $opt{'addl_fields'} }
225   if $opt{'addl_fields'};
226
227 my( $count_query, $sql_query, @count_addl );
228 if ( $cgi->param('magic') ) {
229
230   my @search = ();
231   my @select = (
232     "$table.*",
233     FS::UI::Web::cust_sql_fields(),
234     'cust_main.custnum AS cust_main_custnum',
235   );
236   push @select, $tax_names if $tax_names;
237
238   my $orderby;
239   if ( $cgi->param('magic') eq '_date' ) {
240
241     if ( $cgi->param('agentnum') && $cgi->param('agentnum') =~ /^(\d+)$/ ) {
242       push @search, "cust_main.agentnum = $1"; # $search{'agentnum'} = $1;
243       my $agent = qsearchs('agent', { 'agentnum' => $1 } );
244       die "unknown agentnum $1" unless $agent;
245       $title = $agent->agent. " $title";
246     }
247
248     if ( $cgi->param('refnum') && $cgi->param('refnum') =~ /^(\d+)$/ ) {
249       push @search, "cust_main.refnum = $1";
250       my $part_referral = qsearchs('part_referral', { 'refnum' => $1 } );
251       die "unknown refnum $1" unless $part_referral;
252       $title = $part_referral->referral. " $title";
253     }
254
255     # cust_classnum (false laziness w/ elements/cust_main_dayranges.html, prepaid_income.html, cust_bill_pay.html, cust_bill_pkg.html cust_bill_pkg_referral.html, unearned_detail.html, cust_credit.html, cust_credit_refund.html, cust_main::Search::search_sql)
256     if ( grep { $_ eq 'cust_classnum' } $cgi->param ) {
257       my @classnums = grep /^\d*$/, $cgi->param('cust_classnum');
258       push @search, 'COALESCE( cust_main.classnum, 0) IN ( '.
259                         join(',', map { $_ || '0' } @classnums ).
260                     ' )'
261         if @classnums;
262     }
263
264     if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
265       push @search, "$table.custnum = $1";
266     }
267
268     if ( $cgi->param('payby') ) {
269
270       my @all_payby_search = ();
271       foreach my $payby ( $cgi->param('payby') ) {
272
273         $payby =~
274           /^(CARD|CHEK|BILL|CASH|PPAL|APPL|ANRD|PREP|WIRE|WEST|EDI|MCRD|MCHK)(-(VisaMC|Amex|Discover|Maestro|Tokenized))?$/
275             or die "illegal payby $payby";
276
277         my $payby_search = "$table.payby = '$1'";
278
279         if ( $3 ) {
280
281           my $cardtype = $3;
282
283           my $similar_to = dbh->{Driver}->{Name} =~ /^mysql/i
284                              ? 'REGEXP' #doesn't behave exactly the same, but
285                                         #should work for our patterns
286                              : 'SIMILAR TO';
287
288           my $search;
289           if ( $cardtype eq 'VisaMC' ) {
290
291             #avoid posix regexes for portability
292             $search =
293               " ( (     substring($table.payinfo from 1 for 1) = '4'     ".
294               "     AND substring($table.payinfo from 1 for 4) != '4936' ".
295               "     AND substring($table.payinfo from 1 for 6)           ".
296               "         NOT $similar_to '49030[2-9]'                        ".
297               "     AND substring($table.payinfo from 1 for 6)           ".
298               "         NOT $similar_to '49033[5-9]'                        ".
299               "     AND substring($table.payinfo from 1 for 6)           ".
300               "         NOT $similar_to '49110[1-2]'                        ".
301               "     AND substring($table.payinfo from 1 for 6)           ".
302               "         NOT $similar_to '49117[4-9]'                        ".
303               "     AND substring($table.payinfo from 1 for 6)           ".
304               "         NOT $similar_to '49118[1-2]'                        ".
305               "   )".
306               "   OR substring($table.payinfo from 1 for 2) = '51' ".
307               "   OR substring($table.payinfo from 1 for 2) = '52' ".
308               "   OR substring($table.payinfo from 1 for 2) = '53' ".
309               "   OR substring($table.payinfo from 1 for 2) = '54' ".
310               "   OR substring($table.payinfo from 1 for 2) = '54' ".
311               "   OR substring($table.payinfo from 1 for 2) = '55' ".
312 #              "   OR substring($table.payinfo from 1 for 2) = '36' ". #Diner's int'l was processed as Visa/MC inside US, now Discover
313               " ) ";
314
315           } elsif ( $cardtype eq 'Amex' ) {
316
317             $search =
318               " (    substring($table.payinfo from 1 for 2 ) = '34' ".
319               "   OR substring($table.payinfo from 1 for 2 ) = '37' ".
320               " ) ";
321
322           } elsif ( $cardtype eq 'Discover' ) {
323
324             my $conf = new FS::Conf;
325             my $country = $conf->config('countrydefault') || 'US';
326
327             $search =
328               " (    substring($table.payinfo from 1 for 4 ) = '6011'  ".
329               "   OR substring($table.payinfo from 1 for 2 ) = '65'    ".
330               "   OR substring($table.payinfo from 1 for 3 ) = '300'   ".
331               "   OR substring($table.payinfo from 1 for 3 ) = '301'   ".
332               "   OR substring($table.payinfo from 1 for 3 ) = '302'   ".
333               "   OR substring($table.payinfo from 1 for 3 ) = '303'   ".
334               "   OR substring($table.payinfo from 1 for 3 ) = '304'   ".
335               "   OR substring($table.payinfo from 1 for 3 ) = '305'   ".
336               "   OR substring($table.payinfo from 1 for 4 ) = '3095'  ".
337               "   OR substring($table.payinfo from 1 for 2 ) = '36'    ".
338               "   OR substring($table.payinfo from 1 for 2 ) = '38'    ".
339               "   OR substring($table.payinfo from 1 for 2 ) = '39'    ".
340               "   OR substring($table.payinfo from 1 for 3 ) = '644'   ".
341               "   OR substring($table.payinfo from 1 for 3 ) = '645'   ".
342               "   OR substring($table.payinfo from 1 for 3 ) = '646'   ".
343               "   OR substring($table.payinfo from 1 for 3 ) = '647'   ".
344               "   OR substring($table.payinfo from 1 for 3 ) = '648'   ".
345               "   OR substring($table.payinfo from 1 for 3 ) = '649'   ".
346               ( $country =~ /^(US|CA)$/
347                ?" OR substring($table.payinfo from 1 for 4 ) = '3528'  ". # JCB cards in the 3528-3589 range identified as Discover inside US/CA
348                 " OR substring($table.payinfo from 1 for 4 ) = '3529'  ".
349                 " OR substring($table.payinfo from 1 for 3 ) = '353'   ".
350                 " OR substring($table.payinfo from 1 for 3 ) = '354'   ".
351                 " OR substring($table.payinfo from 1 for 3 ) = '355'   ".
352                 " OR substring($table.payinfo from 1 for 3 ) = '356'   ".
353                 " OR substring($table.payinfo from 1 for 3 ) = '357'   ".
354                 " OR substring($table.payinfo from 1 for 3 ) = '358'   "
355                :""
356               ).
357               "   OR substring($table.payinfo from 1 for 3 ) = '622'   ". #China Union Pay processed as Discover outside CN
358               " ) ";
359
360           } elsif ( $cardtype eq 'Maestro' ) {
361
362             $search =
363               " (    substring($table.payinfo from 1 for 2 ) = '63'     ".
364               "   OR substring($table.payinfo from 1 for 2 ) = '67'     ".
365               "   OR substring($table.payinfo from 1 for 6 ) = '564182' ".
366               "   OR substring($table.payinfo from 1 for 4 ) = '4936'   ".
367               "   OR substring($table.payinfo from 1 for 6 )            ".
368               "      $similar_to '49030[2-9]'                             ".
369               "   OR substring($table.payinfo from 1 for 6 )            ".
370               "      $similar_to '49033[5-9]'                             ".
371               "   OR substring($table.payinfo from 1 for 6 )            ".
372               "      $similar_to '49110[1-2]'                             ".
373               "   OR substring($table.payinfo from 1 for 6 )            ".
374               "      $similar_to '49117[4-9]'                             ".
375               "   OR substring($table.payinfo from 1 for 6 )            ".
376               "      $similar_to '49118[1-2]'                             ".
377               " ) ";
378
379           } elsif ( $cardtype eq 'Tokenized' ) {
380
381             $search = " substring($table.payinfo from 1 for 2 ) = '99' ";
382
383           } else {
384             die "unknown card type $cardtype";
385           }
386
387           my $masksearch = $search;
388           $masksearch =~ s/$table\.payinfo/$table.paymask/gi;
389
390           $payby_search = "( $payby_search AND ( $search OR ( $table.paymask IS NOT NULL AND $masksearch ) ) )";
391
392         }
393
394         push @all_payby_search, $payby_search;
395
396       }
397
398       push @search, ' ( '. join(' OR ', @all_payby_search). ' ) ' if @all_payby_search;
399
400     }
401
402     if ( $cgi->param('payinfo') ) {
403       $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/
404         or die "illegal payinfo ". $cgi->param('payinfo');
405       push @search, "$table.payinfo = '$1'";
406     }
407
408     if ( $cgi->param('ccpay') =~ /^([\w-:]+)$/ ) {
409       # I think that's all the characters we need to allow.
410       # To avoid confusion, this parameter searches both auth and order_number.
411       push @search, "($table.auth LIKE '$1%') OR ($table.order_number LIKE '$1%')";
412       push @fields, 'auth', 'order_number';
413       push @header, 'Auth #', 'Transaction #';
414       $align .= 'rr';
415
416     }
417
418     if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
419       push @search, "$table.usernum = $1";
420     }
421
422     #for cust_pay_pending...  statusNOT=done
423     if ( $cgi->param('statusNOT') =~ /^(\w+)$/ ) {
424       push @search, "$table.status != '$1'";
425     }
426
427     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
428
429     push @search, "$table._date >= $beginning ",
430                   "$table._date <= $ending";
431
432     if ( $table eq 'cust_pay_void' ) {
433       my($v_beginning, $v_ending) =
434         FS::UI::Web::parse_beginning_ending($cgi, 'void');
435       push @search, "$table.void_date >= $v_beginning ",
436                     "$table.void_date <= $v_ending";
437     }
438
439     push @search, FS::UI::Web::parse_lt_gt($cgi, "$table.$amount_field" );
440
441     $orderby = '_date';
442
443   } elsif ( $cgi->param('magic') eq 'paybatch' ) {
444
445     $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/
446       or die "illegal paybatch: ". $cgi->param('paybatch');
447
448     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
449
450   } elsif ( $cgi->param('magic') eq 'batchnum' ) {
451
452     $cgi->param('batchnum') =~ /^(\d+)$/
453       or die "illegal batchnum: ".$cgi->param('batchnum');
454
455     push @search, "batchnum = $1";
456
457     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
458
459   } else {
460     die "unknown search magic: ". $cgi->param('magic');
461   }
462
463   if ( $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/ ) {
464     push @search, "paybatch = '$1'";
465   }
466
467   #unapplied payment/refund
468   if ( $unapplied ) {
469     push @select, '(' . "FS::$table"->unapplied_sql . ') AS unapplied_amount';
470     push @search, "FS::$table"->unapplied_sql . ' > 0';
471
472   }
473
474   #for the history search
475   if ( $cgi->param('history_action') =~ /^([\w,]+)$/ ) {
476     my @history_action = split(/,/, $1);
477     push @search, 'history_action IN ('.
478                     join(',', map "'$_'", @history_action ). ')';
479   }
480
481   if (    $cgi->param('history_date_beginning')
482        || $cgi->param('history_date_ending')    ) {
483       my($h_beginning, $h_ending) =
484         FS::UI::Web::parse_beginning_ending($cgi, 'history_date');
485       push @search, "history_date >= $h_beginning ",
486                     "history_date <= $h_ending";
487   }
488
489   #here is the agent virtualization
490   push @search, $curuser->agentnums_sql;
491
492   my $addl_from = FS::UI::Web::join_cust_main($table);
493   my $group_by = '';
494
495   if ( $cgi->param('tax_names') ) {
496     if ( dbh->{Driver}->{Name} =~ /^Pg/i ) {
497
498       0;#twiddle thumbs
499
500     } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
501
502       $addl_from .= "LEFT JOIN cust_bill_pay USING ( paynum )
503                      LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
504                      LEFT JOIN cust_bill_pkg USING ( billpkgnum ) AS tax_names";
505       $group_by  .= "GROUP BY $table.*,cust_main_custnum,".
506                     FS::UI::Web::cust_sql_fields();
507       push @search,
508        "( cust_bill_pkg.pkgnum = 0 OR cust_bill_pkg.pkgnum is NULL )";
509
510     } else {
511
512       warn "warning: unknown database type ". dbh->{Driver}->{Name}.
513            "omitting tax name information from report.";
514
515     }
516   }
517
518   my $search = ' WHERE '. join(' AND ', @search);
519
520   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) ";
521   $count_query .= ', SUM(' . "FS::$table"->unapplied_sql . ') ' 
522     if $unapplied;
523   $count_query .= "FROM $table $addl_from".
524                   "$search $group_by";
525
526   @count_addl = ( '$%.2f total '.$opt{name_verb} );
527   push @count_addl, '$%.2f unapplied' if $unapplied;
528
529   $sql_query = {
530     'table'     => $table,
531     'select'    => join(', ', @select),
532     'hashref'   => {},
533     'extra_sql' => "$search $group_by",
534     'order_by'  => "ORDER BY $orderby",
535     'addl_from' => $addl_from,
536   };
537
538 } else {
539
540   #hmm... is this still used?
541
542   $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/ or die "illegal payinfo";
543   my $payinfo = $1;
544
545   $cgi->param('payby') =~ /^(\w+)$/ or die "illegal payby";
546   my $payby = $1;
547
548   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) FROM $table".
549                  "  WHERE payinfo = '$payinfo' AND payby = '$payby'".
550                  "  AND ". $curuser->agentnums_sql;
551   @count_addl = ( '$%.2f total '.$opt{name_verb} );
552
553   $sql_query = {
554     'table'     => $table,
555     'hashref'   => { 'payinfo' => $payinfo,
556                      'payby'   => $payby    },
557     'extra_sql' => $curuser->agentnums_sql.
558                    " ORDER BY _date",
559   };
560
561 }
562
563 # for consistency
564 $title = join('',map {ucfirst} split(/\b/,$title));
565
566 </%init>