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