RT# 76028 - Added search field Card Last 4#: to allow the filtering of payment report...
[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 { sprintf("<B>$money</B>", $_[0]->$amount_field) },
67                                     ],
68                 'show_combined'  => 1,
69 &>
70 <%shared>
71 # canonicalize the payby subtype string to an SQL-quoted list
72 my %cardtype_of = (
73   'VisaMC'    => q['VISA card', 'MasterCard'],
74   'Amex'      => q['American Express card'],
75   'Discover'  => q['Discover card'],
76   'Maestro'   => q['Switch', 'Solo', 'Laser'],
77   'Tokenized' => q['Tokenized'],
78 );  
79 </%shared>
80 <%init>
81
82 my %opt = @_;
83
84 my $curuser = $FS::CurrentUser::CurrentUser;
85
86 my $conf = FS::Conf->new;
87 my $money = ($conf->config('money_char') || '$') . '%.2f';
88
89 die "access denied"
90   unless $curuser->access_right('Financial reports');
91
92 my $table = $opt{'table'} || 'cust_'.$opt{'thing'};
93
94 my $has_reason = dbdef->table($table)->column('reasonnum') ? 1 : 0;
95
96 my $amount_field = $opt{'amount_field'};
97 my $name_singular = $opt{'name_singular'};
98
99 my $unapplied = $cgi->param('unapplied');
100 my $title = '';
101 $title = 'Unapplied ' if $unapplied;
102 $title .= "\u$name_singular Search Results";
103
104 ###NOT USED???
105 #my $link = '';
106 #if (    ( $curuser->access_right('View invoices') #remove in 2.5 (2.7?)
107 #          || ($curuser->access_right('View payments') && $table =~ /^cust_pay/)
108 #          || ($curuser->access_right('View refunds') && $table eq 'cust_refund')
109 #        )
110 #     && ! $opt{'disable_link'}
111 #   )
112 #{
113 #
114 #  my $key;
115 #  my $q = '';
116 #  if ( $table eq 'cust_pay_void' ) {
117 #    $key = 'paynum';
118 #    $q .= 'void=1;';
119 #  } elsif ( $table eq /^cust_(\w+)$/ ) {
120 #    $key = $1.'num';
121 #  }
122 #  
123 #  if ( $key ) {
124 #    $q .= "$key=";
125 #    $link = [ "${p}view/$table.html?$q", $key ]
126 #  }
127 #}
128
129 my $cust_link = sub {
130   my $cust_thing = shift;
131   $cust_thing->cust_main_custnum
132     ? [ "${p}view/cust_main.cgi?", 'custnum' ] 
133     : '';
134 };
135
136 # only valid for $table == 'cust_pay' atm
137 my  $tax_names = '';
138 if ( $cgi->param('tax_names') ) {
139   if ( dbh->{Driver}->{Name} =~ /^Pg/i ) {
140
141     $tax_names = "
142       array_to_string(
143         array(
144           SELECT itemdesc
145             FROM cust_bill_pay
146             LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
147             LEFT JOIN cust_bill_pkg USING ( billpkgnum )
148               WHERE cust_bill_pkg.pkgnum = 0
149                 AND cust_bill_pay.paynum = cust_pay.paynum
150         ), '|'
151       ) AS tax_names"
152     ;
153
154   } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
155
156     $tax_names = "GROUP_CONCAT(itemdesc SEPARATOR '|') AS tax_names";
157
158   } else {
159
160     warn "warning: unknown database type ". dbh->{Driver}->{Name}.
161          "omitting tax name information from report.";
162
163   }
164 }
165
166 my @header;
167 my @fields;
168 my @sort_fields;
169 my $align = '';
170 my @links;
171 my @link_onclicks;
172 if ( $opt{'pre_header'} ) {
173   push @header, @{ $opt{'pre_header'} };
174   $align .= 'c' x scalar(@{ $opt{'pre_header'} });
175   push @links, map '', @{ $opt{'pre_header'} };
176   push @fields, @{ $opt{'pre_fields'} };
177   push @sort_fields, @{ $opt{'pre_fields'} };
178 }
179
180 my $sub_receipt = $opt{'disable_link'} ? '' : sub {
181   my $obj = shift;
182   my $objnum = $obj->primary_key . '=' . $obj->get($obj->primary_key);
183   my $table = $obj->table;
184   my $void = '';
185   if ($table eq 'cust_pay_void') {
186     $table = 'cust_pay';
187     $void = ';void=1';
188   }
189
190   include('/elements/popup_link_onclick.html',
191     'action'  => $p.'view/'.$table.'.html?link=popup;'.$objnum.$void,
192     'actionlabel' => emt('Payment Receipt'),
193   );
194 };
195
196 push @header, "\u$name_singular",
197               'Amount',
198 ;
199 $align .= 'rr';
200 push @links, '', '';
201 push @fields, 'payby_payinfo_pretty',
202               sub { sprintf($money, shift->$amount_field() ) },
203 ;
204 push @link_onclicks, $sub_receipt, '';
205 push @sort_fields, 'paysort', $amount_field;
206
207 if ($opt{'show_card_type'}) {
208   push @header, emt('Card Type');
209   $align .= 'r';
210   push @links, '';
211   push @fields, 'paycardtype';
212   push @sort_fields, 'paycardtype';
213 }
214
215 if ( $unapplied ) {
216   push @header, emt('Unapplied');
217   $align .= 'r';
218   push @links, '';
219   push @fields, sub { sprintf($money, shift->unapplied_amount) };
220   push @sort_fields, '';
221 }
222
223 push @header, emt('Date');
224 $align .= 'r';
225 push @links, '';
226 push @fields, sub { time2str('%b %d %Y', shift->_date ) };
227 push @sort_fields, '_date';
228
229 if ($cgi->param('show_order_number')) {
230   push @header, emt('Order Number');
231   $align .= 'r';
232   push @links, '';
233   push @fields, 'order_number';
234   push @sort_fields, 'order_number';
235 }
236
237 unless ( $opt{'disable_by'} ) {
238   push @header, emt('By');
239   $align .= 'c';
240   push @links, '';
241   push @fields, sub { my $o = shift->otaker;
242                       $o = 'auto billing'          if $o eq 'fs_daily';
243                       $o = 'customer self-service' if $o eq 'fs_selfservice';
244                       $o;
245                     };
246   push @sort_fields, '';
247 }
248
249 if ( $tax_names ) {
250   push @header, (emt('Tax names'), emt('Tax province'));
251   $align .= 'cc';
252   push @links, ('','');
253   push @fields, sub { join (' + ', map { /^(.*?)(, \w\w)?$/; $1 }
254                                    split('\|', shift->tax_names)
255                            );
256                     };
257   push @fields, sub { join (' + ', map { if (/^(?:.*)(?:, )(\w\w)$/){ $1 }
258                                          else { () }
259                                        }
260                                    split('\|', shift->tax_names)
261                            );
262                     };
263   push @sort_fields, '', '';
264 }
265
266 push @header, FS::UI::Web::cust_header();
267 $align .=  FS::UI::Web::cust_aligns();
268 push @links, map { $_ ne 'Cust. Status' ? $cust_link : '' }
269                  FS::UI::Web::cust_header();
270 my @color = ( ( map '', @fields ), FS::UI::Web::cust_colors() );
271 my @style = ( ( map '', @fields ), FS::UI::Web::cust_styles() );
272 push @fields, \&FS::UI::Web::cust_fields;
273 push @sort_fields, FS::UI::Web::cust_sort_fields;
274
275 push @header, @{ $opt{'addl_header'} }
276   if $opt{'addl_header'};
277 push @fields, @{ $opt{'addl_fields'} }
278   if $opt{'addl_fields'};
279 push @sort_fields, @{ $opt{'addl_sort_fields'} }
280   if $opt{'addl_sort_fields'};
281
282 my( $count_query, $sql_query, @count_addl );
283 if ( $cgi->param('magic') ) {
284
285   my @search = ();
286   my @select = (
287     "$table.*",
288     "( $table.payby || ' ' || coalesce($table.paymask, $table.payinfo) ) AS paysort",
289     FS::UI::Web::cust_sql_fields(),
290     'cust_main.custnum AS cust_main_custnum',
291   );
292   push @select, $tax_names if $tax_names;
293
294   my $orderby;
295   if ( $cgi->param('magic') eq '_date' ) {
296
297     if ( $cgi->param('agentnum') && $cgi->param('agentnum') =~ /^(\d+)$/ ) {
298       push @search, "cust_main.agentnum = $1"; # $search{'agentnum'} = $1;
299       my $agent = qsearchs('agent', { 'agentnum' => $1 } );
300       die "unknown agentnum $1" unless $agent;
301       $title = $agent->agent. " $title";
302     }
303
304     if ( $cgi->param('refnum') && $cgi->param('refnum') =~ /^(\d+)$/ ) {
305       push @search, "cust_main.refnum = $1";
306       my $part_referral = qsearchs('part_referral', { 'refnum' => $1 } );
307       die "unknown refnum $1" unless $part_referral;
308       $title = $part_referral->referral. " $title";
309     }
310
311     # cust_classnum - standard matching
312     push @search, $m->comp('match-classnum',
313         param => 'cust_classnum', field => 'cust_main.classnum'
314       );
315
316     if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
317       push @search, "$table.custnum = $1";
318     }
319
320     if ( $cgi->param('payby') ) {
321
322       my @all_payby_search = ();
323       foreach my $payby_string ( $cgi->param('payby') ) {
324
325         my $payby_search;
326
327         my ($payby, $subtype) = split('-', $payby_string);
328         # make sure it exists and is a transaction type
329         if ( FS::payby->payment_payby2longname($payby) ) {
330           $payby_search = "$table.payby = " . dbh->quote($payby);
331         } else {
332           die "illegal payby $payby_string";
333         }
334
335         if ( $subtype ) {
336
337           my $in_cardtype = $cardtype_of{$subtype}
338             or die "unknown card type $subtype";
339           $payby_search .= " AND $table.paycardtype IN($in_cardtype)";
340
341         }
342
343         push @all_payby_search, $payby_search;
344
345       }
346
347       push @search, ' ( '. join(' OR ', @all_payby_search). ' ) ' if @all_payby_search;
348
349     }
350
351     if ( $cgi->param('paymask') ) {
352       $cgi->param('paymask') =~ /^\s*(\d+)\s*$/
353         or die "illegal paymask ". $cgi->param('paymask');
354       my $regexp = regexp_sql();
355       push @search, "$table.paymask $regexp '$1\$'";
356     } 
357
358     if ( $cgi->param('payinfo') ) {
359       $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/
360         or die "illegal payinfo ". $cgi->param('payinfo');
361       my $regexp = regexp_sql();
362       push @search, "$table.payinfo $regexp '^0*$1\$'";
363     }
364
365     if ( $cgi->param('ccpay') =~ /^([\w-:]+)$/ ) {
366       # I think that's all the characters we need to allow.
367       # To avoid confusion, this parameter searches both auth and order_number.
368       push @search, "($table.auth LIKE '$1%') OR ($table.order_number LIKE '$1%')";
369       push @fields, 'auth', 'order_number';
370       push @header, 'Auth #', 'Transaction #';
371       push @sort_fields, '', '';
372       $align .= 'rr';
373
374     }
375
376     if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
377       push @search, "$table.usernum = $1";
378     }
379
380     #for cust_pay_pending...  statusNOT=done
381     if ( $cgi->param('statusNOT') =~ /^(\w+)$/ ) {
382       push @search, "$table.status != '$1'";
383     }
384
385     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
386
387     push @search, "$table._date >= $beginning ",
388                   "$table._date <= $ending";
389
390     if ( $table eq 'cust_pay_void' ) {
391       my($v_beginning, $v_ending) =
392         FS::UI::Web::parse_beginning_ending($cgi, 'void');
393       push @search, "$table.void_date >= $v_beginning ",
394                     "$table.void_date <= $v_ending";
395     }
396
397     push @search, FS::UI::Web::parse_lt_gt($cgi, $amount_field, $table);
398
399     $orderby = '_date';
400
401   } elsif ( $cgi->param('magic') eq 'paybatch' ) {
402
403     $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/
404       or die "illegal paybatch: ". $cgi->param('paybatch');
405
406     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
407
408   } elsif ( $cgi->param('magic') eq 'batchnum' ) {
409
410     $cgi->param('batchnum') =~ /^(\d+)$/
411       or die "illegal batchnum: ".$cgi->param('batchnum');
412
413     push @search, "batchnum = $1";
414
415     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
416
417   } else {
418     die "unknown search magic: ". $cgi->param('magic');
419   }
420
421   if ( $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/ ) {
422     push @search, "paybatch = '$1'";
423   }
424
425   #unapplied payment/refund
426   if ( $unapplied ) {
427     push @select, '(' . "FS::$table"->unapplied_sql . ') AS unapplied_amount';
428     push @search, "FS::$table"->unapplied_sql . ' > 0';
429
430   }
431
432   #for the history search
433   if ( $cgi->param('history_action') =~ /^([\w,]+)$/ ) {
434     my @history_action = split(/,/, $1);
435     push @search, 'history_action IN ('.
436                     join(',', map "'$_'", @history_action ). ')';
437   }
438
439   if (    $cgi->param('history_date_beginning')
440        || $cgi->param('history_date_ending')    ) {
441       my($h_beginning, $h_ending) =
442         FS::UI::Web::parse_beginning_ending($cgi, 'history_date');
443       push @search, "history_date >= $h_beginning ",
444                     "history_date <= $h_ending";
445   }
446
447   #here is the agent virtualization
448   push @search, $curuser->agentnums_sql;
449
450   my $addl_from = FS::UI::Web::join_cust_main($table);
451   my $group_by = '';
452
453   # reasons, for refunds and voided payments
454   if ( $has_reason ) {
455     push @select, "reason.reason";
456     $addl_from .= " LEFT JOIN reason USING (reasonnum)\n";
457     push @fields, 'reason';
458     push @sort_fields, 'reason.reason';
459     push @header, emt('Reason');
460     if ( $cgi->param('reasonnum') =~ /^(\d+)$/ ) {
461       push @search, "COALESCE(reasonnum, 0) = $1";
462     }
463   }
464
465   if ( $cgi->param('tax_names') ) {
466     if ( dbh->{Driver}->{Name} =~ /^Pg/i ) {
467
468       0;#twiddle thumbs
469
470     } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
471
472       $addl_from .= "LEFT JOIN cust_bill_pay USING ( paynum )
473                      LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
474                      LEFT JOIN cust_bill_pkg USING ( billpkgnum ) AS tax_names";
475       $group_by  .= "GROUP BY $table.*,cust_main_custnum,".
476                     FS::UI::Web::cust_sql_fields();
477       push @search,
478        "( cust_bill_pkg.pkgnum = 0 OR cust_bill_pkg.pkgnum is NULL )";
479
480     } else {
481
482       warn "warning: unknown database type ". dbh->{Driver}->{Name}.
483            "omitting tax name information from report.";
484
485     }
486   }
487
488   my $search = ' WHERE '. join(' AND ', @search);
489
490   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) ";
491   $count_query .= ', SUM(' . "FS::$table"->unapplied_sql . ') ' 
492     if $unapplied;
493   $count_query .= "FROM $table $addl_from".
494                   "$search $group_by";
495
496   @count_addl = ( '$%.2f total '.$opt{name_verb} );
497   push @count_addl, '$%.2f unapplied' if $unapplied;
498
499   $sql_query = {
500     'table'     => $table,
501     'select'    => join(', ', @select),
502     'hashref'   => {},
503     'extra_sql' => "$search $group_by",
504     'order_by'  => "ORDER BY $orderby",
505     'addl_from' => $addl_from,
506   };
507
508 } else {
509
510   #hmm... is this still used?
511   warn "undefined search magic";
512
513   $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/ or die "illegal payinfo";
514   my $payinfo = $1;
515
516   $cgi->param('payby') =~ /^(\w+)$/ or die "illegal payby";
517   my $payby = $1;
518
519   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) FROM $table".
520                  "  WHERE payinfo = '$payinfo' AND payby = '$payby'".
521                  "  AND ". $curuser->agentnums_sql;
522   @count_addl = ( '$%.2f total '.$opt{name_verb} );
523
524   $sql_query = {
525     'table'     => $table,
526     'hashref'   => { 'payinfo' => $payinfo,
527                      'payby'   => $payby    },
528     'extra_sql' => $curuser->agentnums_sql.
529                    " ORDER BY _date",
530   };
531
532 }
533
534 # for consistency
535 $title = join('',map {ucfirst} split(/\b/,$title));
536
537 </%init>