correct fallout from duplicate line items
[freeside.git] / httemplate / search / report_tax.cgi
1 <% include("/elements/header.html", "$agentname Sales Tax Report - ".
2               ( $beginning
3                   ? time2str('%h %o %Y ', $beginning )
4                   : ''
5               ).
6               'through '.
7               ( $ending == 4294967295
8                   ? 'now'
9                   : time2str('%h %o %Y', $ending )
10               )
11           )
12 %>
13
14 <% include('/elements/table-grid.html') %>
15
16   <TR>
17     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
18     <TH CLASS="grid" BGCOLOR="#cccccc" COLSPAN=9>Sales</TH>
19     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
20     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Rate</TH>
21     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
22     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Tax owed</TH>
23 % unless ( $cgi->param('show_taxclasses') ) { 
24
25       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Tax invoiced</TH>
26 % } 
27
28   </TR>
29   <TR>
30     <TH CLASS="grid" BGCOLOR="#cccccc">Total</TH>
31     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
32     <TH CLASS="grid" BGCOLOR="#cccccc">Non-taxable<BR><FONT SIZE=-1>(tax-exempt customer)</FONT></TH>
33     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
34     <TH CLASS="grid" BGCOLOR="#cccccc">Non-taxable<BR><FONT SIZE=-1>(tax-exempt package)</FONT></TH>
35     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
36     <TH CLASS="grid" BGCOLOR="#cccccc">Non-taxable<BR><FONT SIZE=-1>(monthly exemption)</FONT></TH>
37     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
38     <TH CLASS="grid" BGCOLOR="#cccccc">Taxable</TH>
39   </TR>
40 % my $bgcolor1 = '#eeeeee';
41 %   my $bgcolor2 = '#ffffff';
42 %   my $bgcolor;
43 %
44 % foreach my $region ( @regions ) {
45 %
46 %       if ( $bgcolor eq $bgcolor1 ) {
47 %         $bgcolor = $bgcolor2;
48 %       } else {
49 %         $bgcolor = $bgcolor1;
50 %       }
51 %
52 %       my $link = '';
53 %       if ( $region->{'label'} ne 'Total' ) {
54 %         if ( $region->{'label'} eq $out ) {
55 %           $link = ';out=1';
56 %         } else {
57 %           $link = ';'. $region->{'url_param'};
58 %         }
59 %       }
60 %
61 %
62 %
63 %
64 %  
65
66
67     <TR>
68       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} %></TD>
69       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
70         <A HREF="<% $baselink. $link %>;nottax=1"><% $money_char %><% sprintf('%.2f', $region->{'total'} ) %></A>
71       </TD>
72       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> - </B></FONT></TD>
73       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
74         <A HREF="<% $baselink. $link %>;nottax=1;cust_tax=Y"><% $money_char %><% sprintf('%.2f', $region->{'exempt_cust'} ) %></A>
75       </TD>
76       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> - </B></FONT></TD>
77       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
78         <A HREF="<% $baselink. $link %>;nottax=1;pkg_tax=Y"><% $money_char %><% sprintf('%.2f', $region->{'exempt_pkg'} ) %></A>
79       </TD>
80       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> - </B></FONT></TD>
81       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
82         <A HREF="<% $exemptlink. $link %>"><% $money_char %><% sprintf('%.2f', $region->{'exempt_monthly'} ) %></A>
83         </TD>
84       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> = </B></FONT></TD>
85       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
86         <% $money_char %><% sprintf('%.2f', $region->{'taxable'} ) %></A>
87       </TD>
88       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} eq 'Total' ? '' : '<FONT FACE="sans-serif" SIZE="+1"><B> X </B></FONT>' %></TD>
89       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right"><% $region->{'rate'} %></TD>
90       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} eq 'Total' ? '' : '<FONT FACE="sans-serif" SIZE="+1"><B> = </B></FONT>' %></TD>
91       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
92         <% $money_char %><% sprintf('%.2f', $region->{'owed'} ) %>
93       </TD>
94 % unless ( $cgi->param('show_taxclasses') ) { 
95
96         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
97           <A HREF="<% $baselink. $link %>;istax=1"><% $money_char %><% sprintf('%.2f', $region->{'tax'} ) %></A>
98         </TD>
99 % } 
100
101     </TR>
102 % } 
103
104
105 </TABLE>
106 % if ( $cgi->param('show_taxclasses') ) { 
107
108
109   <BR>
110   <% include('/elements/table-grid.html') %>
111   <TR>
112     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
113     <TH CLASS="grid" BGCOLOR="#cccccc">Tax invoiced</TH>
114   </TR>
115 % #some false laziness w/above
116 %     $bgcolor1 = '#eeeeee';
117 %     $bgcolor2 = '#ffffff';
118 %     foreach my $region ( @base_regions ) {
119 %
120 %       if ( $bgcolor eq $bgcolor1 ) {
121 %         $bgcolor = $bgcolor2;
122 %       } else {
123 %         $bgcolor = $bgcolor1;
124 %       }
125 %
126 %       my $link = '';
127 %       #if ( $region->{'label'} ne 'Total' ) {
128 %         if ( $region->{'label'} eq $out ) {
129 %           $link = ';out=1';
130 %         } else {
131 %           $link = ';'. $region->{'url_param'};
132 %         }
133 %       #}
134 %  
135
136
137     <TR>
138       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} %></TD>
139       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
140         <A HREF="<% $baselink. $link %>;istax=1"><% $money_char %><% sprintf('%.2f', $region->{'tax'} ) %></A>
141       </TD>
142     </TR>
143 % } 
144 %
145 %     if ( $bgcolor eq $bgcolor1 ) {
146 %       $bgcolor = $bgcolor2;
147 %     } else {
148 %       $bgcolor = $bgcolor1;
149 %     }
150 %  
151
152
153   <TR>
154    <TD CLASS="grid" BGCOLOR="<% $bgcolor %>">Total</TD>
155     <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
156       <A HREF="<% $baselink %>;istax=1"><% $money_char %><% sprintf('%.2f', $tax ) %></A>
157     </TD>
158   </TR>
159
160   </TABLE>
161 % } 
162
163
164 </BODY>
165 </HTML>
166 <%init>
167
168 die "access denied"
169   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
170
171 my $conf = new FS::Conf;
172 my $money_char = $conf->config('money_char') || '$';
173
174 my $user = getotaker;
175
176 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
177
178 my $join_cust = "
179     JOIN cust_bill USING ( invnum ) 
180     LEFT JOIN cust_main USING ( custnum )
181 ";
182 my $from_join_cust = "
183     FROM cust_bill_pkg
184     $join_cust
185 "; 
186 my $join_pkg = "
187     LEFT JOIN cust_pkg USING ( pkgnum )
188     LEFT JOIN part_pkg USING ( pkgpart )
189 ";
190
191 my $where = "WHERE _date >= $beginning AND _date <= $ending ".
192             "AND (duplicate IS NULL or duplicate = '')";
193 my @base_param = qw( county county state state country );
194 if ( $conf->exists('tax-ship_address') ) {
195
196   $where .= "
197       AND (    (     ( ship_last IS NULL     OR  ship_last  = '' )
198                  AND ( county       = ? OR ? = '' )
199                  AND ( state        = ? OR ? = '' )
200                  AND   country      = ?
201                )
202             OR (       ship_last IS NOT NULL AND ship_last != ''
203                  AND ( ship_county  = ? OR ? = '' )
204                  AND ( ship_state   = ? OR ? = '' )
205                  AND   ship_country = ?
206                )
207           )
208   ";
209   #    AND payby != 'COMP'
210
211   push @base_param, @base_param;
212
213 } else {
214
215   $where .= "
216       AND ( county  = ? OR ? = '' )
217       AND ( state   = ? OR ? = '' )
218       AND   country = ?
219   ";
220   #    AND payby != 'COMP'
221
222 }
223
224 my $agentname = '';
225 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
226   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
227   die "agent not found" unless $agent;
228   $agentname = $agent->agent;
229   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
230 }
231
232 my $gotcust = "
233   WHERE 0 < ( SELECT COUNT(*) FROM cust_main
234 ";
235 if ( $conf->exists('tax-ship_address') ) {
236
237   $gotcust .= "
238                 WHERE
239
240                 (    cust_main_county.country = cust_main.country
241                   OR cust_main_county.country = cust_main.ship_country
242                 )
243
244                 AND
245
246                 ( 
247
248                   (     ( ship_last IS NULL     OR  ship_last = '' )
249                     AND (    cust_main_county.country = cust_main.country )
250                     AND (    cust_main_county.state = cust_main.state
251                           OR cust_main_county.state = ''
252                           OR cust_main_county.state IS NULL )
253                     AND (    cust_main_county.county = cust_main.county
254                           OR cust_main_county.county = ''
255                           OR cust_main_county.county IS NULL )
256                   )
257   
258                   OR
259   
260                   (       ship_last IS NOT NULL AND ship_last != ''
261                     AND (    cust_main_county.country = cust_main.ship_country )
262                     AND (    cust_main_county.state = cust_main.ship_state
263                           OR cust_main_county.state = ''
264                           OR cust_main_county.state IS NULL )
265                     AND (    cust_main_county.county = cust_main.ship_county
266                           OR cust_main_county.county = ''
267                           OR cust_main_county.county IS NULL )
268                   )
269
270                 )
271
272                 LIMIT 1
273             )
274   ";
275
276 } else {
277
278   $gotcust .= "
279                 WHERE ( cust_main.county  = cust_main_county.county
280                         OR cust_main_county.county = ''
281                         OR cust_main_county.county IS NULL )
282                   AND ( cust_main.state   = cust_main_county.state
283                         OR cust_main_county.state = ''
284                         OR cust_main_county.state IS NULL )
285                   AND ( cust_main.country = cust_main_county.country )
286                 LIMIT 1
287             )
288   ";
289
290 }
291
292 my($total, $tot_taxable, $owed, $tax) = ( 0, 0, 0, 0, 0 );
293 my( $exempt_cust, $exempt_pkg, $exempt_monthly ) = ( 0, 0 );
294 my $out = 'Out of taxable region(s)';
295 my %regions = ();
296 foreach my $r (qsearch('cust_main_county', {}, '', $gotcust) ) {
297   #warn $r->county. ' '. $r->state. ' '. $r->country. "\n";
298
299   my $label = getlabel($r);
300   $regions{$label}->{'label'} = $label;
301   $regions{$label}->{'url_param'} = join(';', map "$_=".$r->$_(), qw( county state country ) );
302
303   my @param = @base_param;
304   my $mywhere = $where;
305
306   if ( $r->taxclass ) {
307
308     $mywhere .= " AND taxclass = ? ";
309     push @param, 'taxclass';
310     $regions{$label}->{'url_param'} .= ';taxclass='. $r->taxclass
311       if $cgi->param('show_taxclasses');
312
313   } else {
314
315     $regions{$label}->{'url_param'} .= ';taxclassNULL=1'
316       if $cgi->param('show_taxclasses');
317
318     my $same_sql = $r->sql_taxclass_sameregion;
319     $mywhere .= " AND $same_sql" if $same_sql;
320
321   }
322
323   my $fromwhere = $from_join_cust. $join_pkg. $mywhere. " AND payby != 'COMP' ";
324
325 #  my $label = getlabel($r);
326 #  $regions{$label}->{'label'} = $label;
327
328   my $nottax = 'pkgnum != 0';
329
330   ## calculate total for this region
331
332   my $t = scalar_sql($r, \@param,
333     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere AND $nottax"
334   );
335   $total += $t;
336   $regions{$label}->{'total'} += $t;
337
338   ## calculate customer-exemption for this region
339
340 ##  my $taxable = $t;
341
342 #  my($taxable, $x_cust) = (0, 0);
343 #  foreach my $e ( grep { $r->get($_.'tax') !~ /^Y/i }
344 #                       qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
345 #    $taxable += scalar_sql($r, \@param, 
346 #      "SELECT SUM($e) $fromwhere AND $nottax AND ( tax != 'Y' OR tax IS NULL )"
347 #    );
348 #
349 #    $x_cust += scalar_sql($r, \@param, 
350 #      "SELECT SUM($e) $fromwhere AND $nottax AND tax = 'Y'"
351 #    );
352 #  }
353
354   my $x_cust = scalar_sql($r, \@param,
355     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur)
356      $fromwhere AND $nottax AND tax = 'Y' "
357   );
358
359   $exempt_cust += $x_cust;
360   $regions{$label}->{'exempt_cust'} += $x_cust;
361   
362   ## calculate package-exemption for this region
363
364   my $x_pkg = scalar_sql($r, \@param,
365     "SELECT SUM(
366                  ( CASE WHEN part_pkg.setuptax = 'Y'
367                         THEN cust_bill_pkg.setup
368                         ELSE 0
369                    END
370                  )
371                  +
372                  ( CASE WHEN part_pkg.recurtax = 'Y'
373                         THEN cust_bill_pkg.recur
374                         ELSE 0
375                    END
376                  )
377                )
378        $fromwhere
379        AND $nottax
380        AND (
381                 ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
382              OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 )
383            )
384        AND ( tax != 'Y' OR tax IS NULL )
385     "
386   );
387   $exempt_pkg += $x_pkg;
388   $regions{$label}->{'exempt_pkg'} += $x_pkg;
389
390   ## calculate monthly exemption (texas tax) for this region
391
392   # count up all the cust_tax_exempt_pkg records associated with
393   # the actual line items.
394
395   my $x_monthly = scalar_sql($r, \@param,
396     "SELECT SUM(amount)
397        FROM cust_tax_exempt_pkg
398        JOIN cust_bill_pkg USING ( billpkgnum )
399        $join_cust $join_pkg
400      $mywhere"
401   );
402 #  if ( $x_monthly ) {
403 #    #warn $r->taxnum(). ": $x_monthly\n";
404 #    $taxable -= $x_monthly;
405 #  }
406
407   $exempt_monthly += $x_monthly;
408   $regions{$label}->{'exempt_monthly'} += $x_monthly;
409
410   my $taxable = $t - $x_cust - $x_pkg - $x_monthly;
411
412   $tot_taxable += $taxable;
413   $regions{$label}->{'taxable'} += $taxable;
414
415   $owed += $taxable * ($r->tax/100);
416   $regions{$label}->{'owed'} += $taxable * ($r->tax/100);
417
418   if ( defined($regions{$label}->{'rate'})
419        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
420     $regions{$label}->{'rate'} = 'variable';
421   } else {
422     $regions{$label}->{'rate'} = $r->tax.'%';
423   }
424
425 }
426
427 my $taxwhere = "$from_join_cust $where AND payby != 'COMP' ";
428 my @taxparam = @base_param;
429 my %base_regions = ();
430 #foreach my $label ( keys %regions ) {
431 foreach my $r (
432   qsearch( 'cust_main_county',
433            {},
434            "DISTINCT
435               country,
436               state,
437               county,
438               CASE WHEN taxname IS NULL THEN '' ELSE taxname END AS taxname,".
439
440               #a little bit unsure of this part... test?
441               #ah, it looks like it winds up being irrelevant as ->{'tax'} 
442               # from $regions is not displayed when show_taxclasses is on
443               ( $cgi->param('show_taxclasses')
444                   ? " CASE WHEN taxclass IS NULL THEN '' ELSE taxclass END "
445                   : " '' "
446               )." AS taxclass"
447            ,
448            $gotcust
449          )
450 ) {
451
452   #warn join('-', map { $r->$_() } qw( country state county taxname ) )."\n";
453
454   my $label = getlabel($r);
455
456   #my $fromwhere = $join_pkg. $where. " AND payby != 'COMP' ";
457   #my @param = @base_param; 
458
459   #match itemdesc if necessary!
460   my $named_tax =
461     $r->taxname
462       ? 'AND itemdesc = '. dbh->quote($r->taxname)
463       : "AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
464
465   my $sql = "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) ".
466             " $taxwhere AND pkgnum = 0 $named_tax";
467
468   my $x = scalar_sql($r, \@taxparam, $sql );
469   $tax += $x;
470   $regions{$label}->{'tax'} += $x;
471
472   if ( $cgi->param('show_taxclasses') ) {
473     my $base_label = getlabel($r, 'no_taxclass'=>1 );
474     $base_regions{$base_label}->{'label'} = $base_label;
475     $base_regions{$base_label}->{'url_param'} =
476       join(';', map "$_=".$r->$_(), qw( county state country ) );
477     $base_regions{$base_label}->{'tax'} += $x;
478   }
479
480 }
481
482 #ordering
483 my @regions =
484   map $regions{$_},
485   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
486   keys %regions;
487
488 my @base_regions =
489   map $base_regions{$_},
490   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
491   keys %base_regions;
492
493 push @regions, {
494   'label'          => 'Total',
495   'url_param'      => '',
496   'total'          => $total,
497   'exempt_cust'    => $exempt_cust,
498   'exempt_pkg'     => $exempt_pkg,
499   'exempt_monthly' => $exempt_monthly,
500   'taxable'        => $tot_taxable,
501   'rate'           => '',
502   'owed'           => $owed,
503   'tax'            => $tax,
504 };
505
506 #-- 
507
508 sub getlabel {
509   my $r = shift;
510   my %opt = @_;
511
512   my $label;
513   if (
514     $r->tax == 0 
515     && ! scalar( qsearch('cust_main_county', { 'state'   => $r->state,
516                                                'county'  => $r->county,
517                                                'country' => $r->country,
518                                                'tax' => { op=>'>', value=>0 },
519                                              }
520                         )
521                )
522
523   ) {
524     #kludge to avoid "will not stay shared" warning
525     my $out = 'Out of taxable region(s)';
526     $label = $out;
527   } elsif ( $r->taxname ) {
528     $label = $r->taxname;
529 #    $regions{$label}->{'taxname'} = $label;
530 #    push @{$regions{$label}->{$_}}, $r->$_() foreach qw( county state country );
531   } else {
532     $label = $r->country;
533     $label = $r->state.", $label" if $r->state;
534     $label = $r->county." county, $label" if $r->county;
535     $label = "$label (". $r->taxclass. ")"
536       if $r->taxclass
537       && $cgi->param('show_taxclasses')
538       && ! $opt{'no_taxclass'};
539     #$label = $r->taxname. " ($label)" if $r->taxname;
540   }
541   return $label;
542 }
543
544 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
545 #to FS::Report or FS::Record or who the fuck knows where)
546 sub scalar_sql {
547   my( $r, $param, $sql ) = @_;
548   #warn "$sql\n";
549   my $sth = dbh->prepare($sql) or die dbh->errstr;
550   $sth->execute( map $r->$_(), @$param )
551     or die "Unexpected error executing statement $sql: ". $sth->errstr;
552   $sth->fetchrow_arrayref->[0] || 0;
553 }
554
555 my $dateagentlink = "begin=$beginning;end=$ending";
556 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
557   if length($agentname);
558 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
559 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
560
561 </%init>