filter by customer class on all financial reports, #20573
[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                 'color'          => \@color,
55                 'style'          => \@style,
56 &>
57 <%init>
58
59 my %opt = @_;
60
61 my $curuser = $FS::CurrentUser::CurrentUser;
62
63 die "access denied"
64   unless $curuser->access_right('Financial reports');
65
66 my $table = $opt{'table'} || 'cust_'.$opt{'thing'};
67
68 my $amount_field = $opt{'amount_field'};
69 my $name_singular = $opt{'name_singular'};
70
71 my $unapplied = $cgi->param('unapplied');
72 my $title = '';
73 $title = 'Unapplied ' if $unapplied;
74 $title .= "\u$name_singular Search Results";
75
76 my $link = '';
77 if (    ( $curuser->access_right('View invoices') #remove in 2.5 (2.7?)
78           || ($curuser->access_right('View payments') && $table =~ /^cust_pay/)
79           || ($curuser->access_right('View refunds') && $table eq 'cust_refund')
80         )
81      && ! $opt{'disable_link'}
82    )
83 {
84
85   my $key;
86   my $q = '';
87   if ( $table eq 'cust_pay_void' ) {
88     $key = 'paynum';
89     $q .= 'void=1;';
90   } elsif ( $table eq /^cust_(\w+)$/ ) {
91     $key = $1.'num';
92   }
93   
94   if ( $key ) {
95     $q .= "$key=";
96     $link = [ "${p}view/$table.html?$q", $key ]
97   }
98 }
99
100 my $cust_link = sub {
101   my $cust_thing = shift;
102   $cust_thing->cust_main_custnum
103     ? [ "${p}view/cust_main.cgi?", 'custnum' ] 
104     : '';
105 };
106
107 # only valid for $table == 'cust_pay' atm
108 my  $tax_names = '';
109 if ( $cgi->param('tax_names') ) {
110   if ( dbh->{Driver}->{Name} eq 'Pg' ) {
111
112     $tax_names = "
113       array_to_string(
114         array(
115           SELECT itemdesc
116             FROM cust_bill_pay
117             LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
118             LEFT JOIN cust_bill_pkg USING ( billpkgnum )
119               WHERE cust_bill_pkg.pkgnum = 0
120                 AND cust_bill_pay.paynum = cust_pay.paynum
121         ), '|'
122       ) AS tax_names"
123     ;
124
125   } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
126
127     $tax_names = "GROUP_CONCAT(itemdesc SEPARATOR '|') AS tax_names";
128
129   } else {
130
131     warn "warning: unknown database type ". dbh->{Driver}->{Name}.
132          "omitting tax name information from report.";
133
134   }
135 }
136
137 my @header = ();
138 my @fields = ();
139 my @sort_fields = ();
140 my $align = '';
141 my @links = ();
142 if ( $opt{'pre_header'} ) {
143   push @header, @{ $opt{'pre_header'} };
144   $align .= 'c' x scalar(@{ $opt{'pre_header'} });
145   push @links, map '', @{ $opt{'pre_header'} };
146   push @fields, @{ $opt{'pre_fields'} };
147   push @sort_fields, @{ $opt{'pre_fields'} };
148 }
149
150 push @header, "\u$name_singular",
151               'Amount',
152 ;
153 $align .= 'rr';
154 push @links, '', '';
155 push @fields, 'payby_payinfo_pretty',
156               sub { sprintf('$%.2f', shift->$amount_field() ) },
157 ;
158 push @sort_fields, '', $amount_field;
159
160 if ( $unapplied ) {
161   push @header, emt('Unapplied');
162   $align .= 'r';
163   push @links, '';
164   push @fields, sub { sprintf('$%.2f', shift->unapplied_amount) };
165   push @sort_fields, '';
166 }
167
168 push @header, emt('Date');
169 $align .= 'r';
170 push @links, '';
171 push @fields, sub { time2str('%b %d %Y', shift->_date ) };
172 push @sort_fields, '_date';
173
174 unless ( $opt{'disable_by'} ) {
175   push @header, emt('By');
176   $align .= 'c';
177   push @links, '';
178   push @fields, sub { my $o = shift->otaker;
179                       $o = 'auto billing'          if $o eq 'fs_daily';
180                       $o = 'customer self-service' if $o eq 'fs_selfservice';
181                       $o;
182                     };
183 }
184
185 if ( $tax_names ) {
186   push @header, (emt('Tax names'), emt('Tax province'));
187   $align .= 'cc';
188   push @links, ('','');
189   push @fields, sub { join (' + ', map { /^(.*?)(, \w\w)?$/; $1 }
190                                    split('\|', shift->tax_names)
191                            );
192                     };
193   push @fields, sub { join (' + ', map { if (/^(?:.*)(?:, )(\w\w)$/){ $1 }
194                                          else { () }
195                                        }
196                                    split('\|', shift->tax_names)
197                            );
198                     };
199 }
200
201 push @header, FS::UI::Web::cust_header();
202 $align .=  FS::UI::Web::cust_aligns();
203 push @links, map { $_ ne 'Cust. Status' ? $cust_link : '' }
204                  FS::UI::Web::cust_header();
205 my @color = ( ( map '', @fields ), FS::UI::Web::cust_colors() );
206 my @style = ( ( map '', @fields ), FS::UI::Web::cust_styles() );
207 push @fields, \&FS::UI::Web::cust_fields;
208
209 push @header, @{ $opt{'addl_header'} }
210   if $opt{'addl_header'};
211 push @fields, @{ $opt{'addl_fields'} }
212   if $opt{'addl_fields'};
213
214 my( $count_query, $sql_query, @count_addl );
215 if ( $cgi->param('magic') ) {
216
217   my @search = ();
218   my @select = (
219     "$table.*",
220     FS::UI::Web::cust_sql_fields(),
221     'cust_main.custnum AS cust_main_custnum',
222   );
223   push @select, $tax_names if $tax_names;
224
225   my $orderby;
226   if ( $cgi->param('magic') eq '_date' ) {
227
228     if ( $cgi->param('agentnum') && $cgi->param('agentnum') =~ /^(\d+)$/ ) {
229       push @search, "agentnum = $1"; # $search{'agentnum'} = $1;
230       my $agent = qsearchs('agent', { 'agentnum' => $1 } );
231       die "unknown agentnum $1" unless $agent;
232       $title = $agent->agent. " $title";
233     }
234
235     if ( $cgi->param('refnum') && $cgi->param('refnum') =~ /^(\d+)$/ ) {
236       push @search, "refnum = $1";
237       my $part_referral = qsearchs('part_referral', { 'refnum' => $1 } );
238       die "unknown refnum $1" unless $part_referral;
239       $title = $part_referral->referral. " $title";
240     }
241
242     if ( $cgi->param('cust_classnum') ) {
243       my @classnums = grep /^\d+$/, $cgi->param('cust_classnum');
244       push @search, 'cust_main.classnum IN('.join(',',@classnums).')'
245         if @classnums;
246     }
247
248     if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
249       push @search, "custnum = $1";
250     }
251
252     if ( $cgi->param('payby') ) {
253       $cgi->param('payby') =~
254         /^(CARD|CHEK|BILL|PREP|CASH|WEST|MCRD)(-(VisaMC|Amex|Discover|Maestro))?$/
255           or die "illegal payby ". $cgi->param('payby');
256       push @search, "$table.payby = '$1'";
257       if ( $3 ) {
258
259         my $cardtype = $3;
260
261         my $search;
262         if ( $cardtype eq 'VisaMC' ) {
263           #avoid posix regexes for portability
264           $search =
265             " ( (     substring($table.payinfo from 1 for 1) = '4'     ".
266             "     AND substring($table.payinfo from 1 for 4) != '4936' ".
267             "     AND substring($table.payinfo from 1 for 6)           ".
268             "         NOT SIMILAR TO '49030[2-9]'                        ".
269             "     AND substring($table.payinfo from 1 for 6)           ".
270             "         NOT SIMILAR TO '49033[5-9]'                        ".
271             "     AND substring($table.payinfo from 1 for 6)           ".
272             "         NOT SIMILAR TO '49110[1-2]'                        ".
273             "     AND substring($table.payinfo from 1 for 6)           ".
274             "         NOT SIMILAR TO '49117[4-9]'                        ".
275             "     AND substring($table.payinfo from 1 for 6)           ".
276             "         NOT SIMILAR TO '49118[1-2]'                        ".
277             "   )".
278             "   OR substring($table.payinfo from 1 for 2) = '51' ".
279             "   OR substring($table.payinfo from 1 for 2) = '52' ".
280             "   OR substring($table.payinfo from 1 for 2) = '53' ".
281             "   OR substring($table.payinfo from 1 for 2) = '54' ".
282             "   OR substring($table.payinfo from 1 for 2) = '54' ".
283             "   OR substring($table.payinfo from 1 for 2) = '55' ".
284             "   OR substring($table.payinfo from 1 for 2) = '36' ". #Diner's int'l processed as Visa/MC inside US
285             " ) ";
286         } elsif ( $cardtype eq 'Amex' ) {
287           $search =
288             " (    substring($table.payinfo from 1 for 2 ) = '34' ".
289             "   OR substring($table.payinfo from 1 for 2 ) = '37' ".
290             " ) ";
291         } elsif ( $cardtype eq 'Discover' ) {
292           $search =
293             " (    substring($table.payinfo from 1 for 4 ) = '6011'  ".
294             "   OR substring($table.payinfo from 1 for 2 ) = '65'    ".
295             "   OR substring($table.payinfo from 1 for 3 ) = '622'   ". #China Union Pay processed as Discover outside CN
296             " ) ";
297         } elsif ( $cardtype eq 'Maestro' ) { 
298           $search =
299             " (    substring($table.payinfo from 1 for 2 ) = '63'     ".
300             "   OR substring($table.payinfo from 1 for 2 ) = '67'     ".
301             "   OR substring($table.payinfo from 1 for 6 ) = '564182' ".
302             "   OR substring($table.payinfo from 1 for 4 ) = '4936'   ".
303             "   OR substring($table.payinfo from 1 for 6 )            ".
304             "      SIMILAR TO '49030[2-9]'                             ".
305             "   OR substring($table.payinfo from 1 for 6 )            ".
306             "      SIMILAR TO '49033[5-9]'                             ".
307             "   OR substring($table.payinfo from 1 for 6 )            ".
308             "      SIMILAR TO '49110[1-2]'                             ".
309             "   OR substring($table.payinfo from 1 for 6 )            ".
310             "      SIMILAR TO '49117[4-9]'                             ".
311             "   OR substring($table.payinfo from 1 for 6 )            ".
312             "      SIMILAR TO '49118[1-2]'                             ".
313             " ) ";
314         } else {
315           die "unknown card type $cardtype";
316         }
317
318         my $masksearch = $search;
319         $masksearch =~ s/$table\.payinfo/$table.paymask/gi;
320
321         push @search,
322           "( $search OR ( $table.paymask IS NOT NULL AND $masksearch ) )";
323
324       }
325     }
326
327     if ( $cgi->param('payinfo') ) {
328       $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/
329         or die "illegal payinfo ". $cgi->param('payinfo');
330       push @search, "$table.payinfo = '$1'";
331     }
332
333     if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
334       push @search, "$table.usernum = $1";
335     }
336
337     #for cust_pay_pending...  statusNOT=done
338     if ( $cgi->param('statusNOT') =~ /^(\w+)$/ ) {
339       push @search, "status != '$1'";
340     }
341
342     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
343     push @search, "_date >= $beginning ",
344                   "_date <= $ending";
345
346     if ( $table eq 'cust_pay_void' ) {
347       my($v_beginning, $v_ending) =
348         FS::UI::Web::parse_beginning_ending($cgi, 'void');
349       push @search, "void_date >= $v_beginning ",
350                     "void_date <= $v_ending";
351     }
352
353     push @search, FS::UI::Web::parse_lt_gt($cgi, $amount_field );
354
355     $orderby = '_date';
356
357   } elsif ( $cgi->param('magic') eq 'paybatch' ) {
358
359     $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/
360       or die "illegal paybatch: ". $cgi->param('paybatch');
361
362     push @search, "paybatch = '$1'";
363
364     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
365
366   } elsif ( $cgi->param('magic') eq 'batchnum' ) {
367
368     $cgi->param('batchnum') =~ /^(\d+)$/
369       or die "illegal batchnum: ".$cgi->param('batchnum');
370
371     push @search, "batchnum = $1";
372
373     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
374
375   } else {
376     die "unknown search magic: ". $cgi->param('magic');
377   }
378
379   #unapplied payment/refund
380   if ( $unapplied ) {
381     push @select, '(' . "FS::$table"->unapplied_sql . ') AS unapplied_amount';
382     push @search, "FS::$table"->unapplied_sql . ' > 0';
383
384   }
385
386   #for the history search
387   if ( $cgi->param('history_action') =~ /^([\w,]+)$/ ) {
388     my @history_action = split(/,/, $1);
389     push @search, 'history_action IN ('.
390                     join(',', map "'$_'", @history_action ). ')';
391   }
392
393   if (    $cgi->param('history_date_beginning')
394        || $cgi->param('history_date_ending')    ) {
395       my($h_beginning, $h_ending) =
396         FS::UI::Web::parse_beginning_ending($cgi, 'history_date');
397       push @search, "history_date >= $h_beginning ",
398                     "history_date <= $h_ending";
399   }
400
401   #here is the agent virtualization
402   push @search, $curuser->agentnums_sql;
403
404   my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
405   my $group_by = '';
406
407   if ( $cgi->param('tax_names') ) {
408     if ( dbh->{Driver}->{Name} eq 'Pg' ) {
409
410       0;#twiddle thumbs
411
412     } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
413
414       $addl_from .= "LEFT JOIN cust_bill_pay USING ( paynum )
415                      LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
416                      LEFT JOIN cust_bill_pkg USING ( billpkgnum ) AS tax_names";
417       $group_by  .= "GROUP BY $table.*,cust_main_custnum,".
418                     FS::UI::Web::cust_sql_fields();
419       push @search,
420        "( cust_bill_pkg.pkgnum = 0 OR cust_bill_pkg.pkgnum is NULL )";
421
422     } else {
423
424       warn "warning: unknown database type ". dbh->{Driver}->{Name}.
425            "omitting tax name information from report.";
426
427     }
428   }
429
430   my $search = ' WHERE '. join(' AND ', @search);
431
432   $count_query = "SELECT COUNT(*), SUM($amount_field) ";
433   $count_query .= ', SUM(' . "FS::$table"->unapplied_sql . ') ' 
434     if $unapplied;
435   $count_query .= "FROM $table $addl_from".
436                   "$search $group_by";
437
438   @count_addl = ( '$%.2f total '.$opt{name_verb} );
439   push @count_addl, '$%.2f unapplied' if $unapplied;
440
441   $sql_query = {
442     'table'     => $table,
443     'select'    => join(', ', @select),
444     'hashref'   => {},
445     'extra_sql' => "$search $group_by",
446     'order_by'  => "ORDER BY $orderby",
447     'addl_from' => $addl_from,
448   };
449
450 } else {
451
452   #hmm... is this still used?
453
454   $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/ or die "illegal payinfo";
455   my $payinfo = $1;
456
457   $cgi->param('payby') =~ /^(\w+)$/ or die "illegal payby";
458   my $payby = $1;
459
460   $count_query = "SELECT COUNT(*), SUM($amount_field) FROM $table".
461                  "  WHERE payinfo = '$payinfo' AND payby = '$payby'".
462                  "  AND ". $curuser->agentnums_sql;
463   @count_addl = ( '$%.2f total '.$opt{name_verb} );
464
465   $sql_query = {
466     'table'     => $table,
467     'hashref'   => { 'payinfo' => $payinfo,
468                      'payby'   => $payby    },
469     'extra_sql' => $curuser->agentnums_sql.
470                    " ORDER BY _date",
471   };
472
473 }
474
475 # for consistency
476 $title = join('',map {ucfirst} split(/\b/,$title));
477
478 </%init>