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