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