fix joins for proper tax reporting
[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($total, $exempt, $taxable, $tax) = ( 0, 0, 0, 0 );
15 my $out = 'Out of taxable region(s)';
16 my %regions;
17 foreach my $r (
18   qsearch('cust_main_county', {}, '',
19           "WHERE 0 < ( SELECT COUNT(*) FROM cust_main
20                        WHERE ( cust_main.county  = cust_main_county.county
21                                OR cust_main_county.county = ''
22                                OR cust_main_county.county IS NULL )
23                          AND ( cust_main.state   = cust_main_county.state
24                                OR cust_main_county.state = ''
25                                OR cust_main_county.state IS NULL )
26                          AND ( cust_main.country = cust_main_county.country )
27                        LIMIT 1
28                      )"
29          )
30 ) {
31   #warn $r->county. ' '. $r->state. ' '. $r->country. "\n";
32   my $label;
33   if ( $r->tax == 0 ) {
34     $label = $out;
35   } elsif ( $r->taxname ) {
36     $label = $r->taxname;
37   } else {
38     $label = $r->country;
39     $label = $r->state.", $label" if $r->state;
40     $label = $r->county." county, $label" if $r->county;
41   }
42
43   my $fromwhere = "
44     FROM cust_bill_pkg
45       JOIN cust_bill USING ( invnum ) 
46       JOIN cust_main USING ( custnum )
47       LEFT OUTER JOIN cust_pkg USING ( pkgnum )
48       LEFT OUTER JOIN part_pkg USING ( pkgpart )
49     WHERE _date >= $beginning AND _date <= $ending
50       AND ( county  = ? OR ? = '' )
51       AND ( state   = ? OR ? = '' )
52       AND ( country = ? )
53       AND payby != 'COMP'
54   ";
55   my @param = qw( county county state state country ); # taxclass);
56
57   my $num_others = 
58     scalar_sql( $r, [qw( country state state county county taxname taxname )], 
59       "SELECT COUNT(*) FROM cust_main_county
60          WHERE country = ?
61          AND ( state = ? OR ( state IS NULL AND ? = '' ) )
62          AND ( county = ? OR ( county IS NULL AND ? = '' ) )
63          AND ( taxname = ? OR ( taxname IS NULL AND ? = '' ) ) "
64     );
65
66   die "didn't even find self?" unless $num_others;
67
68   if ( $num_others > 1 ) {
69     $fromwhere .= " AND ( taxclass = ?  ) ";
70     push @param, 'taxclass';
71   }
72
73   my $nottax = 'pkgnum != 0';
74
75   my $a = scalar_sql($r, \@param,
76     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere AND $nottax"
77   );
78   $total += $a;
79   $regions{$label}->{'total'} += $a;
80
81   foreach my $e ( grep { $r->get($_.'tax') =~ /^Y/i }
82                        qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
83     my $x = scalar_sql($r, \@param,
84       "SELECT SUM($e) $fromwhere AND $nottax"
85     );
86     $exempt += $x;
87     $regions{$label}->{'exempt'} += $x;
88   }
89
90   foreach my $e ( grep { $r->get($_.'tax') !~ /^Y/i }
91                        qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
92     my $t = scalar_sql($r, \@param, 
93       "SELECT SUM($e) $fromwhere AND $nottax AND ( tax != 'Y' OR tax IS NULL )"
94     );
95     $taxable += $t;
96     $regions{$label}->{'taxable'} += $t;
97
98     my $x = scalar_sql($r, \@param, 
99       "SELECT SUM($e) $fromwhere AND $nottax AND tax = 'Y'"
100     );
101     $exempt += $x;
102     $regions{$label}->{'exempt'} += $x;
103   }
104
105   if ( defined($regions{$label}->{'rate'})
106        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
107     $regions{$label}->{'rate'} = 'variable';
108   } else {
109     $regions{$label}->{'rate'} = $r->tax.'%';
110   }
111
112   #match itemdesc if necessary!
113   my $named_tax = $r->taxname ? 'AND itemdesc = '. dbh->quote($r->taxname) : '';
114   my $x = scalar_sql($r, \@param,
115     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere ".
116     "AND pkgnum = 0 $named_tax",
117   );
118   $tax += $x;
119   $regions{$label}->{'tax'} += $x;
120
121   $regions{$label}->{'label'} = $label;
122
123 }
124
125 #ordering
126 my @regions = map $regions{$_},
127               sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
128               keys %regions;
129
130 push @regions, {
131   'label'     => 'Total',
132   'total'     => $total,
133   'exempt'    => $exempt,
134   'taxable'   => $taxable,
135   'rate'      => '',
136   'tax'       => $tax,
137 };
138
139 #-- 
140
141 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
142 #to FS::Report or FS::Record or who the fuck knows where)
143 sub scalar_sql {
144   my( $r, $param, $sql ) = @_;
145   #warn "$sql\n";
146   my $sth = dbh->prepare($sql) or die dbh->errstr;
147   $sth->execute( map $r->$_(), @$param )
148     or die "Unexpected error executing statement $sql: ". $sth->errstr;
149   $sth->fetchrow_arrayref->[0] || 0;
150 }
151
152 %>
153
154 <%= header( "Sales Tax Report - $pbeginning through ".($pending||'now'),
155             menubar( 'Main Menu'=>$p, ) )               %>
156 <%= table() %>
157   <TR>
158     <TH ROWSPAN=2></TH>
159     <TH COLSPAN=3>Sales</TH>
160     <TH ROWSPAN=2>Rate</TH>
161     <TH ROWSPAN=2>Tax</TH>
162   </TR>
163   <TR>
164     <TH>Total</TH>
165     <TH>Non-taxable</TH>
166     <TH>Taxable</TH>
167   </TR>
168   <% foreach my $region ( @regions ) { %>
169     <TR>
170       <TD><%= $region->{'label'} %></TD>
171       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'total'} ) %></TD>
172       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'exempt'} ) %></TD>
173       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'taxable'} ) %></TD>
174       <TD ALIGN="right"><%= $region->{'rate'} %></TD>
175       <TD ALIGN="right">$<%= sprintf('%.2f', $region->{'tax'} ) %></TD>
176     </TR>
177   <% } %>
178
179 </TABLE>
180
181 </BODY>
182 </HTML>
183
184