link new tax report to cust_credit_bill_pkg for credits, RT#12332
[freeside.git] / httemplate / search / report_newtax.cgi
1 <% include("/elements/header.html", "$agentname Tax Report - ".
2               ( $beginning
3                   ? time2str('%h %o %Y ', $beginning )
4                   : ''
5               ).
6               'through '.
7               ( $ending == 4294967295
8                   ? 'now'
9                   : time2str('%h %o %Y', $ending )
10               )
11           )
12 %>
13
14 <% include('/elements/table-grid.html') %>
15
16   <TR>
17     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
18     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
19     <TH CLASS="grid" BGCOLOR="#cccccc">Tax invoiced</TH>
20     <TH CLASS="grid" BGCOLOR="#cccccc">&nbsp;&nbsp;&nbsp;&nbsp;</TH>
21     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
22     <TH CLASS="grid" BGCOLOR="#cccccc">Tax credited</TH>
23   </TR>
24 % my $bgcolor1 = '#eeeeee';
25 % my $bgcolor2 = '#ffffff';
26 % my $bgcolor;
27 %
28 % foreach my $tax ( @taxes ) {
29 %
30 %   if ( $bgcolor eq $bgcolor1 ) {
31 %     $bgcolor = $bgcolor2;
32 %   } else {
33 %     $bgcolor = $bgcolor1;
34 %   }
35 %
36 %   my $link = '';
37 %   if ( $tax->{'label'} ne 'Total' ) {
38 %     $link = ';'. $tax->{'url_param'};
39 %   }
40 %
41
42     <TR>
43       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $tax->{'label'} %></TD>
44       <% $tax->{base} ? qq!<TD CLASS="grid" BGCOLOR="$bgcolor"></TD>! : '' %>
45       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
46         <A HREF="<% $baselink. $link %>;istax=1"><% $money_char %><% sprintf('%.2f', $tax->{'tax'} ) %></A>
47       </TD>
48       <% !($tax->{base}) ? qq!<TD CLASS="grid" BGCOLOR="$bgcolor"></TD>! : '' %>
49       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"></TD>
50       <% $tax->{base} ? qq!<TD CLASS="grid" BGCOLOR="$bgcolor"></TD>! : '' %>
51       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
52         <A HREF="<% $creditlink. $link %>;istax=1;iscredit=rate"><% $money_char %><% sprintf('%.2f', $tax->{'credit'} ) %></A>
53       </TD>
54       <% !($tax->{base}) ? qq!<TD CLASS="grid" BGCOLOR="$bgcolor"></TD>! : '' %>
55     </TR>
56 % } 
57
58 </TABLE>
59
60 </BODY>
61 </HTML>
62 <%init>
63
64 die "access denied"
65   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
66
67 #shit, all sorts of false laxiness w/tax_rate::geneate_liability_report
68
69 my $conf = new FS::Conf;
70 my $money_char = $conf->config('money_char') || '$';
71
72 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
73
74 my $join_cust = "
75     JOIN cust_bill USING ( invnum ) 
76     LEFT JOIN cust_main USING ( custnum )
77 ";
78
79 my $join_loc = "LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum )";
80 my $join_tax_loc = "LEFT JOIN tax_rate_location USING ( taxratelocationnum )";
81
82 my $addl_from = " $join_cust $join_loc $join_tax_loc "; 
83
84 my $where = "WHERE _date >= $beginning AND _date <= $ending ";
85
86 my $agentname = '';
87 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
88   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
89   die "agent not found" unless $agent;
90   $agentname = $agent->agent;
91   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
92 }
93
94 #my @taxparam = ( 'itemdesc', 'tax_rate_location.state', 'tax_rate_location.county', 'tax_rate_location.city', 'cust_bill_pkg_tax_rate_location.locationtaxid' );
95 my @taxparams = qw( city county state locationtaxid );
96 my @params = ('itemdesc', @taxparams);
97
98 my $select = 'DISTINCT itemdesc,locationtaxid,tax_rate_location.state,tax_rate_location.county,tax_rate_location.city';
99
100 my $tax = 0;
101 my $credit = 0;
102 my %taxes = ();
103 my %basetaxes = ();
104 foreach my $t (qsearch({ table     => 'cust_bill_pkg',
105                          select    => $select,
106                          hashref   => { pkgpart => 0 },
107                          addl_from => $addl_from,
108                          extra_sql => $where,
109                       })
110               )
111 {
112   #my @params = map { my $f = $_; $f =~ s/.*\.//; $f } @taxparam;
113   my $label = join('~', map { $t->$_ } @params);
114   $label = 'Tax'. $label if $label =~ /^~/;
115   unless ( exists( $taxes{$label} ) ) {
116     my ($baselabel, @trash) = split /~/, $label;
117
118     $taxes{$label}->{'label'} = join(', ', split(/~/, $label) );
119     $taxes{$label}->{'url_param'} =
120       join(';', map { "$_=". uri_escape($t->$_) } @params);
121
122     my $taxwhere = "FROM cust_bill_pkg $addl_from $where AND payby != 'COMP' ".
123       "AND ". FS::tax_rate_location->location_sql( map { $_ => $t->$_ }
124                                                        @taxparams
125                                                  );
126
127     my $sql = "SELECT SUM(amount) $taxwhere AND cust_bill_pkg.pkgnum = 0";
128
129     my $x = scalar_sql($t, [], $sql );
130     $tax += $x;
131     $taxes{$label}->{'tax'} += $x;
132
133     my $creditfrom = " JOIN cust_credit_bill_pkg USING (billpkgnum,billpkgtaxratelocationnum) ";
134     my $creditwhere = "FROM cust_bill_pkg $addl_from $creditfrom $where ".
135       "AND payby != 'COMP' ".
136       "AND ". FS::tax_rate_location->location_sql( map { $_ => $t->$_ }
137                                                        @taxparams
138                                                  );
139
140     $sql = "SELECT SUM(cust_credit_bill_pkg.amount) ".
141            " $creditwhere AND cust_bill_pkg.pkgnum = 0";
142
143     my $y = scalar_sql($t, [], $sql );
144     $credit += $y;
145     $taxes{$label}->{'credit'} += $y;
146
147     unless ( exists( $taxes{$baselabel} ) ) {
148
149       $basetaxes{$baselabel}->{'label'} = $baselabel;
150       $basetaxes{$baselabel}->{'url_param'} = "itemdesc=$baselabel";
151       $basetaxes{$baselabel}->{'base'} = 1;
152
153     }
154
155     $basetaxes{$baselabel}->{'tax'} += $x;
156     $basetaxes{$baselabel}->{'credit'} += $y;
157       
158   }
159
160   # calculate customer-exemption for this tax
161   # calculate package-exemption for this tax
162   # calculate monthly exemption (texas tax) for this tax
163   # count up all the cust_tax_exempt_pkg records associated with
164   # the actual line items.
165 }
166
167
168 #ordering
169 my @taxes = ();
170
171 foreach my $tax ( sort { $a cmp $b } keys %taxes ) {
172   my ($base, @trash) = split '~', $tax;
173   my $basetax = delete( $basetaxes{$base} );
174   if ($basetax) {
175     if ( $basetax->{tax} == $taxes{$tax}->{tax} ) {
176       $taxes{$tax}->{base} = 1;
177     } else {
178       push @taxes, $basetax;
179     }
180   }
181   push @taxes, $taxes{$tax};
182 }
183
184 push @taxes, {
185   'label'          => 'Total',
186   'url_param'      => '',
187   'tax'            => $tax,
188   'credit'         => $credit,
189   'base'           => 1,
190 };
191
192 #-- 
193
194 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
195 #to FS::Report or FS::Record or who the fuck knows where)
196 sub scalar_sql {
197   my( $r, $param, $sql ) = @_;
198   my $sth = dbh->prepare($sql) or die dbh->errstr;
199   $sth->execute( map $r->$_(), @$param )
200     or die "Unexpected error executing statement $sql: ". $sth->errstr;
201   $sth->fetchrow_arrayref->[0] || 0;
202 }
203
204 my $dateagentlink = "begin=$beginning;end=$ending";
205 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
206   if length($agentname);
207 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
208 my $creditlink = $p. "search/cust_credit_bill_pkg.html?$dateagentlink";
209
210 </%init>