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