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