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