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