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