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