RT#71049: Add order_number to payment reports
[freeside.git] / httemplate / search / cust_bill_pay_pkg.html
1 <& elements/search.html,
2               'title'         => 'Payment application detail', #to line item
3               'name_singular' => 'payment application',
4               'query'         => $query,
5               'count_query'   => $count_query,
6                'count_addl'   => [ $money_char. '%.2f total', ],
7                'header'       => [
8                    #'#',
9
10                    'Amount',
11                    'By',
12                    '#',
13                    'Card Type',
14
15                    #payment
16                    'Date',
17                    'Order Number',
18                    'By',
19
20                    #application
21                    'Applied',
22
23                    # line item
24                    'Description',
25                    'Package class',
26                    'Location',
27                    @post_desc_header,
28
29                    #invoice
30                    'Invoice',
31                    'Date',
32                    FS::UI::Web::cust_header(),
33                ],
34                'fields'       => [
35                    #'billpaypkgnum',
36                    sub { sprintf($money_char.'%.2f', shift->paid ) },
37                    sub { $payby{shift->cust_bill_pay->cust_pay->payby} },
38                    sub { my $cust_pay = shift->cust_bill_pay->cust_pay;
39                          $cust_pay->payby =~ /^(CARD|CHEK)$/
40                            ? $cust_pay->paymask : $cust_pay->payinfo;
41                        },
42                    sub { my $cust_pay = shift->cust_bill_pay->cust_pay;
43                          $cust_pay->payby =~ /^CARD$/
44                            ? cardtype($cust_pay->paymask) : '';
45                        },
46                    sub { time2str('%b %d %Y', shift->get('cust_pay_date') ) },
47                    sub { shift->cust_bill_pay->cust_pay->order_number },
48                    sub { shift->cust_bill_pay->cust_pay->otaker },
49
50                    sub { sprintf($money_char.'%.2f', shift->amount ) },
51
52                    sub { $_[0]->pkgnum > 0
53                            ? $_[0]->get('pkg')      # possibly use override.pkg
54                            : $_[0]->get('itemdesc') # but i think this correct
55                        },
56                    'classname', #package class
57                    $location_sub,
58                    @post_desc,
59                    'invnum',
60                    sub { time2str('%b %d %Y', shift->_date ) },
61                    \&FS::UI::Web::cust_fields,
62                ],
63                'sort_fields'  => [
64                    'paid',
65                    '', #payby
66                    '', #payinfo/paymask
67                    '', #cardtype
68                    'cust_pay_date',
69                    '', #order_number
70                    '', #'otaker',
71                    '', #amount
72                    '', #line item description
73                    '', #package class
74                    '', #location
75                    @post_desc_null,
76                    'invnum',
77                    '_date',
78                    #cust fields
79                ],
80                'links' => [
81                    '',
82                    '',
83                    '',
84                    '',
85                    '',
86                    '',
87                    '',
88                    '',
89                    '',
90                    '',
91                    '',
92                    @post_desc_null,
93                    $ilink,
94                    $ilink,
95                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
96                          FS::UI::Web::cust_header()
97                    ),
98                ],
99                'align' => 'rcrlrrlrlll',
100 #original value before cardtype & package were added
101 #why are there 13 cols?
102 #'rcrrlrlllrrcl'.
103                           $post_desc_align.
104                           'rr'.
105                           FS::UI::Web::cust_aligns(),
106                'color' => [ 
107                               '',
108                               '',
109                               '',
110                               '',
111                               '',
112                               '',
113                               '',
114                               '',
115                               '',
116                               '',
117                               '',
118                               @post_desc_null,
119                               '',
120                               '',
121                               FS::UI::Web::cust_colors(),
122                             ],
123                'style' => [ 
124                               '',
125                               '',
126                               '',
127                               '',
128                               '',
129                               '',
130                               '',
131                               '',
132                               '',
133                               '',
134                               '',
135                               @post_desc_null,
136                               '',
137                               '',
138                               FS::UI::Web::cust_styles(),
139                           ],
140            
141 &>
142 <%init>
143
144 #(and now we're cust_bill_pay_pkg.html, false laziness w/cust_credit_bill_pkg)
145 #LOTS of false laziness below w/cust_bill_pkg.cgi
146 # and a little w/cust_credit.html
147
148 die "access denied"
149   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
150
151 my $conf = new FS::Conf;
152
153 my %payby = FS::payby->payby2shortname;
154
155 #here is the agent virtualization
156 my $agentnums_sql =
157   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
158
159 my @where = ( $agentnums_sql );
160
161 if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
162   push @where, "cust_pay.usernum = $1";
163 }
164
165 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
166 push @where, "cust_bill._date >= $beginning",
167              "cust_bill._date <= $ending";
168
169 my($cr_begin, $cr_end) = FS::UI::Web::parse_beginning_ending($cgi, 'payment');
170 push @where, "cust_pay._date >= $cr_begin",
171              "cust_pay._date <= $cr_end";
172
173 #payment amount?  seems more what is expected than the applied amount
174 my @lt_gt = FS::UI::Web::parse_lt_gt($cgi, 'paid' );
175 s/paid/cust_pay.paid/g foreach (@lt_gt);
176 push @where, @lt_gt;
177
178 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
179   push @where, "cust_main.agentnum = $1";
180 }
181
182 if ( $cgi->param('billpkgnum') =~ /^(\d+)$/ ) {
183   push @where, "billpkgnum = $1";
184 }
185
186 #classnum
187 # not specified: all classes
188 # 0: empty class
189 # N: classnum
190 my $use_override = $cgi->param('use_override');
191 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
192   my $comparison = '';
193   if ( $1 == 0 ) {
194     $comparison = "IS NULL";
195   } else {
196     $comparison = "= $1";
197   }
198
199   if ( $use_override ) {
200     push @where, "(
201       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
202       override.classnum $comparison AND pkgpart_override IS NOT NULL
203     )";
204   } else {
205     push @where, "part_pkg.classnum $comparison";
206   }
207 }
208
209 if ( $cgi->param('taxclass')
210      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
211                                 #(should we save a taxclass or a link to taxnum
212                                 # in cust_bill_pkg or something like
213                                 # cust_bill_pkg_tax_location?)
214    )
215 {
216
217   #override taxclass when use_override is specified?  probably
218   #if ( $use_override ) {
219   #
220   #  push @where,
221   #    ' ( '. join(' OR ',
222   #                  map {
223   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
224   #                        '      AND pkgpart_override IS NULL '.
225   #                        '   OR '.
226   #                        '      override.taxclass = '. dbh->quote($_).
227   #                        '      AND pkgpart_override IS NOT NULL '.
228   #                        ' ) '
229   #                      }
230   #                      $cgi->param('taxclass')
231   #               ).
232   #    ' ) ';
233   #
234   #} else {
235
236     push @where,
237       ' ( '. join(' OR ',
238                     map ' part_pkg.taxclass = '.dbh->quote($_),
239                         $cgi->param('taxclass')
240                  ).
241       ' ) ';
242
243   #}
244
245 }
246
247 my @loc_param = qw( district city county state country );
248
249 if ( $cgi->param('out') ) {
250
251   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
252   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
253     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
254   }
255
256   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
257     if $cgi->param('istax');
258
259   push @where, "
260     0 = (
261           SELECT COUNT(*) FROM cust_main_county
262            WHERE cust_main_county.tax > 0
263              AND $loc_sql
264         )
265   ";
266
267   #not linked to by anything, but useful for debugging "out of taxable region"
268   if ( grep $cgi->param($_), @loc_param ) {
269
270     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
271
272     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
273     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
274       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
275     }
276
277     push @where, $loc_sql;
278
279   }
280
281 } elsif ( $cgi->param('country') ) {
282
283   my @counties = $cgi->param('county');
284    
285   if ( scalar(@counties) > 1 ) {
286
287     #hacky, could be more efficient.  care if it is ever used for more than the
288     # tax-report_groups filtering kludge
289
290     my $locs_sql =
291       ' ( '. join(' OR ', map {
292
293           my %ph = ( 'county' => dbh->quote($_),
294                      map { $_ => dbh->quote( $cgi->param($_) ) }
295                        qw( district city state country )
296                    );
297
298           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
299           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
300             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
301           }
302
303           $loc_sql;
304
305         } @counties
306
307       ). ' ) ';
308
309     push @where, $locs_sql;
310
311   } else {
312
313     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
314
315     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
316     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
317       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
318     }
319
320     push @where, $loc_sql;
321
322   }
323    
324   my($title, $name);
325   if ( $cgi->param('istax') ) {
326     $title = 'Tax credits';
327     $name  = 'tax credits';
328     if ( $cgi->param('taxname') ) {
329       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
330     #} elsif ( $cgi->param('taxnameNULL') {
331     } else {
332       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
333     }
334   } elsif ( $cgi->param('nottax') ) {
335     $title = 'Payment applications to line items';
336     $name  = 'applications';
337     #what can we usefully do with "taxname" ????  look up a class???
338   } else {
339     $title = 'Payment applications to line items';
340     $name  = 'applications';
341     #warn "neither nottax nor istax parameters specified";
342   }
343
344   if ( $cgi->param('taxclassNULL')
345        && ! $cgi->param('istax')  #no taxclass in this case
346      )
347   {
348
349     my %hash = ( 'country' => scalar($cgi->param('country')) );
350     foreach (qw( state county )) {
351       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
352     }
353     my $cust_main_county = qsearchs('cust_main_county', \%hash);
354     die "unknown base region for empty taxclass" unless $cust_main_county;
355
356     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
357     push @where, $same_sql if $same_sql;
358
359   }
360
361 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
362
363   # this should really be shoved out to FS::cust_pkg->location_sql or something
364   # along with the code in report_newtax.cgi
365
366   my %pn = (
367    'county'        => 'tax_rate_location.county',
368    'state'         => 'tax_rate_location.state',
369    'city'          => 'tax_rate_location.city',
370    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
371   );
372
373   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
374            qw( city county state locationtaxid );
375
376   push @where,
377     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
378                    keys %ph
379     );
380
381 }
382
383 if ( $cgi->param('itemdesc') ) {
384   if ( $cgi->param('itemdesc') eq 'Tax' ) {
385     push @where, "(itemdesc='Tax' OR itemdesc is null)";
386   } else {
387     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
388   }
389 }
390
391 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
392   my ( $group_op, $group_value ) = ( $1, $2 );
393   if ( $group_op eq '=' ) {
394     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
395     push @where, 'itemdesc = '. dbh->quote($group_value);
396   } elsif ( $group_op eq '!=' ) {
397     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
398   } else {
399     die "guru meditation #00de: group_op $group_op\n";
400   }
401   
402 }
403
404 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
405 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
406
407 if ( $cgi->param('cust_tax') ) {
408   #false laziness -ish w/report_tax.cgi
409   my $cust_exempt;
410   if ( $cgi->param('taxname') ) {
411     my $q_taxname = dbh->quote($cgi->param('taxname'));
412     $cust_exempt =
413       "( tax = 'Y'
414          OR EXISTS ( SELECT 1 FROM cust_main_exemption
415                        WHERE cust_main_exemption.custnum = cust_main.custnum
416                          AND cust_main_exemption.taxname = $q_taxname )
417        )
418       ";
419   } else {
420     $cust_exempt = " tax = 'Y' ";
421   }
422
423   push @where, $cust_exempt;
424 }
425
426 my $count_query = "SELECT COUNT(DISTINCT billpaypkgnum),
427                           SUM(cust_bill_pay_pkg.amount)";
428
429 my $join_cust =
430   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum )'.
431   FS::UI::Web::join_cust_main('cust_bill', 'cust_pkg');
432
433
434 my $join_pkg;
435
436 my $join_cust_bill_pkg = 'LEFT JOIN cust_bill_pkg USING ( billpkgnum )';
437
438 if ( $cgi->param('nottax') ) {
439
440   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
441                  LEFT JOIN part_pkg USING ( pkgpart )
442                  LEFT JOIN pkg_class USING ( classnum )
443                  LEFT JOIN part_pkg AS override
444                    ON pkgpart_override = override.pkgpart ';
445   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
446     if $conf->exists('tax-pkg_address');
447
448 } elsif ( $cgi->param('istax') ) {
449
450   #false laziness w/report_tax.cgi $taxfromwhere
451   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
452             $cgi->param('iscredit') eq 'rate') {
453
454     $join_pkg .=
455       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ';
456     if ( $cgi->param('iscredit') eq 'rate' ) {
457       $join_pkg .= ', billpkgtaxratelocationnum )';
458     } elsif ( $conf->exists('tax-pkg_address') ) {
459       $join_pkg .= ', billpkgtaxlocationnum )';
460       push @where, "billpkgtaxratelocationnum IS NULL";
461     } else {
462       $join_pkg .= ' )';
463       push @where, "billpkgtaxratelocationnum IS NULL";
464     }
465
466     $join_pkg .= ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
467
468   } elsif ( $conf->exists('tax-pkg_address') ) {
469
470     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
471                    LEFT JOIN cust_location              USING ( locationnum ) ';
472
473     #quelle kludge, somewhat false laziness w/report_tax.cgi
474     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
475   }
476
477 } else {
478
479   #warn "neither nottax nor istax parameters specified";
480   #same as before?
481   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
482                  LEFT JOIN part_pkg USING ( pkgpart ) 
483                  LEFT JOIN pkg_class USING ( classnum )';
484
485 }
486
487 my $where = ' WHERE '. join(' AND ', @where);
488
489 my $join_pay = ' LEFT JOIN cust_bill_pay USING ( billpaynum )
490                  LEFT JOIN cust_pay      USING ( paynum ) ';
491
492 $count_query .= " FROM cust_bill_pay_pkg
493                          $join_cust_bill_pkg
494                          $join_pkg
495                          $join_pay
496                          $join_cust
497                        $where";
498
499 my @select = ( 'cust_bill_pay_pkg.*',
500                'cust_bill_pkg.*',
501                'cust_pay.paid',
502                'cust_pay.otaker',
503                'cust_pay._date AS cust_pay_date',
504                'cust_bill._date',
505              );
506 push @select, 'part_pkg.pkg, pkg_class.classname' unless $cgi->param('istax');
507 push @select, 'cust_main.custnum',
508               FS::UI::Web::cust_sql_fields();
509
510 my @post_desc_header = ();
511 my @post_desc = ();
512 my @post_desc_null = ();
513 my $post_desc_align = '';
514 if ( $conf->exists('enable_taxclasses') && ! $cgi->param('istax') ) {
515   push @post_desc_header, 'Tax class';
516   push @post_desc, 'taxclass';
517   push @post_desc_null, '';
518   $post_desc_align .= 'l';
519   push @select, 'part_pkg.taxclass'; # or should this use override?
520 }
521
522 #warn "$join_cust_bill_pkg
523 #                  $join_pkg
524 #                  $join_pay
525 #                  $join_cust";
526
527 my $query = {
528   'table'     => 'cust_bill_pay_pkg',
529   'addl_from' => "$join_cust_bill_pkg
530                   $join_pkg
531                   $join_pay
532                   $join_cust",
533   'hashref'   => {},
534   'select'    => join(', ', @select ),
535   'extra_sql' => $where,
536   'order_by'  => 'ORDER BY billpaypkgnum', #cust_bill. or cust_pay._date?
537 };
538
539 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
540 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
541
542 my $conf = new FS::Conf;
543 my $money_char = $conf->config('money_char') || '$';
544
545 my $tax_pkg_address = $conf->exists('tax-pkg_address');
546 my $tax_ship_address = $conf->exists('tax-ship_address');
547
548 my $location_sub = sub {
549   #my $cust_bill_pay_pkg = shift;
550   my $self = shift;
551   my $tax_Xlocation = $self->cust_bill_pkg_tax_Xlocation;
552   if ( defined($tax_Xlocation) && $tax_Xlocation ) {
553
554     if ( ref($tax_Xlocation) eq 'FS::cust_bill_pkg_tax_location' ) {
555
556       if ( $tax_Xlocation->taxtype eq 'FS::cust_main_county' ) {
557         my $cust_main_county = $tax_Xlocation->cust_main_county;
558         if ( $cust_main_county ) {
559           $cust_main_county->label;
560         } else {
561           ''; #cust_main_county record is gone... history?  yuck.
562         }
563       } else {
564         '(CCH tax_rate)'; #XXX FS::tax_rate.. vendor taxes not yet handled here
565       }
566
567     } elsif ( ref($tax_Xlocation) eq 'FS::cust_bill_pkg_tax_rate_location' ) {
568       '(CCH)'; #XXX vendor taxes not yet handled here
569     } else {
570       'unknown tax_Xlocation '. ref($tax_Xlocation);
571     }
572
573   } else {
574
575     my $cust_bill_pkg = $self->cust_bill_pkg;
576     if ( $cust_bill_pkg->pkgnum > 0 ) {
577       my $cust_pkg = $cust_bill_pkg->cust_pkg;
578       if ( $tax_pkg_address && (my $cust_location = $cust_pkg->cust_location) ){
579         $cust_location->county_state_country;
580       } else {
581         my $cust_main = $cust_pkg->cust_main;
582         if ( $tax_ship_address && $cust_main->has_ship_address ) {
583           $cust_main->county_state_country('ship_');
584         } else {
585           $cust_main->county_state_country;
586         }
587       }
588
589     } else {
590       #tax?  we shouldn't have wound up here then...
591       ''; #return customer ship or bill address? (depending on tax-ship_address)
592     }
593
594   }
595
596 };
597
598 </%init>