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