fix broadband reporting with giant query URLs (large numbers of package defs, etc...
[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('Basic payment and refund 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 # 4.x, to remain functional while the upgrade is running...
208 my $sub_guess_cardtype = sub {
209   my $row = shift;
210   $row->paycardtype || (
211     ($row->payby eq 'CARD'  && $row->paymask !~ /N\/A/)
212     ? cardtype($row->paymask)
213     : ''
214   )
215 };
216
217 if ($opt{'show_card_type'}) {
218   push @header, emt('Card Type');
219   $align .= 'r';
220   push @links, '';
221   push @fields, $sub_guess_cardtype;
222   # worst case, paycardtype isn't filled in yet and sorting by that column
223   # does nothing.
224   push @sort_fields, 'paycardtype';
225 }
226
227 if ( $unapplied ) {
228   push @header, emt('Unapplied');
229   $align .= 'r';
230   push @links, '';
231   push @fields, sub { sprintf($money, shift->unapplied_amount) };
232   push @sort_fields, '';
233 }
234
235 push @header, emt('Date');
236 $align .= 'r';
237 push @links, '';
238 push @fields, sub { time2str('%b %d %Y', shift->_date ) };
239 push @sort_fields, '_date';
240
241 if ($cgi->param('show_order_number')) {
242   push @header, emt('Order Number');
243   $align .= 'r';
244   push @links, '';
245   push @fields, 'order_number';
246   push @sort_fields, 'order_number';
247 }
248
249 unless ( $opt{'disable_by'} ) {
250   push @header, emt('By');
251   $align .= 'c';
252   push @links, '';
253   push @fields, sub { my $o = shift->otaker;
254                       $o = 'auto billing'          if $o eq 'fs_daily';
255                       $o = 'customer self-service' if $o eq 'fs_selfservice';
256                       $o;
257                     };
258   push @sort_fields, '';
259 }
260
261 if ( $tax_names ) {
262   push @header, (emt('Tax names'), emt('Tax province'));
263   $align .= 'cc';
264   push @links, ('','');
265   push @fields, sub { join (' + ', map { /^(.*?)(, \w\w)?$/; $1 }
266                                    split('\|', shift->tax_names)
267                            );
268                     };
269   push @fields, sub { join (' + ', map { if (/^(?:.*)(?:, )(\w\w)$/){ $1 }
270                                          else { () }
271                                        }
272                                    split('\|', shift->tax_names)
273                            );
274                     };
275   push @sort_fields, '', '';
276 }
277
278 push @header, FS::UI::Web::cust_header();
279 $align .=  FS::UI::Web::cust_aligns();
280 push @links, map { $_ ne 'Cust. Status' ? $cust_link : '' }
281                  FS::UI::Web::cust_header();
282 my @color = ( ( map '', @fields ), FS::UI::Web::cust_colors() );
283 my @style = ( ( map '', @fields ), FS::UI::Web::cust_styles() );
284 push @fields, \&FS::UI::Web::cust_fields;
285 push @sort_fields, FS::UI::Web::cust_sort_fields;
286
287 push @header, @{ $opt{'addl_header'} }
288   if $opt{'addl_header'};
289 push @fields, @{ $opt{'addl_fields'} }
290   if $opt{'addl_fields'};
291 push @sort_fields, @{ $opt{'addl_sort_fields'} }
292   if $opt{'addl_sort_fields'};
293
294 my( $count_query, $sql_query, @count_addl );
295 if ( $cgi->param('magic') ) {
296
297   my @search = ();
298   my @select = (
299     "$table.*",
300     "( $table.payby || ' ' || coalesce($table.paymask, $table.payinfo) ) AS paysort",
301     FS::UI::Web::cust_sql_fields(),
302     'cust_main.custnum AS cust_main_custnum',
303   );
304   push @select, $tax_names if $tax_names;
305
306   my $orderby;
307   if ( $cgi->param('magic') eq '_date' ) {
308
309     if ( $cgi->param('agentnum') && $cgi->param('agentnum') =~ /^(\d+)$/ ) {
310       push @search, "cust_main.agentnum = $1"; # $search{'agentnum'} = $1;
311       my $agent = qsearchs('agent', { 'agentnum' => $1 } );
312       die "unknown agentnum $1" unless $agent;
313       $title = $agent->agent. " $title";
314     }
315
316     if ( $cgi->param('refnum') && $cgi->param('refnum') =~ /^(\d+)$/ ) {
317       push @search, "cust_main.refnum = $1";
318       my $part_referral = qsearchs('part_referral', { 'refnum' => $1 } );
319       die "unknown refnum $1" unless $part_referral;
320       $title = $part_referral->referral. " $title";
321     }
322
323     # cust_classnum - standard matching
324     push @search, $m->comp('match-classnum',
325         param => 'cust_classnum', field => 'cust_main.classnum'
326       );
327
328     if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
329       push @search, "$table.custnum = $1";
330     }
331
332     if ( $cgi->param('payby') ) {
333
334       my @all_payby_search = ();
335       foreach my $payby_string ( $cgi->param('payby') ) {
336
337         my $payby_search;
338
339         my ($payby, $subtype) = split('-', $payby_string);
340         # make sure it exists and is a transaction type
341         if ( FS::payby->payment_payby2longname($payby) ) {
342           $payby_search = "$table.payby = " . dbh->quote($payby);
343         } else {
344           die "illegal payby $payby_string";
345         }
346
347         if ( $subtype ) {
348
349           my $in_cardtype = $cardtype_of{$subtype}
350             or die "unknown card type $subtype";
351           # will complete this phrase after alt_search
352           $payby_search .= " AND ( $table.paycardtype IN($in_cardtype)";
353
354           # 4.x transitional, to avoid breaking things while we upgrade
355           my $similar_to = dbh->{Driver}->{Name} =~ /^mysql/i
356                              ? 'REGEXP' #doesn't behave exactly the same, but
357                                         #should work for our patterns
358                              : 'SIMILAR TO';
359
360           my $alt_search;
361           if ( $subtype eq 'VisaMC' ) {
362
363             #avoid posix regexes for portability
364             $alt_search =
365               # Visa
366               " ( (     substring($table.payinfo from 1 for 1) = '4'     ".
367               #   is not Switch
368               "     AND substring($table.payinfo from 1 for 4) != '4936' ".
369               "     AND substring($table.payinfo from 1 for 6)           ".
370               "         NOT $similar_to '49030[2-9]'                        ".
371               "     AND substring($table.payinfo from 1 for 6)           ".
372               "         NOT $similar_to '49033[5-9]'                        ".
373               "     AND substring($table.payinfo from 1 for 6)           ".
374               "         NOT $similar_to '49110[1-2]'                        ".
375               "     AND substring($table.payinfo from 1 for 6)           ".
376               "         NOT $similar_to '49117[4-9]'                        ".
377               "     AND substring($table.payinfo from 1 for 6)           ".
378               "         NOT $similar_to '49118[1-2]'                        ".
379               "   )".
380               # MasterCard
381               "   OR substring($table.payinfo from 1 for 2) = '51' ".
382               "   OR substring($table.payinfo from 1 for 2) = '52' ".
383               "   OR substring($table.payinfo from 1 for 2) = '53' ".
384               "   OR substring($table.payinfo from 1 for 2) = '54' ".
385               "   OR substring($table.payinfo from 1 for 2) = '54' ".
386               "   OR substring($table.payinfo from 1 for 2) = '55' ".
387               "   OR substring($table.payinfo from 1 for 4) $similar_to '222[1-9]' ".
388               "   OR substring($table.payinfo from 1 for 3) $similar_to '22[3-9]' ".
389               "   OR substring($table.payinfo from 1 for 2) $similar_to '2[3-6]' ".
390               "   OR substring($table.payinfo from 1 for 3) $similar_to '27[0-1]' ".
391               "   OR substring($table.payinfo from 1 for 4) = '2720' ".
392               "   OR substring($table.payinfo from 1 for 3) = '2[2-7]x' ".
393               " ) ";
394
395           } elsif ( $subtype eq 'Amex' ) {
396
397             $alt_search =
398               " (    substring($table.payinfo from 1 for 2 ) = '34' ".
399               "   OR substring($table.payinfo from 1 for 2 ) = '37' ".
400               " ) ";
401
402           } elsif ( $subtype eq 'Discover' ) {
403
404             my $country = $conf->config('countrydefault') || 'US';
405
406             $alt_search =
407               " (    substring($table.payinfo from 1 for 4 ) = '6011'  ".
408               "   OR substring($table.payinfo from 1 for 3 ) = '60x'   ".
409               "   OR substring($table.payinfo from 1 for 2 ) = '65'    ".
410
411               # diner's 300-305 / 3095
412               "   OR substring($table.payinfo from 1 for 3 ) = '300'   ".
413               "   OR substring($table.payinfo from 1 for 3 ) = '301'   ".
414               "   OR substring($table.payinfo from 1 for 3 ) = '302'   ".
415               "   OR substring($table.payinfo from 1 for 3 ) = '303'   ".
416               "   OR substring($table.payinfo from 1 for 3 ) = '304'   ".
417               "   OR substring($table.payinfo from 1 for 3 ) = '305'   ".
418               "   OR substring($table.payinfo from 1 for 4 ) = '3095'  ".
419               "   OR substring($table.payinfo from 1 for 3 ) = '30x'   ".
420
421               # diner's 36, 38, 39
422               "   OR substring($table.payinfo from 1 for 2 ) = '36'    ".
423               "   OR substring($table.payinfo from 1 for 2 ) = '38'    ".
424               "   OR substring($table.payinfo from 1 for 2 ) = '39'    ".
425
426               "   OR substring($table.payinfo from 1 for 3 ) = '644'   ".
427               "   OR substring($table.payinfo from 1 for 3 ) = '645'   ".
428               "   OR substring($table.payinfo from 1 for 3 ) = '646'   ".
429               "   OR substring($table.payinfo from 1 for 3 ) = '647'   ".
430               "   OR substring($table.payinfo from 1 for 3 ) = '648'   ".
431               "   OR substring($table.payinfo from 1 for 3 ) = '649'   ".
432               "   OR substring($table.payinfo from 1 for 3 ) = '64x'   ".
433
434               # JCB cards in the 3528-3589 range identified as Discover inside US & territories (NOT Canada)
435               ( $country =~ /^(US|PR|VI|MP|PW|GU)$/
436                ?" OR substring($table.payinfo from 1 for 4 ) = '3528'  ".
437                 " OR substring($table.payinfo from 1 for 4 ) = '3529'  ".
438                 " OR substring($table.payinfo from 1 for 3 ) = '353'   ".
439                 " OR substring($table.payinfo from 1 for 3 ) = '354'   ".
440                 " OR substring($table.payinfo from 1 for 3 ) = '355'   ".
441                 " OR substring($table.payinfo from 1 for 3 ) = '356'   ".
442                 " OR substring($table.payinfo from 1 for 3 ) = '357'   ".
443                 " OR substring($table.payinfo from 1 for 3 ) = '358'   ".
444                 " OR substring($table.payinfo from 1 for 3 ) = '35x'   "
445                :""
446               ).
447
448               #China Union Pay processed as Discover in US, Mexico and Caribbean
449               ( $country =~ /^(US|MX|AI|AG|AW|BS|BB|BM|BQ|VG|KY|CW|DM|DO|GD|GP|JM|MQ|MS|BL|KN|LC|VC|MF|SX|TT|TC)$/
450                ?" OR substring($table.payinfo from 1 for 3 ) $similar_to '62[24-68x]'   "
451                :""
452               ).
453
454               " ) ";
455
456           } elsif ( $subtype eq 'Maestro' ) {
457
458             $alt_search =
459               " (    substring($table.payinfo from 1 for 2 ) = '63'     ".
460               "   OR substring($table.payinfo from 1 for 2 ) = '67'     ".
461               "   OR substring($table.payinfo from 1 for 6 ) = '564182' ".
462               "   OR substring($table.payinfo from 1 for 4 ) = '4936'   ".
463               "   OR substring($table.payinfo from 1 for 6 )            ".
464               "      $similar_to '49030[2-9]'                             ".
465               "   OR substring($table.payinfo from 1 for 6 )            ".
466               "      $similar_to '49033[5-9]'                             ".
467               "   OR substring($table.payinfo from 1 for 6 )            ".
468               "      $similar_to '49110[1-2]'                             ".
469               "   OR substring($table.payinfo from 1 for 6 )            ".
470               "      $similar_to '49117[4-9]'                             ".
471               "   OR substring($table.payinfo from 1 for 6 )            ".
472               "      $similar_to '49118[1-2]'                             ".
473               " ) ";
474
475           } elsif ( $subtype eq 'Tokenized' ) {
476
477               $alt_search = " substring($table.payinfo from 1 for 2 ) = '99' ";
478
479           } else { # shouldn't happen if there's a $subtype
480
481             $alt_search = 'TRUE';
482  
483           }
484
485           # alt_search is already paren'd if it contains OR.
486           # now make sure it works if they're encrypted.
487           my $masksearch = $alt_search;
488           $masksearch =~ s/$table.payinfo/$table.paymask/g;
489           $alt_search = "( ($table.paymask IS NOT NULL AND $masksearch)
490                           OR $alt_search )";
491
492           # close paren here
493           $payby_search .= " OR ( $table.paycardtype IS NULL AND $alt_search ) )";
494
495         } # if $subtype
496
497         push @all_payby_search, $payby_search;
498
499       }
500
501       push @search, ' ( '. join(' OR ', @all_payby_search). ' ) ' if @all_payby_search;
502
503     }
504
505     if ( $cgi->param('paymask') ) {
506       $cgi->param('paymask') =~ /^\s*(\d+)\s*$/
507         or die "illegal paymask ". $cgi->param('paymask');
508       my $regexp = regexp_sql();
509       push @search, "$table.paymask $regexp '$1\$'";
510     } 
511
512     if ( $cgi->param('payinfo') ) {
513       $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/
514         or die "illegal payinfo ". $cgi->param('payinfo');
515       my $regexp = regexp_sql();
516       push @search, "$table.payinfo $regexp '^0*$1\$'";
517     }
518
519     if ( $cgi->param('ccpay') =~ /^([\w-:]+)$/ ) {
520       # I think that's all the characters we need to allow.
521       # To avoid confusion, this parameter searches both auth and order_number.
522       push @search, "($table.auth LIKE '$1%') OR ($table.order_number LIKE '$1%')";
523       push @fields, 'auth', 'order_number';
524       push @header, 'Auth #', 'Transaction #';
525       push @sort_fields, '', '';
526       $align .= 'rr';
527
528     }
529
530     if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
531       push @search, "$table.usernum = $1";
532     }
533
534     #for cust_pay_pending...  statusNOT=done
535     if ( $cgi->param('statusNOT') =~ /^(\w+)$/ ) {
536       push @search, "$table.status != '$1'";
537     }
538
539     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
540
541     push @search, "$table._date >= $beginning ",
542                   "$table._date <= $ending";
543
544     if ( $table eq 'cust_pay_void' ) {
545       my($v_beginning, $v_ending) =
546         FS::UI::Web::parse_beginning_ending($cgi, 'void');
547       push @search, "$table.void_date >= $v_beginning ",
548                     "$table.void_date <= $v_ending";
549     }
550
551     push @search, FS::UI::Web::parse_lt_gt($cgi, $amount_field, $table);
552
553     $orderby = '_date';
554
555   } elsif ( $cgi->param('magic') eq 'paybatch' ) {
556
557     $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/
558       or die "illegal paybatch: ". $cgi->param('paybatch');
559
560     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
561
562   } elsif ( $cgi->param('magic') eq 'batchnum' ) {
563
564     $cgi->param('batchnum') =~ /^(\d+)$/
565       or die "illegal batchnum: ".$cgi->param('batchnum');
566
567     push @search, "batchnum = $1";
568
569     $orderby = "LOWER(company || ' ' || last || ' ' || first )";
570
571   } else {
572     die "unknown search magic: ". $cgi->param('magic');
573   }
574
575   if ( $cgi->param('paybatch') =~ /^([\w\/\:\-\.]+)$/ ) {
576     push @search, "paybatch = '$1'";
577   }
578
579   #unapplied payment/refund
580   if ( $unapplied ) {
581     push @select, '(' . "FS::$table"->unapplied_sql . ') AS unapplied_amount';
582     push @search, "FS::$table"->unapplied_sql . ' > 0';
583
584   }
585
586   #for the history search
587   if ( $cgi->param('history_action') =~ /^([\w,]+)$/ ) {
588     my @history_action = split(/,/, $1);
589     push @search, 'history_action IN ('.
590                     join(',', map "'$_'", @history_action ). ')';
591   }
592
593   if (    $cgi->param('history_date_beginning')
594        || $cgi->param('history_date_ending')    ) {
595       my($h_beginning, $h_ending) =
596         FS::UI::Web::parse_beginning_ending($cgi, 'history_date');
597       push @search, "history_date >= $h_beginning ",
598                     "history_date <= $h_ending";
599   }
600
601   #here is the agent virtualization
602   push @search, $curuser->agentnums_sql;
603
604   my $addl_from = FS::UI::Web::join_cust_main($table);
605   my $group_by = '';
606
607   # reasons, for refunds and voided payments
608   if ( $has_reason ) {
609     push @select, "reason.reason";
610     $addl_from .= " LEFT JOIN reason USING (reasonnum)\n";
611     push @fields, 'reason';
612     push @sort_fields, 'reason.reason';
613     push @header, emt('Reason');
614     if ( $cgi->param('reasonnum') =~ /^(\d+)$/ ) {
615       push @search, "COALESCE(reasonnum, 0) = $1";
616     }
617   }
618
619   #check for customer tags
620   my @tags;
621   foreach my $p ($cgi->param) {
622     if ($p =~ /^tagnum(\d+)/ && $1) {
623       $addl_from .= " LEFT JOIN cust_tag ON (cust_tag.custnum = cust_pay.custnum)" unless @tags;
624       push @tags, $1;
625     }
626   }
627   if (@tags) {
628     my $tags = join(',',@tags);
629     push @search, "cust_tag.tagnum in ($tags)";
630   }
631
632   if ( $cgi->param('tax_names') ) {
633     if ( dbh->{Driver}->{Name} =~ /^Pg/i ) {
634
635       0;#twiddle thumbs
636
637     } elsif ( dbh->{Driver}->{Name} =~ /^mysql/i ) {
638
639       $addl_from .= "LEFT JOIN cust_bill_pay USING ( paynum )
640                      LEFT JOIN cust_bill_pay_pkg USING ( billpaynum )
641                      LEFT JOIN cust_bill_pkg USING ( billpkgnum ) AS tax_names";
642       $group_by  .= "GROUP BY $table.*,cust_main_custnum,".
643                     FS::UI::Web::cust_sql_fields();
644       push @search,
645        "( cust_bill_pkg.pkgnum = 0 OR cust_bill_pkg.pkgnum is NULL )";
646
647     } else {
648
649       warn "warning: unknown database type ". dbh->{Driver}->{Name}.
650            "omitting tax name information from report.";
651
652     }
653   }
654
655   #customer location... total false laziness w/cust_main/Search.pm
656
657   my $current = '';
658   unless ( $cgi->param('location_history') ) {
659     $current = '
660       AND (    cust_location.locationnum IN ( cust_main.bill_locationnum,
661                                               cust_main.ship_locationnum
662                                             )
663             OR cust_location.locationnum IN (
664                  SELECT locationnum FROM cust_pkg
665                   WHERE cust_pkg.custnum = cust_main.custnum
666                     AND locationnum IS NOT NULL
667                     AND '. FS::cust_pkg->ncancelled_recurring_sql.'
668                )
669           )';
670   }
671
672
673   ##
674   # address
675   ##
676   if ( $cgi->param('address') ) {
677     my @values = $cgi->param('address');
678     my @orwhere;
679     foreach (grep /\S/, @values) {
680       my $address = dbh->quote('%'. lc($_). '%');
681       push @orwhere,
682         "LOWER(cust_location.address1) LIKE $address",
683         "LOWER(cust_location.address2) LIKE $address";
684     }
685     if (@orwhere) {
686       push @search, "EXISTS(
687         SELECT 1 FROM cust_location 
688         WHERE cust_location.custnum = cust_main.custnum
689           AND (".join(' OR ',@orwhere).")
690           $current
691         )";
692     }
693   }
694
695   ##
696   # city
697   ##
698   if ( $cgi->param('city') =~ /\S/ ) {
699     my $city = dbh->quote($cgi->param('city'));
700     push @search, "EXISTS(
701       SELECT 1 FROM cust_location
702       WHERE cust_location.custnum = cust_main.custnum
703         AND cust_location.city = $city
704         $current
705     )";
706   }
707
708   ##
709   # county
710   ##
711   if ( $cgi->param('county') =~ /\S/ ) {
712     my $county = dbh->quote($cgi->param('county'));
713     push @search, "EXISTS(
714       SELECT 1 FROM cust_location
715       WHERE cust_location.custnum = cust_main.custnum
716         AND cust_location.county = $county
717         $current
718     )";
719   }
720
721   ##
722   # state
723   ##
724   if ( $cgi->param('state') =~ /\S/ ) {
725     my $state = dbh->quote($cgi->param('state'));
726     push @search, "EXISTS(
727       SELECT 1 FROM cust_location
728       WHERE cust_location.custnum = cust_main.custnum
729         AND cust_location.state = $state
730         $current
731     )";
732   }
733
734   ##
735   # zipcode
736   ##
737   if ( $cgi->param('zip') =~ /\S/ ) {
738     my $zip = dbh->quote($cgi->param('zip') . '%');
739     push @search, "EXISTS(
740       SELECT 1 FROM cust_location
741       WHERE cust_location.custnum = cust_main.custnum
742         AND cust_location.zip LIKE $zip
743         $current
744     )";
745   }
746
747   ##
748   # country
749   ##
750   if ( $cgi->param('country') =~ /^(\w\w)$/ ) {
751     my $country = uc($1);
752     push @search, "EXISTS(
753       SELECT 1 FROM cust_location
754       WHERE cust_location.custnum = cust_main.custnum
755         AND cust_location.country = '$country'
756         $current
757     )";
758   }
759
760   #end of false laziness w/cust_main/Search.pm
761
762   my $search = ' WHERE '. join(' AND ', @search);
763
764   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) ";
765   $count_query .= ', SUM(' . "FS::$table"->unapplied_sql . ') ' 
766     if $unapplied;
767   $count_query .= "FROM $table $addl_from".
768                   "$search $group_by";
769
770   @count_addl = ( '$%.2f total '.$opt{name_verb} );
771   push @count_addl, '$%.2f unapplied' if $unapplied;
772
773   $sql_query = {
774     'table'     => $table,
775     'select'    => join(', ', @select),
776     'hashref'   => {},
777     'extra_sql' => "$search $group_by",
778     'order_by'  => "ORDER BY $orderby",
779     'addl_from' => $addl_from,
780   };
781
782 } else {
783
784   #hmm... is this still used?
785   warn "undefined search magic";
786
787   $cgi->param('payinfo') =~ /^\s*(\d+)\s*$/ or die "illegal payinfo";
788   my $payinfo = $1;
789
790   $cgi->param('payby') =~ /^(\w+)$/ or die "illegal payby";
791   my $payby = $1;
792
793   $count_query = "SELECT COUNT(*), SUM($table.$amount_field) FROM $table".
794                  "  WHERE payinfo = '$payinfo' AND payby = '$payby'".
795                  "  AND ". $curuser->agentnums_sql;
796   @count_addl = ( '$%.2f total '.$opt{name_verb} );
797
798   $sql_query = {
799     'table'     => $table,
800     'hashref'   => { 'payinfo' => $payinfo,
801                      'payby'   => $payby    },
802     'extra_sql' => $curuser->agentnums_sql.
803                    " ORDER BY _date",
804   };
805
806 }
807
808 # for consistency
809 $title = join('',map {ucfirst} split(/\b/,$title));
810
811 </%init>