This commit was generated by cvs2svn to compensate for changes in r4407,
[freeside.git] / httemplate / search / report_tax.cgi
1 <!-- mason kludge -->
2 <%
3
4 my $user = getotaker;
5
6 $cgi->param('beginning') =~ /^([ 0-9\-\/]{0,10})$/;
7 my $pbeginning = $1;
8 my $beginning = $1 ? str2time($1) : 0;
9
10 $cgi->param('ending') =~ /^([ 0-9\-\/]{0,10})$/;
11 my $pending = $1;
12 my $ending = ( $1 ? str2time($1) : 4294880896 ) + 86399;
13
14 my $from_join_cust = "
15   FROM cust_bill_pkg
16     JOIN cust_bill USING ( invnum ) 
17     JOIN cust_main USING ( custnum )
18 ";
19 my $join_pkg = "
20     JOIN cust_pkg USING ( pkgnum )
21     JOIN part_pkg USING ( pkgpart )
22 ";
23 my $where = "
24   WHERE _date >= $beginning AND _date <= $ending
25     AND ( county  = ? OR ? = '' )
26     AND ( state   = ? OR ? = '' )
27     AND ( country = ? )
28     AND payby != 'COMP'
29 ";
30 my @base_param = qw( county county state state country );
31
32 my $gotcust = "
33   WHERE 0 < ( SELECT COUNT(*) FROM cust_main
34               WHERE ( cust_main.county  = cust_main_county.county
35                       OR cust_main_county.county = ''
36                       OR cust_main_county.county IS NULL )
37                 AND ( cust_main.state   = cust_main_county.state
38                       OR cust_main_county.state = ''
39                       OR cust_main_county.state IS NULL )
40                 AND ( cust_main.country = cust_main_county.country )
41               LIMIT 1
42             )
43 ";
44
45 my $monthly_exempt_warning = 0;
46 my($total, $exempt, $taxable, $owed, $tax) = ( 0, 0, 0, 0, 0 );
47 my $out = 'Out of taxable region(s)';
48 my %regions;
49 foreach my $r (qsearch('cust_main_county', {}, '', $gotcust) ) {
50   #warn $r->county. ' '. $r->state. ' '. $r->country. "\n";
51
52   my $label = getlabel($r);
53   $regions{$label}->{'label'} = $label;
54
55   my $fromwhere = $from_join_cust. $join_pkg. $where;
56   my @param = @base_param; 
57
58   if ( $r->taxclass ) {
59     $fromwhere .= " AND ( taxclass = ?  ) ";
60     push @param, 'taxclass';
61   }
62
63   my $nottax = 'pkgnum != 0';
64
65   my $a = scalar_sql($r, \@param,
66     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere AND $nottax"
67   );
68   $total += $a;
69   $regions{$label}->{'total'} += $a;
70
71   foreach my $e ( grep { $r->get($_.'tax') =~ /^Y/i }
72                        qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
73     my $x = scalar_sql($r, \@param,
74       "SELECT SUM($e) $fromwhere AND $nottax"
75     );
76     $exempt += $x;
77     $regions{$label}->{'exempt'} += $x;
78   }
79
80   my($t, $x) = (0, 0);
81   foreach my $e ( grep { $r->get($_.'tax') !~ /^Y/i }
82                        qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
83     $t += scalar_sql($r, \@param, 
84       "SELECT SUM($e) $fromwhere AND $nottax AND ( tax != 'Y' OR tax IS NULL )"
85     );
86
87     $x += scalar_sql($r, \@param, 
88       "SELECT SUM($e) $fromwhere AND $nottax AND tax = 'Y'"
89     );
90   }
91
92   my($sday,$smon,$syear) = (localtime($beginning) )[ 3, 4, 5 ];
93   $monthly_exempt_warning=1 if $sday != 1 && $beginning;
94   $smon++; $syear+=1900;
95
96   my $eending = ( $ending == 4294967295 ) ? time : $ending;
97   my($eday,$emon,$eyear) = (localtime($eending) )[ 3, 4, 5 ];
98   $emon++; $eyear+=1900;
99
100   my $monthly_exemption = scalar_sql($r, [ 'taxnum' ],
101     "SELECT SUM(amount) FROM cust_tax_exempt where taxnum = ? ".
102     "  AND ( year > $syear OR ( year = $syear and month >= $smon ) )".
103     "  AND ( year < $eyear OR ( year = $eyear and month <= $emon ) )"
104   );
105   #warn $r->taxnum(). ": $monthly_exemption\n";
106   if ( $monthly_exemption ) {
107     $t -= $monthly_exemption;
108     $x += $monthly_exemption;
109   }
110
111   $taxable += $t;
112   $regions{$label}->{'taxable'} += $t;
113
114   $exempt += $x;
115   $regions{$label}->{'exempt'} += $x;
116
117   $owed += $t * ($r->tax/100);
118   $regions{$label}->{'owed'} += $t * ($r->tax/100);
119
120   if ( defined($regions{$label}->{'rate'})
121        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
122     $regions{$label}->{'rate'} = 'variable';
123   } else {
124     $regions{$label}->{'rate'} = $r->tax.'%';
125   }
126
127 }
128
129 my $taxwhere = "$from_join_cust $where";
130 my @taxparam = @base_param;
131
132 #foreach my $label ( keys %regions ) {
133 foreach my $r (
134   qsearch( 'cust_main_county',
135            {},
136            'DISTINCT ON (country, state, county, taxname) *',
137            $gotcust
138          )
139 ) {
140
141   #warn join('-', map { $r->$_() } qw( country state county taxname ) )."\n";
142
143   my $label = getlabel($r);
144
145   my $fromwhere = $join_pkg. $where;
146   my @param = @base_param; 
147
148   #match itemdesc if necessary!
149   my $named_tax =
150     $r->taxname
151       ? 'AND itemdesc = '. dbh->quote($r->taxname)
152       : "AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
153   my $x = scalar_sql($r, \@taxparam,
154     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $taxwhere ".
155     "AND pkgnum = 0 $named_tax",
156   );
157   $tax += $x;
158   $regions{$label}->{'tax'} += $x;
159
160 }
161
162 #ordering
163 my @regions = map $regions{$_},
164               sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
165               keys %regions;
166
167 push @regions, {
168   'label'     => 'Total',
169   'total'     => $total,
170   'exempt'    => $exempt,
171   'taxable'   => $taxable,
172   'rate'      => '',
173   'owed'      => $owed,
174   'tax'       => $tax,
175 };
176
177 #-- 
178
179 sub getlabel {
180   my $r = shift;
181
182   my $label;
183   if ( $r->tax == 0 ) {
184     #kludge to avoid "will not stay shared" warning
185     my $out = 'Out of taxable region(s)';
186     $label = $out;
187   } elsif ( $r->taxname ) {
188     $label = $r->taxname;
189 #    $regions{$label}->{'taxname'} = $label;
190 #    push @{$regions{$label}->{$_}}, $r->$_() foreach qw( county state country );
191   } else {
192     $label = $r->country;
193     $label = $r->state.", $label" if $r->state;
194     $label = $r->county." county, $label" if $r->county;
195     #$label = $r->taxname. " ($label)" if $r->taxname;
196   }
197   return $label;
198 }
199
200 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
201 #to FS::Report or FS::Record or who the fuck knows where)
202 sub scalar_sql {
203   my( $r, $param, $sql ) = @_;
204   #warn "$sql\n";
205   my $sth = dbh->prepare($sql) or die dbh->errstr;
206   $sth->execute( map $r->$_(), @$param )
207     or die "Unexpected error executing statement $sql: ". $sth->errstr;
208   $sth->fetchrow_arrayref->[0] || 0;
209 }
210
211 %>
212
213 <%= header( "Sales Tax Report - $pbeginning through ".($pending||'now'),
214             menubar( 'Main Menu'=>$p, ) )               %>
215 <%= table() %>
216   <TR>
217     <TH ROWSPAN=2></TH>
218     <TH COLSPAN=3>Sales</TH>
219     <TH ROWSPAN=2>Rate</TH>
220     <TH ROWSPAN=2>Tax owed</TH>
221     <TH ROWSPAN=2>Tax invoiced</TH>
222   </TR>
223   <TR>
224     <TH>Total</TH>
225     <TH>Non-taxable</TH>
226     <TH>Taxable</TH>
227   </TR>
228   <% foreach my $region ( @regions ) { %>
229     <TR>
230       <TD><%= $region->{'label'} %></TD>
231       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'total'} ) %></TD>
232       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'exempt'} ) %></TD>
233       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'taxable'} ) %></TD>
234       <TD ALIGN="right"><%= $region->{'rate'} %></TD>
235       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'owed'} ) %></TD>
236       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'tax'} ) %></TD>
237     </TR>
238   <% } %>
239
240 </TABLE>
241
242 <% if ( $monthly_exempt_warning ) { %>
243   <BR>
244   Partial-month tax reports (except for current month) may not be correct due
245   to month-granularity tax exemption (usually "texas tax").  For an accurate
246   report, start on the first of a month and end on the last day of a month (or
247   leave blank for to now).
248 <% } %>
249
250 </BODY>
251 </HTML>
252
253