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