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