improved taxproduct tax report RT#4783
[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 collected</TH>
20   </TR>
21 % my $bgcolor1 = '#eeeeee';
22 % my $bgcolor2 = '#ffffff';
23 % my $bgcolor;
24 %
25 % foreach my $tax ( @taxes ) {
26 %
27 %   if ( $bgcolor eq $bgcolor1 ) {
28 %     $bgcolor = $bgcolor2;
29 %   } else {
30 %     $bgcolor = $bgcolor1;
31 %   }
32 %
33 %   my $link = '';
34 %   if ( $tax->{'label'} ne 'Total' ) {
35 %     $link = ';'. $tax->{'url_param'};
36 %   }
37 %
38
39     <TR>
40       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $tax->{'label'} %></TD>
41       <% $tax->{base} ? qq!<TD CLASS="grid" BGCOLOR="$bgcolor"></TD>! : '' %>
42       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
43         <A HREF="<% $baselink. $link %>;istax=1"><% $money_char %><% sprintf('%.2f', $tax->{'tax'} ) %></A>
44       </TD>
45       <% !($tax->{base}) ? qq!<TD CLASS="grid" BGCOLOR="$bgcolor"></TD>! : '' %>
46     </TR>
47 % } 
48
49 </TABLE>
50
51 </BODY>
52 </HTML>
53 <%init>
54
55 die "access denied"
56   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
57
58 my $conf = new FS::Conf;
59 my $money_char = $conf->config('money_char') || '$';
60
61 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
62
63 my $join_cust = "
64     JOIN cust_bill USING ( invnum ) 
65     LEFT JOIN cust_main USING ( custnum )
66 ";
67
68 my $join_loc = "LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum )";
69 my $join_tax_loc = "LEFT JOIN tax_rate_location USING ( taxratelocationnum )";
70
71 my $addl_from = " $join_cust $join_loc $join_tax_loc "; 
72
73 my $where = "WHERE _date >= $beginning AND _date <= $ending ";
74
75 my $agentname = '';
76 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
77   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
78   die "agent not found" unless $agent;
79   $agentname = $agent->agent;
80   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
81 }
82
83 # my ( $location_sql, @location_param ) = FS::cust_pkg->location_sql;
84 # $where .= " AND $location_sql";
85 #my @taxparam = ( 'itemdesc', @location_param );
86 # now something along the lines of geocode matching ?
87 #$where .= FS::cust_pkg->_location_sql_where('cust_tax_location');;
88 my @taxparam = ( 'itemdesc', 'tax_rate_location.state', 'tax_rate_location.county', 'tax_rate_location.city', 'cust_bill_pkg_tax_rate_location.locationtaxid' );
89
90 my $select = 'DISTINCT itemdesc,locationtaxid,tax_rate_location.state,tax_rate_location.county,tax_rate_location.city';
91
92 my $tax = 0;
93 my %taxes = ();
94 my %basetaxes = ();
95 foreach my $t (qsearch({ table     => 'cust_bill_pkg',
96                          select    => $select,
97                          hashref   => { pkgpart => 0 },
98                          addl_from => $addl_from,
99                          extra_sql => $where,
100                       })
101               )
102 {
103   my @params = map { my $f = $_; $f =~ s/.*\.//; $f } @taxparam;
104   my $label = join('~', map { $t->$_ } @params);
105   $label = 'Tax'. $label if $label =~ /^~/;
106   unless ( exists( $taxes{$label} ) ) {
107     my ($baselabel, @trash) = split /~/, $label;
108
109     $taxes{$label}->{'label'} = join(', ', split(/~/, $label) );
110     $taxes{$label}->{'url_param'} =
111       join(';', map { "$_=". uri_escape($t->$_) } @params);
112
113     my $taxwhere = "FROM cust_bill_pkg $addl_from $where AND payby != 'COMP' ".
114       "AND ". join( ' AND ', map { "( $_ = ? OR ? = '' AND $_ IS NULL)" } @taxparam );
115
116     my $sql = "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) ".
117               " $taxwhere AND cust_bill_pkg.pkgnum = 0";
118
119     my $x = scalar_sql($t, [ map { $_, $_ } @params ], $sql );
120     $tax += $x;
121     $taxes{$label}->{'tax'} += $x;
122
123     unless ( exists( $taxes{$baselabel} ) ) {
124
125       $basetaxes{$baselabel}->{'label'} = $baselabel;
126       $basetaxes{$baselabel}->{'url_param'} = "itemdesc=$baselabel";
127       $basetaxes{$baselabel}->{'base'} = 1;
128
129     }
130
131     $basetaxes{$baselabel}->{'tax'} += $x;
132       
133   }
134
135   # calculate customer-exemption for this tax
136   # calculate package-exemption for this tax
137   # calculate monthly exemption (texas tax) for this tax
138   # count up all the cust_tax_exempt_pkg records associated with
139   # the actual line items.
140 }
141
142
143 #ordering
144 my @taxes = ();
145
146 foreach my $tax ( sort { $a cmp $b } keys %taxes ) {
147   my ($base, @trash) = split '~', $tax;
148   my $basetax = delete( $basetaxes{$base} );
149   if ($basetax) {
150     if ( $basetax->{tax} == $taxes{$tax}->{tax} ) {
151       $taxes{$tax}->{base} = 1;
152     } else {
153       push @taxes, $basetax;
154     }
155   }
156   push @taxes, $taxes{$tax};
157 }
158
159 push @taxes, {
160   'label'          => 'Total',
161   'url_param'      => '',
162   'tax'            => $tax,
163   'base'           => 1,
164 };
165
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   my $sth = dbh->prepare($sql) or die dbh->errstr;
173   $sth->execute( map $r->$_(), @$param )
174     or die "Unexpected error executing statement $sql: ". $sth->errstr;
175   $sth->fetchrow_arrayref->[0] || 0;
176 }
177
178 my $dateagentlink = "begin=$beginning;end=$ending";
179 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
180   if length($agentname);
181 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
182
183 </%init>