customer location columns in more reports, #940
[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     if ( $cgi->param('cust_classnum') ) {
256       my @classnums = grep /^\d+$/, $cgi->param('cust_classnum');
257       push @search, 'cust_main.classnum IN('.join(',',@classnums).')'
258         if @classnums;
259     }
260
261     if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
262       push @search, "custnum = $1";
263     }
264
265     if ( $cgi->param('payby') ) {
266       $cgi->param('payby') =~
267         /^(CARD|CHEK|BILL|PREP|CASH|WEST|MCRD)(-(VisaMC|Amex|Discover|Maestro))?$/
268           or die "illegal payby ". $cgi->param('payby');
269       push @search, "$table.payby = '$1'";
270       if ( $3 ) {
271
272         my $cardtype = $3;
273
274         my $search;
275         if ( $cardtype eq 'VisaMC' ) {
276           #avoid posix regexes for portability
277           $search =
278             " ( (     substring($table.payinfo from 1 for 1) = '4'     ".
279             "     AND substring($table.payinfo from 1 for 4) != '4936' ".
280             "     AND substring($table.payinfo from 1 for 6)           ".
281             "         NOT SIMILAR TO '49030[2-9]'                        ".
282             "     AND substring($table.payinfo from 1 for 6)           ".
283             "         NOT SIMILAR TO '49033[5-9]'                        ".
284             "     AND substring($table.payinfo from 1 for 6)           ".
285             "         NOT SIMILAR TO '49110[1-2]'                        ".
286             "     AND substring($table.payinfo from 1 for 6)           ".
287             "         NOT SIMILAR TO '49117[4-9]'                        ".
288             "     AND substring($table.payinfo from 1 for 6)           ".
289             "         NOT SIMILAR TO '49118[1-2]'                        ".
290             "   )".
291             "   OR substring($table.payinfo from 1 for 2) = '51' ".
292             "   OR substring($table.payinfo from 1 for 2) = '52' ".
293             "   OR substring($table.payinfo from 1 for 2) = '53' ".
294             "   OR substring($table.payinfo from 1 for 2) = '54' ".
295             "   OR substring($table.payinfo from 1 for 2) = '54' ".
296             "   OR substring($table.payinfo from 1 for 2) = '55' ".
297             "   OR substring($table.payinfo from 1 for 2) = '36' ". #Diner's int'l processed as Visa/MC inside US
298             " ) ";
299         } elsif ( $cardtype eq 'Amex' ) {
300           $search =
301             " (    substring($table.payinfo from 1 for 2 ) = '34' ".
302             "   OR substring($table.payinfo from 1 for 2 ) = '37' ".
303             " ) ";
304         } elsif ( $cardtype eq 'Discover' ) {
305           $search =
306             " (    substring($table.payinfo from 1 for 4 ) = '6011'  ".
307             "   OR substring($table.payinfo from 1 for 2 ) = '65'    ".
308             "   OR substring($table.payinfo from 1 for 3 ) = '622'   ". #China Union Pay processed as Discover outside CN
309             " ) ";
310         } elsif ( $cardtype eq 'Maestro' ) { 
311           $search =
312             " (    substring($table.payinfo from 1 for 2 ) = '63'     ".
313             "   OR substring($table.payinfo from 1 for 2 ) = '67'     ".
314             "   OR substring($table.payinfo from 1 for 6 ) = '564182' ".
315             "   OR substring($table.payinfo from 1 for 4 ) = '4936'   ".
316             "   OR substring($table.payinfo from 1 for 6 )            ".
317             "      SIMILAR TO '49030[2-9]'                             ".
318             "   OR substring($table.payinfo from 1 for 6 )            ".
319             "      SIMILAR TO '49033[5-9]'                             ".
320             "   OR substring($table.payinfo from 1 for 6 )            ".
321             "      SIMILAR TO '49110[1-2]'                             ".
322             "   OR substring($table.payinfo from 1 for 6 )            ".
323             "      SIMILAR TO '49117[4-9]'                             ".
324             "   OR substring($table.payinfo from 1 for 6 )            ".
325             "      SIMILAR TO '49118[1-2]'                             ".
326             " ) ";
327         } else {
328           die "unknown card type $cardtype";
329         }
330
331         my $masksearch = $search;
332         $masksearch =~ s/$table\.payinfo/$table.paymask/gi;
333
334         push @search,
335           "( $search OR ( $table.paymask IS NOT NULL AND $masksearch ) )";
336
337       }
338     }
339
340     if ( $cgi->param('payinfo') ) {
341       $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/
342         or die "illegal payinfo ". $cgi->param('payinfo');
343       push @search, "$table.payinfo = '$1'";
344     }
345
346     if ( $cgi->param('ccpay') =~ /^([\w-:]+)$/ ) {
347       # I think that's all the characters we need to allow.
348       # To avoid confusion, this parameter searches both auth and order_number.
349       push @search, "($table.auth LIKE '$1%') OR ($table.order_number LIKE '$1%')";
350       push @fields, 'auth', 'order_number';
351       push @header, 'Auth #', 'Transaction #';
352       $align .= 'rr';
353
354     }
355
356     if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
357       push @search, "$table.usernum = $1";
358     }
359
360     #for cust_pay_pending...  statusNOT=done
361     if ( $cgi->param('statusNOT') =~ /^(\w+)$/ ) {
362       push @search, "status != '$1'";
363     }
364
365     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
366     push @search, "_date >= $beginning ",
367                   "_date <= $ending";
368
369     if ( $table eq 'cust_pay_void' ) {
370       my($v_beginning, $v_ending) =
371         FS::UI::Web::parse_beginning_ending($cgi, 'void');
372       push @search, "void_date >= $v_beginning ",
373                     "void_date <= $v_ending";
374     }
375
376     push @search, FS::UI::Web::parse_lt_gt($cgi, $amount_field );
377
378     $orderby = '_date';
379
380   } elsif ( $cgi->param('magic') eq 'paybatch' ) {
381
382     $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/
383       or die "illegal paybatch: ". $cgi->param('paybatch');
384
385     push @search, "paybatch = '$1'";
386
387     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
388
389   } elsif ( $cgi->param('magic') eq 'batchnum' ) {
390
391     $cgi->param('batchnum') =~ /^(\d+)$/
392       or die "illegal batchnum: ".$cgi->param('batchnum');
393
394     push @search, "batchnum = $1";
395
396     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
397
398   } else {
399     die "unknown search magic: ". $cgi->param('magic');
400   }
401
402   #unapplied payment/refund
403   if ( $unapplied ) {
404     push @select, '(' . "FS::$table"->unapplied_sql . ') AS unapplied_amount';
405     push @search, "FS::$table"->unapplied_sql . ' > 0';
406
407   }
408
409   #for the history search
410   if ( $cgi->param('history_action') =~ /^([\w,]+)$/ ) {
411     my @history_action = split(/,/, $1);
412     push @search, 'history_action IN ('.
413                     join(',', map "'$_'", @history_action ). ')';
414   }
415
416   if (    $cgi->param('history_date_beginning')
417        || $cgi->param('history_date_ending')    ) {
418       my($h_beginning, $h_ending) =
419         FS::UI::Web::parse_beginning_ending($cgi, 'history_date');
420       push @search, "history_date >= $h_beginning ",
421                     "history_date <= $h_ending";
422   }
423
424   #here is the agent virtualization
425   push @search, $curuser->agentnums_sql;
426
427   my $addl_from = FS::UI::Web::join_cust_main('cust_pay');
428   my $group_by = '';
429
430   if ( $cgi->param('tax_names') ) {
431     if ( dbh->{Driver}->{Name} eq 'Pg' ) {
432
433       0;#twiddle thumbs
434
435     } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
436
437       $addl_from .= "LEFT JOIN cust_bill_pay USING ( paynum )
438                      LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
439                      LEFT JOIN cust_bill_pkg USING ( billpkgnum ) AS tax_names";
440       $group_by  .= "GROUP BY $table.*,cust_main_custnum,".
441                     FS::UI::Web::cust_sql_fields();
442       push @search,
443        "( cust_bill_pkg.pkgnum = 0 OR cust_bill_pkg.pkgnum is NULL )";
444
445     } else {
446
447       warn "warning: unknown database type ". dbh->{Driver}->{Name}.
448            "omitting tax name information from report.";
449
450     }
451   }
452
453   my $search = ' WHERE '. join(' AND ', @search);
454
455   $count_query = "SELECT COUNT(*), SUM($amount_field) ";
456   $count_query .= ', SUM(' . "FS::$table"->unapplied_sql . ') ' 
457     if $unapplied;
458   $count_query .= "FROM $table $addl_from".
459                   "$search $group_by";
460
461   @count_addl = ( '$%.2f total '.$opt{name_verb} );
462   push @count_addl, '$%.2f unapplied' if $unapplied;
463
464   $sql_query = {
465     'table'     => $table,
466     'select'    => join(', ', @select),
467     'hashref'   => {},
468     'extra_sql' => "$search $group_by",
469     'order_by'  => "ORDER BY $orderby",
470     'addl_from' => $addl_from,
471   };
472
473 } else {
474
475   #hmm... is this still used?
476
477   $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/ or die "illegal payinfo";
478   my $payinfo = $1;
479
480   $cgi->param('payby') =~ /^(\w+)$/ or die "illegal payby";
481   my $payby = $1;
482
483   $count_query = "SELECT COUNT(*), SUM($amount_field) FROM $table".
484                  "  WHERE payinfo = '$payinfo' AND payby = '$payby'".
485                  "  AND ". $curuser->agentnums_sql;
486   @count_addl = ( '$%.2f total '.$opt{name_verb} );
487
488   $sql_query = {
489     'table'     => $table,
490     'hashref'   => { 'payinfo' => $payinfo,
491                      'payby'   => $payby    },
492     'extra_sql' => $curuser->agentnums_sql.
493                    " ORDER BY _date",
494   };
495
496 }
497
498 # for consistency
499 $title = join('',map {ucfirst} split(/\b/,$title));
500
501 </%init>