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