multiple payment types on payment and refund reports, RT#21061
[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} eq 'Pg' ) {
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, "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, "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     if ( $cgi->param('cust_classnum') ) {
256       my @classnums = grep /^\d+$/, $cgi->param('cust_classnum');
257       push @search, 'cust_main.classnum IN('.join(',',@classnums).')'
258         if @classnums;
259     }
260
261     if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
262       push @search, "custnum = $1";
263     }
264
265     if ( $cgi->param('payby') ) {
266
267       my @all_payby_search = ();
268       foreach my $payby ( $cgi->param('payby') ) {
269
270         $payby =~
271           /^(CARD|CHEK|BILL|PREP|CASH|WEST|MCRD)(-(VisaMC|Amex|Discover|Maestro))?$/
272             or die "illegal payby $payby";
273
274         my $payby_search = "$table.payby = '$1'";
275
276         if ( $3 ) {
277
278           my $cardtype = $3;
279
280           my $search;
281           if ( $cardtype eq 'VisaMC' ) {
282             #avoid posix regexes for portability
283             $search =
284               " ( (     substring($table.payinfo from 1 for 1) = '4'     ".
285               "     AND substring($table.payinfo from 1 for 4) != '4936' ".
286               "     AND substring($table.payinfo from 1 for 6)           ".
287               "         NOT SIMILAR TO '49030[2-9]'                        ".
288               "     AND substring($table.payinfo from 1 for 6)           ".
289               "         NOT SIMILAR TO '49033[5-9]'                        ".
290               "     AND substring($table.payinfo from 1 for 6)           ".
291               "         NOT SIMILAR TO '49110[1-2]'                        ".
292               "     AND substring($table.payinfo from 1 for 6)           ".
293               "         NOT SIMILAR TO '49117[4-9]'                        ".
294               "     AND substring($table.payinfo from 1 for 6)           ".
295               "         NOT SIMILAR TO '49118[1-2]'                        ".
296               "   )".
297               "   OR substring($table.payinfo from 1 for 2) = '51' ".
298               "   OR substring($table.payinfo from 1 for 2) = '52' ".
299               "   OR substring($table.payinfo from 1 for 2) = '53' ".
300               "   OR substring($table.payinfo from 1 for 2) = '54' ".
301               "   OR substring($table.payinfo from 1 for 2) = '54' ".
302               "   OR substring($table.payinfo from 1 for 2) = '55' ".
303 #              "   OR substring($table.payinfo from 1 for 2) = '36' ". #Diner's int'l was processed as Visa/MC inside US, now Discover
304               " ) ";
305           } elsif ( $cardtype eq 'Amex' ) {
306             $search =
307               " (    substring($table.payinfo from 1 for 2 ) = '34' ".
308               "   OR substring($table.payinfo from 1 for 2 ) = '37' ".
309               " ) ";
310           } elsif ( $cardtype eq 'Discover' ) {
311
312             my $conf = new FS::Conf;
313             my $country = $conf->config('countrydefault') || 'US';
314
315             $search =
316               " (    substring($table.payinfo from 1 for 4 ) = '6011'  ".
317               "   OR substring($table.payinfo from 1 for 2 ) = '65'    ".
318               "   OR substring($table.payinfo from 1 for 3 ) = '300'   ".
319               "   OR substring($table.payinfo from 1 for 3 ) = '301'   ".
320               "   OR substring($table.payinfo from 1 for 3 ) = '302'   ".
321               "   OR substring($table.payinfo from 1 for 3 ) = '303'   ".
322               "   OR substring($table.payinfo from 1 for 3 ) = '304'   ".
323               "   OR substring($table.payinfo from 1 for 3 ) = '305'   ".
324               "   OR substring($table.payinfo from 1 for 4 ) = '3095'  ".
325               "   OR substring($table.payinfo from 1 for 2 ) = '36'    ".
326               "   OR substring($table.payinfo from 1 for 2 ) = '38'    ".
327               "   OR substring($table.payinfo from 1 for 2 ) = '39'    ".
328               "   OR substring($table.payinfo from 1 for 3 ) = '644'   ".
329               "   OR substring($table.payinfo from 1 for 3 ) = '645'   ".
330               "   OR substring($table.payinfo from 1 for 3 ) = '646'   ".
331               "   OR substring($table.payinfo from 1 for 3 ) = '647'   ".
332               "   OR substring($table.payinfo from 1 for 3 ) = '648'   ".
333               "   OR substring($table.payinfo from 1 for 3 ) = '649'   ".
334               ( $country =~ /^(US|CA)$/
335                ?" OR substring($table.payinfo from 1 for 4 ) = '3528'  ". # JCB cards in the 3528-3589 range identified as Discover inside US/CA
336                 " OR substring($table.payinfo from 1 for 4 ) = '3529'  ".
337                 " OR substring($table.payinfo from 1 for 3 ) = '353'   ".
338                 " OR substring($table.payinfo from 1 for 3 ) = '354'   ".
339                 " OR substring($table.payinfo from 1 for 3 ) = '355'   ".
340                 " OR substring($table.payinfo from 1 for 3 ) = '356'   ".
341                 " OR substring($table.payinfo from 1 for 3 ) = '357'   ".
342                 " OR substring($table.payinfo from 1 for 3 ) = '358'   "
343                :""
344               ).
345               "   OR substring($table.payinfo from 1 for 3 ) = '622'   ". #China Union Pay processed as Discover outside CN
346               " ) ";
347           } elsif ( $cardtype eq 'Maestro' ) { 
348             $search =
349               " (    substring($table.payinfo from 1 for 2 ) = '63'     ".
350               "   OR substring($table.payinfo from 1 for 2 ) = '67'     ".
351               "   OR substring($table.payinfo from 1 for 6 ) = '564182' ".
352               "   OR substring($table.payinfo from 1 for 4 ) = '4936'   ".
353               "   OR substring($table.payinfo from 1 for 6 )            ".
354               "      SIMILAR TO '49030[2-9]'                             ".
355               "   OR substring($table.payinfo from 1 for 6 )            ".
356               "      SIMILAR TO '49033[5-9]'                             ".
357               "   OR substring($table.payinfo from 1 for 6 )            ".
358               "      SIMILAR TO '49110[1-2]'                             ".
359               "   OR substring($table.payinfo from 1 for 6 )            ".
360               "      SIMILAR TO '49117[4-9]'                             ".
361               "   OR substring($table.payinfo from 1 for 6 )            ".
362               "      SIMILAR TO '49118[1-2]'                             ".
363               " ) ";
364           } else {
365             die "unknown card type $cardtype";
366           }
367
368           my $masksearch = $search;
369           $masksearch =~ s/$table\.payinfo/$table.paymask/gi;
370
371           $payby_search = "( $payby_search AND ( $search OR ( $table.paymask IS NOT NULL AND $masksearch ) ) )";
372
373         }
374
375         push @all_payby_search, $payby_search;
376
377       }
378
379       push @search, ' ( '. join(' OR ', @all_payby_search). ' ) ' if @all_payby_search;
380
381     }
382
383     if ( $cgi->param('payinfo') ) {
384       $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/
385         or die "illegal payinfo ". $cgi->param('payinfo');
386       push @search, "$table.payinfo = '$1'";
387     }
388
389     if ( $cgi->param('ccpay') =~ /^([\w-:]+)$/ ) {
390       # I think that's all the characters we need to allow.
391       # To avoid confusion, this parameter searches both auth and order_number.
392       push @search, "($table.auth LIKE '$1%') OR ($table.order_number LIKE '$1%')";
393       push @fields, 'auth', 'order_number';
394       push @header, 'Auth #', 'Transaction #';
395       $align .= 'rr';
396
397     }
398
399     if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
400       push @search, "$table.usernum = $1";
401     }
402
403     #for cust_pay_pending...  statusNOT=done
404     if ( $cgi->param('statusNOT') =~ /^(\w+)$/ ) {
405       push @search, "status != '$1'";
406     }
407
408     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
409 warn $beginning;
410     push @search, "_date >= $beginning ",
411                   "_date <= $ending";
412
413     if ( $table eq 'cust_pay_void' ) {
414       my($v_beginning, $v_ending) =
415         FS::UI::Web::parse_beginning_ending($cgi, 'void');
416       push @search, "void_date >= $v_beginning ",
417                     "void_date <= $v_ending";
418     }
419
420     push @search, FS::UI::Web::parse_lt_gt($cgi, $amount_field );
421
422     $orderby = '_date';
423
424   } elsif ( $cgi->param('magic') eq 'paybatch' ) {
425
426     $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/
427       or die "illegal paybatch: ". $cgi->param('paybatch');
428
429     push @search, "paybatch = '$1'";
430
431     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
432
433   } elsif ( $cgi->param('magic') eq 'batchnum' ) {
434
435     $cgi->param('batchnum') =~ /^(\d+)$/
436       or die "illegal batchnum: ".$cgi->param('batchnum');
437
438     push @search, "batchnum = $1";
439
440     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
441
442   } else {
443     die "unknown search magic: ". $cgi->param('magic');
444   }
445
446   #unapplied payment/refund
447   if ( $unapplied ) {
448     push @select, '(' . "FS::$table"->unapplied_sql . ') AS unapplied_amount';
449     push @search, "FS::$table"->unapplied_sql . ' > 0';
450
451   }
452
453   #for the history search
454   if ( $cgi->param('history_action') =~ /^([\w,]+)$/ ) {
455     my @history_action = split(/,/, $1);
456     push @search, 'history_action IN ('.
457                     join(',', map "'$_'", @history_action ). ')';
458   }
459
460   if (    $cgi->param('history_date_beginning')
461        || $cgi->param('history_date_ending')    ) {
462       my($h_beginning, $h_ending) =
463         FS::UI::Web::parse_beginning_ending($cgi, 'history_date');
464       push @search, "history_date >= $h_beginning ",
465                     "history_date <= $h_ending";
466   }
467
468   #here is the agent virtualization
469   push @search, $curuser->agentnums_sql;
470
471   my $addl_from = FS::UI::Web::join_cust_main('cust_pay');
472   my $group_by = '';
473
474   if ( $cgi->param('tax_names') ) {
475     if ( dbh->{Driver}->{Name} eq 'Pg' ) {
476
477       0;#twiddle thumbs
478
479     } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
480
481       $addl_from .= "LEFT JOIN cust_bill_pay USING ( paynum )
482                      LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
483                      LEFT JOIN cust_bill_pkg USING ( billpkgnum ) AS tax_names";
484       $group_by  .= "GROUP BY $table.*,cust_main_custnum,".
485                     FS::UI::Web::cust_sql_fields();
486       push @search,
487        "( cust_bill_pkg.pkgnum = 0 OR cust_bill_pkg.pkgnum is NULL )";
488
489     } else {
490
491       warn "warning: unknown database type ". dbh->{Driver}->{Name}.
492            "omitting tax name information from report.";
493
494     }
495   }
496
497   my $search = ' WHERE '. join(' AND ', @search);
498
499   $count_query = "SELECT COUNT(*), SUM($amount_field) ";
500   $count_query .= ', SUM(' . "FS::$table"->unapplied_sql . ') ' 
501     if $unapplied;
502   $count_query .= "FROM $table $addl_from".
503                   "$search $group_by";
504
505   @count_addl = ( '$%.2f total '.$opt{name_verb} );
506   push @count_addl, '$%.2f unapplied' if $unapplied;
507
508   $sql_query = {
509     'table'     => $table,
510     'select'    => join(', ', @select),
511     'hashref'   => {},
512     'extra_sql' => "$search $group_by",
513     'order_by'  => "ORDER BY $orderby",
514     'addl_from' => $addl_from,
515   };
516
517 } else {
518
519   #hmm... is this still used?
520
521   $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/ or die "illegal payinfo";
522   my $payinfo = $1;
523
524   $cgi->param('payby') =~ /^(\w+)$/ or die "illegal payby";
525   my $payby = $1;
526
527   $count_query = "SELECT COUNT(*), SUM($amount_field) FROM $table".
528                  "  WHERE payinfo = '$payinfo' AND payby = '$payby'".
529                  "  AND ". $curuser->agentnums_sql;
530   @count_addl = ( '$%.2f total '.$opt{name_verb} );
531
532   $sql_query = {
533     'table'     => $table,
534     'hashref'   => { 'payinfo' => $payinfo,
535                      'payby'   => $payby    },
536     'extra_sql' => $curuser->agentnums_sql.
537                    " ORDER BY _date",
538   };
539
540 }
541
542 # for consistency
543 $title = join('',map {ucfirst} split(/\b/,$title));
544
545 </%init>