Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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 ( $unapplied ) {
188   push @header, emt('Unapplied');
189   $align .= 'r';
190   push @links, '';
191   push @fields, sub { sprintf($money, shift->unapplied_amount) };
192   push @sort_fields, '';
193 }
194
195 push @header, emt('Date');
196 $align .= 'r';
197 push @links, '';
198 push @fields, sub { time2str('%b %d %Y', shift->_date ) };
199 push @sort_fields, '_date';
200
201 unless ( $opt{'disable_by'} ) {
202   push @header, emt('By');
203   $align .= 'c';
204   push @links, '';
205   push @fields, sub { my $o = shift->otaker;
206                       $o = 'auto billing'          if $o eq 'fs_daily';
207                       $o = 'customer self-service' if $o eq 'fs_selfservice';
208                       $o;
209                     };
210 }
211
212 if ( $tax_names ) {
213   push @header, (emt('Tax names'), emt('Tax province'));
214   $align .= 'cc';
215   push @links, ('','');
216   push @fields, sub { join (' + ', map { /^(.*?)(, \w\w)?$/; $1 }
217                                    split('\|', shift->tax_names)
218                            );
219                     };
220   push @fields, sub { join (' + ', map { if (/^(?:.*)(?:, )(\w\w)$/){ $1 }
221                                          else { () }
222                                        }
223                                    split('\|', shift->tax_names)
224                            );
225                     };
226 }
227
228 push @header, FS::UI::Web::cust_header();
229 $align .=  FS::UI::Web::cust_aligns();
230 push @links, map { $_ ne 'Cust. Status' ? $cust_link : '' }
231                  FS::UI::Web::cust_header();
232 my @color = ( ( map '', @fields ), FS::UI::Web::cust_colors() );
233 my @style = ( ( map '', @fields ), FS::UI::Web::cust_styles() );
234 push @fields, \&FS::UI::Web::cust_fields;
235
236 push @header, @{ $opt{'addl_header'} }
237   if $opt{'addl_header'};
238 push @fields, @{ $opt{'addl_fields'} }
239   if $opt{'addl_fields'};
240
241 my( $count_query, $sql_query, @count_addl );
242 if ( $cgi->param('magic') ) {
243
244   my @search = ();
245   my @select = (
246     "$table.*",
247     "( $table.payby || ' ' || coalesce($table.paymask, $table.payinfo) ) AS paysort",
248     FS::UI::Web::cust_sql_fields(),
249     'cust_main.custnum AS cust_main_custnum',
250   );
251   push @select, $tax_names if $tax_names;
252
253   my $orderby;
254   if ( $cgi->param('magic') eq '_date' ) {
255
256     if ( $cgi->param('agentnum') && $cgi->param('agentnum') =~ /^(\d+)$/ ) {
257       push @search, "cust_main.agentnum = $1"; # $search{'agentnum'} = $1;
258       my $agent = qsearchs('agent', { 'agentnum' => $1 } );
259       die "unknown agentnum $1" unless $agent;
260       $title = $agent->agent. " $title";
261     }
262
263     if ( $cgi->param('refnum') && $cgi->param('refnum') =~ /^(\d+)$/ ) {
264       push @search, "cust_main.refnum = $1";
265       my $part_referral = qsearchs('part_referral', { 'refnum' => $1 } );
266       die "unknown refnum $1" unless $part_referral;
267       $title = $part_referral->referral. " $title";
268     }
269
270     # cust_classnum - standard matching
271     push @search, $m->comp('match-classnum',
272         param => 'cust_classnum', field => 'cust_main.classnum'
273       );
274
275     if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
276       push @search, "$table.custnum = $1";
277     }
278
279     if ( $cgi->param('payby') ) {
280
281       my @all_payby_search = ();
282       foreach my $payby ( $cgi->param('payby') ) {
283
284         $payby =~
285           /^(CARD|CHEK|BILL|CASH|PPAL|APPL|ANRD|PREP|WIRE|WEST|EDI|MCRD|MCHK)(-(VisaMC|Amex|Discover|Maestro|Tokenized))?$/
286             or die "illegal payby $payby";
287
288         my $payby_search = "$table.payby = '$1'";
289
290         if ( $3 ) {
291
292           my $cardtype = $3;
293
294           my $similar_to = dbh->{Driver}->{Name} =~ /^mysql/i
295                              ? 'REGEXP' #doesn't behave exactly the same, but
296                                         #should work for our patterns
297                              : 'SIMILAR TO';
298
299           my $search;
300           if ( $cardtype eq 'VisaMC' ) {
301
302             #avoid posix regexes for portability
303             $search =
304               " ( (     substring($table.payinfo from 1 for 1) = '4'     ".
305               "     AND substring($table.payinfo from 1 for 4) != '4936' ".
306               "     AND substring($table.payinfo from 1 for 6)           ".
307               "         NOT $similar_to '49030[2-9]'                        ".
308               "     AND substring($table.payinfo from 1 for 6)           ".
309               "         NOT $similar_to '49033[5-9]'                        ".
310               "     AND substring($table.payinfo from 1 for 6)           ".
311               "         NOT $similar_to '49110[1-2]'                        ".
312               "     AND substring($table.payinfo from 1 for 6)           ".
313               "         NOT $similar_to '49117[4-9]'                        ".
314               "     AND substring($table.payinfo from 1 for 6)           ".
315               "         NOT $similar_to '49118[1-2]'                        ".
316               "   )".
317               "   OR substring($table.payinfo from 1 for 2) = '51' ".
318               "   OR substring($table.payinfo from 1 for 2) = '52' ".
319               "   OR substring($table.payinfo from 1 for 2) = '53' ".
320               "   OR substring($table.payinfo from 1 for 2) = '54' ".
321               "   OR substring($table.payinfo from 1 for 2) = '54' ".
322               "   OR substring($table.payinfo from 1 for 2) = '55' ".
323 #              "   OR substring($table.payinfo from 1 for 2) = '36' ". #Diner's int'l was processed as Visa/MC inside US, now Discover
324               " ) ";
325
326           } elsif ( $cardtype eq 'Amex' ) {
327
328             $search =
329               " (    substring($table.payinfo from 1 for 2 ) = '34' ".
330               "   OR substring($table.payinfo from 1 for 2 ) = '37' ".
331               " ) ";
332
333           } elsif ( $cardtype eq 'Discover' ) {
334
335             my $country = $conf->config('countrydefault') || 'US';
336
337             $search =
338               " (    substring($table.payinfo from 1 for 4 ) = '6011'  ".
339               "   OR substring($table.payinfo from 1 for 2 ) = '65'    ".
340               "   OR substring($table.payinfo from 1 for 3 ) = '300'   ".
341               "   OR substring($table.payinfo from 1 for 3 ) = '301'   ".
342               "   OR substring($table.payinfo from 1 for 3 ) = '302'   ".
343               "   OR substring($table.payinfo from 1 for 3 ) = '303'   ".
344               "   OR substring($table.payinfo from 1 for 3 ) = '304'   ".
345               "   OR substring($table.payinfo from 1 for 3 ) = '305'   ".
346               "   OR substring($table.payinfo from 1 for 4 ) = '3095'  ".
347               "   OR substring($table.payinfo from 1 for 2 ) = '36'    ".
348               "   OR substring($table.payinfo from 1 for 2 ) = '38'    ".
349               "   OR substring($table.payinfo from 1 for 2 ) = '39'    ".
350               "   OR substring($table.payinfo from 1 for 3 ) = '644'   ".
351               "   OR substring($table.payinfo from 1 for 3 ) = '645'   ".
352               "   OR substring($table.payinfo from 1 for 3 ) = '646'   ".
353               "   OR substring($table.payinfo from 1 for 3 ) = '647'   ".
354               "   OR substring($table.payinfo from 1 for 3 ) = '648'   ".
355               "   OR substring($table.payinfo from 1 for 3 ) = '649'   ".
356               ( $country =~ /^(US|CA)$/
357                ?" OR substring($table.payinfo from 1 for 4 ) = '3528'  ". # JCB cards in the 3528-3589 range identified as Discover inside US/CA
358                 " OR substring($table.payinfo from 1 for 4 ) = '3529'  ".
359                 " OR substring($table.payinfo from 1 for 3 ) = '353'   ".
360                 " OR substring($table.payinfo from 1 for 3 ) = '354'   ".
361                 " OR substring($table.payinfo from 1 for 3 ) = '355'   ".
362                 " OR substring($table.payinfo from 1 for 3 ) = '356'   ".
363                 " OR substring($table.payinfo from 1 for 3 ) = '357'   ".
364                 " OR substring($table.payinfo from 1 for 3 ) = '358'   "
365                :""
366               ).
367               "   OR substring($table.payinfo from 1 for 3 ) = '622'   ". #China Union Pay processed as Discover outside CN
368               " ) ";
369
370           } elsif ( $cardtype eq 'Maestro' ) {
371
372             $search =
373               " (    substring($table.payinfo from 1 for 2 ) = '63'     ".
374               "   OR substring($table.payinfo from 1 for 2 ) = '67'     ".
375               "   OR substring($table.payinfo from 1 for 6 ) = '564182' ".
376               "   OR substring($table.payinfo from 1 for 4 ) = '4936'   ".
377               "   OR substring($table.payinfo from 1 for 6 )            ".
378               "      $similar_to '49030[2-9]'                             ".
379               "   OR substring($table.payinfo from 1 for 6 )            ".
380               "      $similar_to '49033[5-9]'                             ".
381               "   OR substring($table.payinfo from 1 for 6 )            ".
382               "      $similar_to '49110[1-2]'                             ".
383               "   OR substring($table.payinfo from 1 for 6 )            ".
384               "      $similar_to '49117[4-9]'                             ".
385               "   OR substring($table.payinfo from 1 for 6 )            ".
386               "      $similar_to '49118[1-2]'                             ".
387               " ) ";
388
389           } elsif ( $cardtype eq 'Tokenized' ) {
390
391             $search = " substring($table.payinfo from 1 for 2 ) = '99' ";
392
393           } else {
394             die "unknown card type $cardtype";
395           }
396
397           my $masksearch = $search;
398           $masksearch =~ s/$table\.payinfo/$table.paymask/gi;
399
400           $payby_search = "( $payby_search AND ( $search OR ( $table.paymask IS NOT NULL AND $masksearch ) ) )";
401
402         }
403
404         push @all_payby_search, $payby_search;
405
406       }
407
408       push @search, ' ( '. join(' OR ', @all_payby_search). ' ) ' if @all_payby_search;
409
410     }
411
412     if ( $cgi->param('payinfo') ) {
413       $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/
414         or die "illegal payinfo ". $cgi->param('payinfo');
415       my $regexp = regexp_sql();
416       push @search, "$table.payinfo $regexp '^0*$1\$'";
417     }
418
419     if ( $cgi->param('ccpay') =~ /^([\w-:]+)$/ ) {
420       # I think that's all the characters we need to allow.
421       # To avoid confusion, this parameter searches both auth and order_number.
422       push @search, "($table.auth LIKE '$1%') OR ($table.order_number LIKE '$1%')";
423       push @fields, 'auth', 'order_number';
424       push @header, 'Auth #', 'Transaction #';
425       $align .= 'rr';
426
427     }
428
429     if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
430       push @search, "$table.usernum = $1";
431     }
432
433     #for cust_pay_pending...  statusNOT=done
434     if ( $cgi->param('statusNOT') =~ /^(\w+)$/ ) {
435       push @search, "$table.status != '$1'";
436     }
437
438     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
439
440     push @search, "$table._date >= $beginning ",
441                   "$table._date <= $ending";
442
443     if ( $table eq 'cust_pay_void' ) {
444       my($v_beginning, $v_ending) =
445         FS::UI::Web::parse_beginning_ending($cgi, 'void');
446       push @search, "$table.void_date >= $v_beginning ",
447                     "$table.void_date <= $v_ending";
448     }
449
450     push @search, FS::UI::Web::parse_lt_gt($cgi, $amount_field, $table);
451
452     $orderby = '_date';
453
454   } elsif ( $cgi->param('magic') eq 'paybatch' ) {
455
456     $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/
457       or die "illegal paybatch: ". $cgi->param('paybatch');
458
459     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
460
461   } elsif ( $cgi->param('magic') eq 'batchnum' ) {
462
463     $cgi->param('batchnum') =~ /^(\d+)$/
464       or die "illegal batchnum: ".$cgi->param('batchnum');
465
466     push @search, "batchnum = $1";
467
468     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
469
470   } else {
471     die "unknown search magic: ". $cgi->param('magic');
472   }
473
474   if ( $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/ ) {
475     push @search, "paybatch = '$1'";
476   }
477
478   #unapplied payment/refund
479   if ( $unapplied ) {
480     push @select, '(' . "FS::$table"->unapplied_sql . ') AS unapplied_amount';
481     push @search, "FS::$table"->unapplied_sql . ' > 0';
482
483   }
484
485   #for the history search
486   if ( $cgi->param('history_action') =~ /^([\w,]+)$/ ) {
487     my @history_action = split(/,/, $1);
488     push @search, 'history_action IN ('.
489                     join(',', map "'$_'", @history_action ). ')';
490   }
491
492   if (    $cgi->param('history_date_beginning')
493        || $cgi->param('history_date_ending')    ) {
494       my($h_beginning, $h_ending) =
495         FS::UI::Web::parse_beginning_ending($cgi, 'history_date');
496       push @search, "history_date >= $h_beginning ",
497                     "history_date <= $h_ending";
498   }
499
500   #here is the agent virtualization
501   push @search, $curuser->agentnums_sql;
502
503   my $addl_from = FS::UI::Web::join_cust_main($table);
504   my $group_by = '';
505
506   if ( $cgi->param('tax_names') ) {
507     if ( dbh->{Driver}->{Name} =~ /^Pg/i ) {
508
509       0;#twiddle thumbs
510
511     } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
512
513       $addl_from .= "LEFT JOIN cust_bill_pay USING ( paynum )
514                      LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
515                      LEFT JOIN cust_bill_pkg USING ( billpkgnum ) AS tax_names";
516       $group_by  .= "GROUP BY $table.*,cust_main_custnum,".
517                     FS::UI::Web::cust_sql_fields();
518       push @search,
519        "( cust_bill_pkg.pkgnum = 0 OR cust_bill_pkg.pkgnum is NULL )";
520
521     } else {
522
523       warn "warning: unknown database type ". dbh->{Driver}->{Name}.
524            "omitting tax name information from report.";
525
526     }
527   }
528
529   my $search = ' WHERE '. join(' AND ', @search);
530
531   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) ";
532   $count_query .= ', SUM(' . "FS::$table"->unapplied_sql . ') ' 
533     if $unapplied;
534   $count_query .= "FROM $table $addl_from".
535                   "$search $group_by";
536
537   @count_addl = ( '$%.2f total '.$opt{name_verb} );
538   push @count_addl, '$%.2f unapplied' if $unapplied;
539
540   $sql_query = {
541     'table'     => $table,
542     'select'    => join(', ', @select),
543     'hashref'   => {},
544     'extra_sql' => "$search $group_by",
545     'order_by'  => "ORDER BY $orderby",
546     'addl_from' => $addl_from,
547   };
548
549 } else {
550
551   #hmm... is this still used?
552   warn "undefined search magic";
553
554   $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/ or die "illegal payinfo";
555   my $payinfo = $1;
556
557   $cgi->param('payby') =~ /^(\w+)$/ or die "illegal payby";
558   my $payby = $1;
559
560   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) FROM $table".
561                  "  WHERE payinfo = '$payinfo' AND payby = '$payby'".
562                  "  AND ". $curuser->agentnums_sql;
563   @count_addl = ( '$%.2f total '.$opt{name_verb} );
564
565   $sql_query = {
566     'table'     => $table,
567     'hashref'   => { 'payinfo' => $payinfo,
568                      'payby'   => $payby    },
569     'extra_sql' => $curuser->agentnums_sql.
570                    " ORDER BY _date",
571   };
572
573 }
574
575 # for consistency
576 $title = join('',map {ucfirst} split(/\b/,$title));
577
578 </%init>