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