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