better reporting for tax credits, RT#4729
[freeside.git] / httemplate / search / cust_credit_bill_pkg.html
1 <% include( 'elements/search.html',
2               'title'       => 'Tax credits', #well, actually application of
3               'name'        => 'tax credits', # credit to line item
4               'query'       => $query,
5               'count_query' => $count_query,
6                  'count_addl'  => [ $money_char. '%.2f total', ],
7                  'header'      => [
8                    #'#',
9
10                    'Amount',
11                    # credit date, By, Reason,
12                    # line item, invoice
13
14                    'Description',
15                    'Setup charge',
16                    ( $use_usage eq 'usage'
17                      ? 'Usage charge'
18                      : 'Recurring charge'
19                    ),
20                    'Invoice',
21                    'Date',
22                    FS::UI::Web::cust_header(),
23                  ],
24                  'fields'      => [
25                    #'creditbillpkgnum',
26                    'amount',
27
28                    sub { $_[0]->pkgnum > 0
29                            ? $_[0]->get('pkg')      # possibly use override.pkg
30                            : $_[0]->get('itemdesc') # but i think this correct
31                        },
32                    #strikethrough or "N/A ($amount)" or something these when
33                    # they're not applicable to pkg_tax search
34                    sub { sprintf($money_char.'%.2f', shift->setup ) },
35                    sub { my $row = shift;
36                          my $value = 0;
37                          if ( $use_usage eq 'recurring' ) {
38                            $value = $row->recur - $row->usage;
39                          } elsif ( $use_usage eq 'usage' ) {
40                            $value = $row->usage;
41                          } else {
42                            $value = $row->recur;
43                          }
44                          sprintf($money_char.'%.2f', $value );
45                        },
46                    'invnum',
47                    sub { time2str('%b %d %Y', shift->_date ) },
48                    \&FS::UI::Web::cust_fields,
49                  ],
50                  'links'       => [
51                    '',
52                    '',
53                    '',
54                    '',
55                    $ilink,
56                    $ilink,
57                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
58                          FS::UI::Web::cust_header()
59                    ),
60                  ],
61                  'align' => 'rlrrrc'.FS::UI::Web::cust_aligns(),
62                  'color' => [ 
63                               '',
64                               '',
65                               '',
66                               '',
67                               '',
68                               '',
69                               FS::UI::Web::cust_colors(),
70                             ],
71                  'style' => [ 
72                               '',
73                               '',
74                               '',
75                               '',
76                               '',
77                               '',
78                               FS::UI::Web::cust_styles(),
79                             ],
80            )
81 %>
82 <%init>
83
84 #LOTS of false laziness below w/cust_bill_pkg.cgi
85
86 die "access denied"
87   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
88
89 my $conf = new FS::Conf;
90
91 #here is the agent virtualization
92 my $agentnums_sql =
93   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
94
95 my @where = ( $agentnums_sql );
96
97 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
98 push @where, "cust_bill._date >= $beginning",
99              "cust_bill._date <= $ending";
100
101 push @where , " payby != 'COMP' "
102   unless $cgi->param('include_comp_cust');
103
104 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
105   push @where, "cust_main.agentnum = $1";
106 }
107
108 #classnum
109 # not specified: all classes
110 # 0: empty class
111 # N: classnum
112 my $use_override = $cgi->param('use_override');
113 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
114   my $comparison = '';
115   if ( $1 == 0 ) {
116     $comparison = "IS NULL";
117   } else {
118     $comparison = "= $1";
119   }
120
121   if ( $use_override ) {
122     push @where, "(
123       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
124       override.classnum $comparison AND pkgpart_override IS NOT NULL
125     )";
126   } else {
127     push @where, "part_pkg.classnum $comparison";
128   }
129 }
130
131 if ( $cgi->param('taxclass')
132      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
133                                 #(should we save a taxclass or a link to taxnum
134                                 # in cust_bill_pkg or something like
135                                 # cust_bill_pkg_tax_location?)
136    )
137 {
138
139   #override taxclass when use_override is specified?  probably
140   #if ( $use_override ) {
141   #
142   #  push @where,
143   #    ' ( '. join(' OR ',
144   #                  map {
145   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
146   #                        '      AND pkgpart_override IS NULL '.
147   #                        '   OR '.
148   #                        '      override.taxclass = '. dbh->quote($_).
149   #                        '      AND pkgpart_override IS NOT NULL '.
150   #                        ' ) '
151   #                      }
152   #                      $cgi->param('taxclass')
153   #               ).
154   #    ' ) ';
155   #
156   #} else {
157
158     push @where,
159       ' ( '. join(' OR ',
160                     map ' part_pkg.taxclass = '.dbh->quote($_),
161                         $cgi->param('taxclass')
162                  ).
163       ' ) ';
164
165   #}
166
167 }
168
169 my @loc_param = qw( city county state country );
170
171 if ( $cgi->param('out') ) {
172
173   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
174   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
175     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
176   }
177
178   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
179     if $cgi->param('istax');
180
181   push @where, "
182     0 = (
183           SELECT COUNT(*) FROM cust_main_county
184            WHERE cust_main_county.tax > 0
185              AND $loc_sql
186         )
187   ";
188
189   #not linked to by anything, but useful for debugging "out of taxable region"
190   if ( grep $cgi->param($_), @loc_param ) {
191
192     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
193
194     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
195     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
196       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
197     }
198
199     push @where, $loc_sql;
200
201   }
202
203 } elsif ( $cgi->param('country') ) {
204
205   my @counties = $cgi->param('county');
206    
207   if ( scalar(@counties) > 1 ) {
208
209     #hacky, could be more efficient.  care if it is ever used for more than the
210     # tax-report_groups filtering kludge
211
212     my $locs_sql =
213       ' ( '. join(' OR ', map {
214
215           my %ph = ( 'county' => dbh->quote($_),
216                      map { $_ => dbh->quote( $cgi->param($_) ) }
217                        qw( city state country )
218                    );
219
220           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
221           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
222             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
223           }
224
225           $loc_sql;
226
227         } @counties
228
229       ). ' ) ';
230
231     push @where, $locs_sql;
232
233   } else {
234
235     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
236
237     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
238     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
239       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
240     }
241
242     push @where, $loc_sql;
243
244   }
245    
246   my($title, $name);
247   if ( $cgi->param('istax') ) {
248     $title = 'Tax credits';
249     $name  = 'tax credits';
250     if ( $cgi->param('taxname') ) {
251       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
252     #} elsif ( $cgi->param('taxnameNULL') {
253     } else {
254       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
255     }
256   } elsif ( $cgi->param('nottax') ) {
257     $title = 'Credit applications to line items';
258     $name  = 'applications';
259     #what can we usefully do with "taxname" ????  look up a class???
260   } else {
261     $title = 'Credit applications to line items';
262     $name  = 'applications';
263     #warn "neither nottax nor istax parameters specified";
264   }
265
266   if ( $cgi->param('taxclassNULL') ) {
267
268     my %hash = ( 'country' => scalar($cgi->param('country')) );
269     foreach (qw( state county )) {
270       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
271     }
272     my $cust_main_county = qsearchs('cust_main_county', \%hash);
273     die "unknown base region for empty taxclass" unless $cust_main_county;
274
275     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
276     push @where, $same_sql if $same_sql;
277
278   }
279
280 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
281
282   # this should really be shoved out to FS::cust_pkg->location_sql or something
283   # along with the code in report_newtax.cgi
284
285   my %pn = (
286    'county'        => 'tax_rate_location.county',
287    'state'         => 'tax_rate_location.state',
288    'city'          => 'tax_rate_location.city',
289    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
290   );
291
292   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
293            qw( city county state locationtaxid );
294
295   push @where,
296     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
297                    keys %ph
298     );
299
300 }
301
302 if ( $cgi->param('itemdesc') ) {
303   if ( $cgi->param('itemdesc') eq 'Tax' ) {
304     push @where, "(itemdesc='Tax' OR itemdesc is null)";
305   } else {
306     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
307   }
308 }
309
310 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
311   my ( $group_op, $group_value ) = ( $1, $2 );
312   if ( $group_op eq '=' ) {
313     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
314     push @where, 'itemdesc = '. dbh->quote($group_value);
315   } elsif ( $group_op eq '!=' ) {
316     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
317   } else {
318     die "guru meditation #00de: group_op $group_op\n";
319   }
320   
321 }
322
323 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
324 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
325
326 if ( $cgi->param('cust_tax') ) {
327   #false laziness -ish w/report_tax.cgi
328   my $cust_exempt;
329   if ( $cgi->param('taxname') ) {
330     my $q_taxname = dbh->quote($cgi->param('taxname'));
331     $cust_exempt =
332       "( tax = 'Y'
333          OR EXISTS ( SELECT 1 FROM cust_main_exemption
334                        WHERE cust_main_exemption.custnum = cust_main.custnum
335                          AND cust_main_exemption.taxname = $q_taxname )
336        )
337       ";
338   } else {
339     $cust_exempt = " tax = 'Y' ";
340   }
341
342   push @where, $cust_exempt;
343 }
344
345 my $use_usage = $cgi->param('use_usage');
346
347 my $count_query;
348 if ( $cgi->param('pkg_tax') ) { #does this mean anything here?
349
350   $count_query =
351     "SELECT COUNT(*),
352             SUM(
353                  ( CASE WHEN part_pkg.setuptax = 'Y'
354                         THEN cust_bill_pkg.setup
355                         ELSE 0
356                    END
357                  )
358                  +
359                  ( CASE WHEN part_pkg.recurtax = 'Y'
360                         THEN cust_bill_pkg.recur
361                         ELSE 0
362                    END
363                  )
364                )
365     ";
366
367   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
368                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
369                "( tax != 'Y' OR tax IS NULL )";
370
371 } elsif ( $cgi->param('taxable') ) { #again, meaningful?
372
373   my $setup_taxable = "(
374     CASE WHEN part_pkg.setuptax = 'Y'
375          THEN 0
376          ELSE cust_bill_pkg.setup
377     END
378   )";
379
380   my $recur_taxable = "(
381     CASE WHEN part_pkg.recurtax = 'Y'
382          THEN 0
383          ELSE cust_bill_pkg.recur
384     END
385   )";
386
387   my $exempt = "(
388     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
389       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
390   )";
391
392   $count_query =
393     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
394
395   push @where,
396     #not tax-exempt package (setup or recur)
397     "(
398           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
399             AND cust_bill_pkg.setup > 0 )
400        OR
401           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
402             AND cust_bill_pkg.recur > 0 )
403     )",
404     #not a tax_exempt customer
405     "( tax != 'Y' OR tax IS NULL )";
406     #not covered in full by a monthly tax exemption (texas tax)
407     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
408
409 } else {
410
411   $count_query = "SELECT COUNT(*), ";
412
413   if ( $use_usage eq 'recurring' ) { #mean anything?
414     $count_query .= "SUM(setup + recur - usage)";
415   } elsif ( $use_usage eq 'usage' ) { #mean anything?
416     $count_query .= "SUM(usage)";
417   } else {
418     $count_query .= "SUM(cust_credit_bill_pkg.amount)";
419   }
420
421 }
422
423 my $join_cust =
424   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum ) 
425     LEFT JOIN cust_main ON ( cust_bill.custnum = cust_main.custnum ) ';
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 part_pkg AS override
437                    ON pkgpart_override = override.pkgpart ';
438   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
439     if $conf->exists('tax-pkg_address');
440
441 } elsif ( $cgi->param('istax') ) {
442
443   #false laziness w/report_tax.cgi $taxfromwhere
444   if ( $conf->exists('tax-pkg_address') ) {
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   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
451             $cgi->param('iscredit') eq 'rate') {
452     $join_pkg .=
453       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
454       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
455   }
456
457     if ( $conf->exists('tax-pkg_address') ) {
458       $join_cust_bill_pkg .= ', billpkgtaxlocationnum )';
459       push @where, "billpkgtaxratelocationnum IS NULL";
460     #} elsif ( $cgi->param('iscredit') eq 'rate' ) {
461     #  $join_pkg .= ', billpkgtaxratelocationnum )';
462     } else {
463       $join_cust_bill_pkg .= ' )';
464       push @where, "billpkgtaxratelocationnum IS NULL";
465     }
466
467 } else { 
468
469   #die?
470   warn "neiether nottax nor istax parameters specified";
471   #same as before?
472   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
473                  LEFT JOIN part_pkg USING ( pkgpart ) ';
474
475 }
476
477 my $where = ' WHERE '. join(' AND ', @where);
478
479 my $join_credit = ' LEFT JOIN cust_credit_bill USING ( creditbillnum )
480                     LEFT JOIN cust_credit      USING ( crednum ) ';
481
482 #if ($use_usage) {
483 #  $count_query .=
484 #    " FROM (SELECT cust_bill_pkg.setup, cust_bill_pkg.recur, 
485 #             ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_bill_pkg_detail
486 #               WHERE cust_bill_pkg.billpkgnum = cust_bill_pkg_detail.billpkgnum
487 #             ) AS usage FROM cust_bill_pkg  $join_cust $join_pkg $where
488 #           ) AS countquery";
489 #} else {
490   $count_query .= " FROM cust_credit_bill_pkg
491                         $join_pkg
492                         $join_cust_bill_pkg
493                         $join_credit
494                         $join_cust
495                       $where";
496 #}
497
498 my @select = ( 'cust_credit_bill_pkg.amount',
499                'cust_bill_pkg.*',
500                'cust_bill._date',
501              );
502 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
503 push @select, 'cust_main.custnum',
504               FS::UI::Web::cust_sql_fields();
505
506 my $query = {
507   'table'     => 'cust_credit_bill_pkg',
508   'addl_from' => "$join_pkg
509                   $join_cust_bill_pkg
510                   $join_credit
511                   $join_cust",
512   'hashref'   => {},
513   'select'    => join(', ', @select ),
514   'extra_sql' => $where,
515   'order_by'  => 'ORDER BY creditbillpkgnum', #cust_bill. or cust_credit._date?
516 };
517
518 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
519 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
520
521 my $conf = new FS::Conf;
522 my $money_char = $conf->config('money_char') || '$';
523
524 </%init>