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