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