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