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