should be a proper fix for edge cases where you have taxclass and empty-taxclass...
[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 my @base_param = qw( county county state state country );
193 if ( $conf->exists('tax-ship_address') ) {
194
195   $where .= "
196       AND (    (     ( ship_last IS NULL     OR  ship_last  = '' )
197                  AND ( county       = ? OR ? = '' )
198                  AND ( state        = ? OR ? = '' )
199                  AND   country      = ?
200                )
201             OR (       ship_last IS NOT NULL AND ship_last != ''
202                  AND ( ship_county  = ? OR ? = '' )
203                  AND ( ship_state   = ? OR ? = '' )
204                  AND   ship_country = ?
205                )
206           )
207   ";
208   #    AND payby != 'COMP'
209
210   push @base_param, @base_param;
211
212 } else {
213
214   $where .= "
215       AND ( county  = ? OR ? = '' )
216       AND ( state   = ? OR ? = '' )
217       AND   country = ?
218   ";
219   #    AND payby != 'COMP'
220
221 }
222
223 my $agentname = '';
224 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
225   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
226   die "agent not found" unless $agent;
227   $agentname = $agent->agent;
228   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
229 }
230
231 my $gotcust = "
232   WHERE 0 < ( SELECT COUNT(*) FROM cust_main
233 ";
234 if ( $conf->exists('tax-ship_address') ) {
235
236   $gotcust .= "
237                 WHERE
238
239                 (    cust_main_county.country = cust_main.country
240                   OR cust_main_county.country = cust_main.ship_country
241                 )
242
243                 AND
244
245                 ( 
246
247                   (     ( ship_last IS NULL     OR  ship_last = '' )
248                     AND (    cust_main_county.country = cust_main.country )
249                     AND (    cust_main_county.state = cust_main.state
250                           OR cust_main_county.state = ''
251                           OR cust_main_county.state IS NULL )
252                     AND (    cust_main_county.county = cust_main.county
253                           OR cust_main_county.county = ''
254                           OR cust_main_county.county IS NULL )
255                   )
256   
257                   OR
258   
259                   (       ship_last IS NOT NULL AND ship_last != ''
260                     AND (    cust_main_county.country = cust_main.ship_country )
261                     AND (    cust_main_county.state = cust_main.ship_state
262                           OR cust_main_county.state = ''
263                           OR cust_main_county.state IS NULL )
264                     AND (    cust_main_county.county = cust_main.ship_county
265                           OR cust_main_county.county = ''
266                           OR cust_main_county.county IS NULL )
267                   )
268
269                 )
270
271                 LIMIT 1
272             )
273   ";
274
275 } else {
276
277   $gotcust .= "
278                 WHERE ( cust_main.county  = cust_main_county.county
279                         OR cust_main_county.county = ''
280                         OR cust_main_county.county IS NULL )
281                   AND ( cust_main.state   = cust_main_county.state
282                         OR cust_main_county.state = ''
283                         OR cust_main_county.state IS NULL )
284                   AND ( cust_main.country = cust_main_county.country )
285                 LIMIT 1
286             )
287   ";
288
289 }
290
291 my($total, $tot_taxable, $owed, $tax) = ( 0, 0, 0, 0, 0 );
292 my( $exempt_cust, $exempt_pkg, $exempt_monthly ) = ( 0, 0 );
293 my $out = 'Out of taxable region(s)';
294 my %regions = ();
295 foreach my $r (qsearch('cust_main_county', {}, '', $gotcust) ) {
296   #warn $r->county. ' '. $r->state. ' '. $r->country. "\n";
297
298   my $label = getlabel($r);
299   $regions{$label}->{'label'} = $label;
300   $regions{$label}->{'url_param'} = join(';', map "$_=".$r->$_(), qw( county state country ) );
301
302   my @param = @base_param;
303   my $mywhere = $where;
304
305   if ( $r->taxclass ) {
306
307     $mywhere .= " AND taxclass = ? ";
308     push @param, 'taxclass';
309     $regions{$label}->{'url_param'} .= ';taxclass='. $r->taxclass
310       if $cgi->param('show_taxclasses');
311
312   } else {
313
314     my $same_query = 'SELECT taxclass FROM cust_main_county '.
315                      ' WHERE taxnum != ? AND country = ?';
316     my @same_param = ( 'taxnum', 'country' );
317     foreach my $opt_field (qw( state county )) {
318       if ( $r->$opt_field() ) {
319         $same_query .= " AND $opt_field = ?";
320         push @same_param, $opt_field;
321       } else {
322         $same_query .= " AND $opt_field IS NULL";
323       }
324     }
325
326     my @taxclasses = list_sql( $r, \@same_param, $same_query );
327
328     if ( scalar(@taxclasses) ) {
329       $mywhere .= ' AND '. join(' AND ', map ' taxclass != ? ', @taxclasses );
330       push @param, map \$_, @taxclasses;
331     }
332   
333   }
334
335   my $fromwhere = $from_join_cust. $join_pkg. $mywhere. " AND payby != 'COMP' ";
336
337 #  my $label = getlabel($r);
338 #  $regions{$label}->{'label'} = $label;
339
340   my $nottax = 'pkgnum != 0';
341
342   ## calculate total for this region
343
344   my $t = scalar_sql($r, \@param,
345     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere AND $nottax"
346   );
347   $total += $t;
348   $regions{$label}->{'total'} += $t;
349
350   ## calculate customer-exemption for this region
351
352 ##  my $taxable = $t;
353
354 #  my($taxable, $x_cust) = (0, 0);
355 #  foreach my $e ( grep { $r->get($_.'tax') !~ /^Y/i }
356 #                       qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
357 #    $taxable += scalar_sql($r, \@param, 
358 #      "SELECT SUM($e) $fromwhere AND $nottax AND ( tax != 'Y' OR tax IS NULL )"
359 #    );
360 #
361 #    $x_cust += scalar_sql($r, \@param, 
362 #      "SELECT SUM($e) $fromwhere AND $nottax AND tax = 'Y'"
363 #    );
364 #  }
365
366   my $x_cust = scalar_sql($r, \@param,
367     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur)
368      $fromwhere AND $nottax AND tax = 'Y' "
369   );
370
371   $exempt_cust += $x_cust;
372   $regions{$label}->{'exempt_cust'} += $x_cust;
373   
374   ## calculate package-exemption for this region
375
376   my $x_pkg = scalar_sql($r, \@param,
377     "SELECT SUM(
378                  ( CASE WHEN part_pkg.setuptax = 'Y'
379                         THEN cust_bill_pkg.setup
380                         ELSE 0
381                    END
382                  )
383                  +
384                  ( CASE WHEN part_pkg.recurtax = 'Y'
385                         THEN cust_bill_pkg.recur
386                         ELSE 0
387                    END
388                  )
389                )
390        $fromwhere
391        AND $nottax
392        AND (
393                 ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
394              OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 )
395            )
396        AND ( tax != 'Y' OR tax IS NULL )
397     "
398   );
399   $exempt_pkg += $x_pkg;
400   $regions{$label}->{'exempt_pkg'} += $x_pkg;
401
402   ## calculate monthly exemption (texas tax) for this region
403
404   # count up all the cust_tax_exempt_pkg records associated with
405   # the actual line items.
406
407   my $x_monthly = scalar_sql($r, \@param,
408     "SELECT SUM(amount)
409        FROM cust_tax_exempt_pkg
410        JOIN cust_bill_pkg USING ( billpkgnum )
411        $join_cust $join_pkg
412      $mywhere"
413   );
414 #  if ( $x_monthly ) {
415 #    #warn $r->taxnum(). ": $x_monthly\n";
416 #    $taxable -= $x_monthly;
417 #  }
418
419   $exempt_monthly += $x_monthly;
420   $regions{$label}->{'exempt_monthly'} += $x_monthly;
421
422   my $taxable = $t - $x_cust - $x_pkg - $x_monthly;
423
424   $tot_taxable += $taxable;
425   $regions{$label}->{'taxable'} += $taxable;
426
427   $owed += $taxable * ($r->tax/100);
428   $regions{$label}->{'owed'} += $taxable * ($r->tax/100);
429
430   if ( defined($regions{$label}->{'rate'})
431        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
432     $regions{$label}->{'rate'} = 'variable';
433   } else {
434     $regions{$label}->{'rate'} = $r->tax.'%';
435   }
436
437 }
438
439 my $taxwhere = "$from_join_cust $where AND payby != 'COMP' ";
440 my @taxparam = @base_param;
441 my %base_regions = ();
442 #foreach my $label ( keys %regions ) {
443 foreach my $r (
444   qsearch( 'cust_main_county',
445            {},
446            "DISTINCT
447               country,
448               state,
449               county,
450               CASE WHEN taxname IS NULL THEN '' ELSE taxname END AS taxname,".
451
452               #a little bit unsure of this part... test?
453               #ah, it looks like it winds up being irrelevant as ->{'tax'} 
454               # from $regions is not displayed when show_taxclasses is on
455               ( $cgi->param('show_taxclasses')
456                   ? " CASE WHEN taxclass IS NULL THEN '' ELSE taxclass END "
457                   : " '' "
458               )." AS taxclass"
459            ,
460            $gotcust
461          )
462 ) {
463
464   #warn join('-', map { $r->$_() } qw( country state county taxname ) )."\n";
465
466   my $label = getlabel($r);
467
468   #my $fromwhere = $join_pkg. $where. " AND payby != 'COMP' ";
469   #my @param = @base_param; 
470
471   #match itemdesc if necessary!
472   my $named_tax =
473     $r->taxname
474       ? 'AND itemdesc = '. dbh->quote($r->taxname)
475       : "AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
476
477   my $sql = "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) ".
478             " $taxwhere AND pkgnum = 0 $named_tax";
479
480   my $x = scalar_sql($r, \@taxparam, $sql );
481   $tax += $x;
482   $regions{$label}->{'tax'} += $x;
483
484   if ( $cgi->param('show_taxclasses') ) {
485     my $base_label = getlabel($r, 'no_taxclass'=>1 );
486     $base_regions{$base_label}->{'label'} = $base_label;
487     $base_regions{$base_label}->{'url_param'} =
488       join(';', map "$_=".$r->$_(), qw( county state country ) );
489     $base_regions{$base_label}->{'tax'} += $x;
490   }
491
492 }
493
494 #ordering
495 my @regions =
496   map $regions{$_},
497   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
498   keys %regions;
499
500 my @base_regions =
501   map $base_regions{$_},
502   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
503   keys %base_regions;
504
505 push @regions, {
506   'label'          => 'Total',
507   'url_param'      => '',
508   'total'          => $total,
509   'exempt_cust'    => $exempt_cust,
510   'exempt_pkg'     => $exempt_pkg,
511   'exempt_monthly' => $exempt_monthly,
512   'taxable'        => $tot_taxable,
513   'rate'           => '',
514   'owed'           => $owed,
515   'tax'            => $tax,
516 };
517
518 #-- 
519
520 sub getlabel {
521   my $r = shift;
522   my %opt = @_;
523
524   my $label;
525   if (
526     $r->tax == 0 
527     && ! scalar( qsearch('cust_main_county', { 'state'   => $r->state,
528                                                'county'  => $r->county,
529                                                'country' => $r->country,
530                                                'tax' => { op=>'>', value=>0 },
531                                              }
532                         )
533                )
534
535   ) {
536     #kludge to avoid "will not stay shared" warning
537     my $out = 'Out of taxable region(s)';
538     $label = $out;
539   } elsif ( $r->taxname ) {
540     $label = $r->taxname;
541 #    $regions{$label}->{'taxname'} = $label;
542 #    push @{$regions{$label}->{$_}}, $r->$_() foreach qw( county state country );
543   } else {
544     $label = $r->country;
545     $label = $r->state.", $label" if $r->state;
546     $label = $r->county." county, $label" if $r->county;
547     $label = "$label (". $r->taxclass. ")"
548       if $r->taxclass
549       && $cgi->param('show_taxclasses')
550       && ! $opt{'no_taxclass'};
551     #$label = $r->taxname. " ($label)" if $r->taxname;
552   }
553   return $label;
554 }
555
556 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
557 #to FS::Report or FS::Record or who the fuck knows where)
558 sub scalar_sql {
559   my( $r, $param, $sql ) = @_;
560   #warn "$sql\n";
561   my $sth = dbh->prepare($sql) or die dbh->errstr;
562   $sth->execute( map { ref($_) ? ${$_} : $r->$_() } @$param )
563     or die "Unexpected error executing statement $sql: ". $sth->errstr;
564   $sth->fetchrow_arrayref->[0] || 0;
565 }
566
567 sub list_sql {
568   my( $r, $param, $sql ) = @_;
569   #warn "$sql\n";
570   my $sth = dbh->prepare($sql) or die dbh->errstr;
571   $sth->execute( map $r->$_(), @$param )
572     or die "Unexpected error executing statement $sql: ". $sth->errstr;
573   map $_->[0], @{ $sth->fetchall_arrayref };
574 }
575
576 my $dateagentlink = "begin=$beginning;end=$ending";
577 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
578   if length($agentname);
579 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
580 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
581
582 </%init>