aa85be6869035041b1ed055a8b39724746bbc6b2
[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   foreach my $e ( grep { $r->get($_.'tax') !~ /^Y/i }
81                        qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
82     my $t = scalar_sql($r, \@param, 
83       "SELECT SUM($e) $fromwhere AND $nottax AND ( tax != 'Y' OR tax IS NULL )"
84     );
85
86     my $x = scalar_sql($r, \@param, 
87       "SELECT SUM($e) $fromwhere AND $nottax AND tax = 'Y'"
88     );
89
90     my($sday,$smon,$syear) = (localtime($beginning) )[ 3, 4, 5 ];
91     $monthly_exempt_warning=1 if $sday != 1 && $beginning;
92     $smon++; $syear+=1900;
93
94     my($eday,$emon,$eyear) = (localtime($ending) )[ 3, 4, 5 ];
95     $emon++; $eyear+=1900;
96
97     my $monthly_exemption = scalar_sql($r, [ 'taxnum' ],
98       "SELECT SUM(amount) FROM cust_tax_exempt where taxnum = ? ".
99       "  AND ( year > $syear OR ( year = $syear and month >= $smon ) )".
100       "  AND ( year < $eyear OR ( year = $eyear and month <= $emon ) )"
101     );
102     if ( $monthly_exemption ) {
103       $t -= $monthly_exemption;
104       $x += $monthly_exemption;
105     }
106
107     $taxable += $t;
108     $regions{$label}->{'taxable'} += $t;
109
110     $exempt += $x;
111     $regions{$label}->{'exempt'} += $x;
112
113     $owed += $t * ($r->tax/100);
114     $regions{$label}->{'owed'} += $t * ($r->tax/100);
115
116   }
117
118   if ( defined($regions{$label}->{'rate'})
119        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
120     $regions{$label}->{'rate'} = 'variable';
121   } else {
122     $regions{$label}->{'rate'} = $r->tax.'%';
123   }
124
125 }
126
127 my $taxwhere = "$from_join_cust $where";
128 my @taxparam = @base_param;
129
130 #foreach my $label ( keys %regions ) {
131 foreach my $r (
132   qsearch( 'cust_main_county',
133            {},
134            'DISTINCT ON (country, state, county, taxname) *',
135            $gotcust
136          )
137 ) {
138
139   #warn join('-', map { $r->$_() } qw( country state county taxname ) )."\n";
140
141   my $label = getlabel($r);
142
143   my $fromwhere = $join_pkg. $where;
144   my @param = @base_param; 
145
146   #match itemdesc if necessary!
147   my $named_tax =
148     $r->taxname
149       ? 'AND itemdesc = '. dbh->quote($r->taxname)
150       : "AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
151   my $x = scalar_sql($r, \@taxparam,
152     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $taxwhere ".
153     "AND pkgnum = 0 $named_tax",
154   );
155   $tax += $x;
156   $regions{$label}->{'tax'} += $x;
157
158 }
159
160 #ordering
161 my @regions = map $regions{$_},
162               sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
163               keys %regions;
164
165 push @regions, {
166   'label'     => 'Total',
167   'total'     => $total,
168   'exempt'    => $exempt,
169   'taxable'   => $taxable,
170   'rate'      => '',
171   'tax'       => $tax,
172 };
173
174 #-- 
175
176 sub getlabel {
177   my $r = shift;
178
179   my $label;
180   if ( $r->tax == 0 ) {
181     #kludge to avoid "will not stay shared" warning
182     my $out = 'Out of taxable region(s)';
183     $label = $out;
184   } elsif ( $r->taxname ) {
185     $label = $r->taxname;
186 #    $regions{$label}->{'taxname'} = $label;
187 #    push @{$regions{$label}->{$_}}, $r->$_() foreach qw( county state country );
188   } else {
189     $label = $r->country;
190     $label = $r->state.", $label" if $r->state;
191     $label = $r->county." county, $label" if $r->county;
192     #$label = $r->taxname. " ($label)" if $r->taxname;
193   }
194   return $label;
195 }
196
197 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
198 #to FS::Report or FS::Record or who the fuck knows where)
199 sub scalar_sql {
200   my( $r, $param, $sql ) = @_;
201   #warn "$sql\n";
202   my $sth = dbh->prepare($sql) or die dbh->errstr;
203   $sth->execute( map $r->$_(), @$param )
204     or die "Unexpected error executing statement $sql: ". $sth->errstr;
205   $sth->fetchrow_arrayref->[0] || 0;
206 }
207
208 %>
209
210 <%= header( "Sales Tax Report - $pbeginning through ".($pending||'now'),
211             menubar( 'Main Menu'=>$p, ) )               %>
212 <%= table() %>
213   <TR>
214     <TH ROWSPAN=2></TH>
215     <TH COLSPAN=3>Sales</TH>
216     <TH ROWSPAN=2>Rate</TH>
217     <TH ROWSPAN=2>Tax owed</TH>
218     <TH ROWSPAN=2>Tax invoiced</TH>
219   </TR>
220   <TR>
221     <TH>Total</TH>
222     <TH>Non-taxable</TH>
223     <TH>Taxable</TH>
224   </TR>
225   <% foreach my $region ( @regions ) { %>
226     <TR>
227       <TD><%= $region->{'label'} %></TD>
228       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'total'} ) %></TD>
229       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'exempt'} ) %></TD>
230       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'taxable'} ) %></TD>
231       <TD ALIGN="right"><%= $region->{'rate'} %></TD>
232       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'owed'} ) %></TD>
233       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'tax'} ) %></TD>
234     </TR>
235   <% } %>
236
237 </TABLE>
238
239 <% if ( $monthly_exempt_warning ) { %>
240   <BR>
241   Partial-month tax reports (except for current month) may not be correct due
242   to month-granularity tax exemption (usually "texas tax").  For an accurate
243   report, start on the first of a month and end on the last day of a month (or
244   leave blank for to now).
245 <% } %>
246
247 </BODY>
248 </HTML>
249
250