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