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