838335b780e462e91d88221da70d76f7cb14306b
[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($total, $exempt, $taxable, $tax) = ( 0, 0, 0, 0 );
46 my $out = 'Out of taxable region(s)';
47 my %regions;
48 foreach my $r (qsearch('cust_main_county', {}, '', $gotcust) ) {
49   #warn $r->county. ' '. $r->state. ' '. $r->country. "\n";
50
51   my $label = getlabel($r);
52   $regions{$label}->{'label'} = $label;
53
54   my $fromwhere = $from_join_cust. $join_pkg. $where;
55   my @param = @base_param; 
56
57   if ( $r->taxclass ) {
58     $fromwhere .= " AND ( taxclass = ?  ) ";
59     push @param, 'taxclass';
60   }
61
62   my $nottax = 'pkgnum != 0';
63
64   my $a = scalar_sql($r, \@param,
65     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere AND $nottax"
66   );
67   $total += $a;
68   $regions{$label}->{'total'} += $a;
69
70   foreach my $e ( grep { $r->get($_.'tax') =~ /^Y/i }
71                        qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
72     my $x = scalar_sql($r, \@param,
73       "SELECT SUM($e) $fromwhere AND $nottax"
74     );
75     $exempt += $x;
76     $regions{$label}->{'exempt'} += $x;
77   }
78
79   foreach my $e ( grep { $r->get($_.'tax') !~ /^Y/i }
80                        qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
81     my $t = scalar_sql($r, \@param, 
82       "SELECT SUM($e) $fromwhere AND $nottax AND ( tax != 'Y' OR tax IS NULL )"
83     );
84     $taxable += $t;
85     $regions{$label}->{'taxable'} += $t;
86     $owed += $t * ($r->tax/100);
87     $regions{$label}->{'owed'} += $t * ($r->tax/100);
88
89     my $x = scalar_sql($r, \@param, 
90       "SELECT SUM($e) $fromwhere AND $nottax AND tax = 'Y'"
91     );
92     $exempt += $x;
93     $regions{$label}->{'exempt'} += $x;
94   }
95
96   if ( defined($regions{$label}->{'rate'})
97        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
98     $regions{$label}->{'rate'} = 'variable';
99   } else {
100     $regions{$label}->{'rate'} = $r->tax.'%';
101   }
102
103 }
104
105 my $taxwhere = "$from_join_cust $where";
106 my @taxparam = @base_param;
107
108 #foreach my $label ( keys %regions ) {
109 foreach my $r (
110   qsearch( 'cust_main_county',
111            {},
112            'DISTINCT ON (country, state, county, taxname) *',
113            $gotcust
114          )
115 ) {
116
117   #warn join('-', map { $r->$_() } qw( country state county taxname ) )."\n";
118
119   my $label = getlabel($r);
120
121   my $fromwhere = $join_pkg. $where;
122   my @param = @base_param; 
123
124   #match itemdesc if necessary!
125   my $named_tax = $r->taxname ? 'AND itemdesc = '. dbh->quote($r->taxname) : '';
126   my $x = scalar_sql($r, \@taxparam,
127     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $taxwhere ".
128     "AND pkgnum = 0 $named_tax",
129   );
130   $tax += $x;
131   $regions{$label}->{'tax'} += $x;
132
133 }
134
135 #ordering
136 my @regions = map $regions{$_},
137               sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
138               keys %regions;
139
140 push @regions, {
141   'label'     => 'Total',
142   'total'     => $total,
143   'exempt'    => $exempt,
144   'taxable'   => $taxable,
145   'rate'      => '',
146   'tax'       => $tax,
147 };
148
149 #-- 
150
151 sub getlabel {
152   my $r = shift;
153   if ( $r->tax == 0 ) {
154     $label = $out;
155   } elsif ( $r->taxname ) {
156     $label = $r->taxname;
157 #    $regions{$label}->{'taxname'} = $label;
158 #    push @{$regions{$label}->{$_}}, $r->$_() foreach qw( county state country );
159   } else {
160     $label = $r->country;
161     $label = $r->state.", $label" if $r->state;
162     $label = $r->county." county, $label" if $r->county;
163     #$label = $r->taxname. " ($label)" if $r->taxname;
164   }
165   return $label;
166 }
167
168 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
169 #to FS::Report or FS::Record or who the fuck knows where)
170 sub scalar_sql {
171   my( $r, $param, $sql ) = @_;
172   #warn "$sql\n";
173   my $sth = dbh->prepare($sql) or die dbh->errstr;
174   $sth->execute( map $r->$_(), @$param )
175     or die "Unexpected error executing statement $sql: ". $sth->errstr;
176   $sth->fetchrow_arrayref->[0] || 0;
177 }
178
179 %>
180
181 <%= header( "Sales Tax Report - $pbeginning through ".($pending||'now'),
182             menubar( 'Main Menu'=>$p, ) )               %>
183 <%= table() %>
184   <TR>
185     <TH ROWSPAN=2></TH>
186     <TH COLSPAN=3>Sales</TH>
187     <TH ROWSPAN=2>Rate</TH>
188     <TH ROWSPAN=2>Tax owed</TH>
189     <TH ROWSPAN=2>Tax invoiced</TH>
190   </TR>
191   <TR>
192     <TH>Total</TH>
193     <TH>Non-taxable</TH>
194     <TH>Taxable</TH>
195   </TR>
196   <% foreach my $region ( @regions ) { %>
197     <TR>
198       <TD><%= $region->{'label'} %></TD>
199       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'total'} ) %></TD>
200       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'exempt'} ) %></TD>
201       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'taxable'} ) %></TD>
202       <TD ALIGN="right"><%= $region->{'rate'} %></TD>
203       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'owed'} ) %></TD>
204       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'tax'} ) %></TD>
205     </TR>
206   <% } %>
207
208 </TABLE>
209
210 </BODY>
211 </HTML>
212
213