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