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