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