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