add customer status column to customer & most other reports. also put the C in ACL...
[freeside.git] / httemplate / search / report_tax.cgi
1 <% include("/elements/header.html", "$agentname Sales 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             menubar( 'Main Menu'=>$p, )
12           )
13 %>
14
15 <% include('/elements/table-grid.html') %>
16
17   <TR>
18     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
19     <TH CLASS="grid" BGCOLOR="#cccccc" COLSPAN=9>Sales</TH>
20     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
21     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Rate</TH>
22     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
23     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Tax owed</TH>
24 % unless ( $cgi->param('show_taxclasses') ) { 
25
26       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Tax invoiced</TH>
27 % } 
28
29   </TR>
30   <TR>
31     <TH CLASS="grid" BGCOLOR="#cccccc">Total</TH>
32     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
33     <TH CLASS="grid" BGCOLOR="#cccccc">Non-taxable<BR><FONT SIZE=-1>(tax-exempt customer)</FONT></TH>
34     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
35     <TH CLASS="grid" BGCOLOR="#cccccc">Non-taxable<BR><FONT SIZE=-1>(tax-exempt package)</FONT></TH>
36     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
37     <TH CLASS="grid" BGCOLOR="#cccccc">Non-taxable<BR><FONT SIZE=-1>(monthly exemption)</FONT></TH>
38     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
39     <TH CLASS="grid" BGCOLOR="#cccccc">Taxable</TH>
40   </TR>
41 % my $bgcolor1 = '#eeeeee';
42 %   my $bgcolor2 = '#ffffff';
43 %   my $bgcolor;
44 %
45 % foreach my $region ( @regions ) {
46 %
47 %       if ( $bgcolor eq $bgcolor1 ) {
48 %         $bgcolor = $bgcolor2;
49 %       } else {
50 %         $bgcolor = $bgcolor1;
51 %       }
52 %
53 %       my $link = '';
54 %       if ( $region->{'label'} ne 'Total' ) {
55 %         if ( $region->{'label'} eq $out ) {
56 %           $link = ';out=1';
57 %         } else {
58 %           $link = ';'. $region->{'url_param'};
59 %         }
60 %       }
61 %
62 %
63 %
64 %
65 %  
66
67
68     <TR>
69       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} %></TD>
70       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
71         <A HREF="<% $baselink. $link %>;nottax=1"><% $money_char %><% sprintf('%.2f', $region->{'total'} ) %></A>
72       </TD>
73       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> - </B></FONT></TD>
74       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
75         <A HREF="<% $baselink. $link %>;nottax=1;cust_tax=Y"><% $money_char %><% sprintf('%.2f', $region->{'exempt_cust'} ) %></A>
76       </TD>
77       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> - </B></FONT></TD>
78       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
79         <A HREF="<% $baselink. $link %>;nottax=1;pkg_tax=Y"><% $money_char %><% sprintf('%.2f', $region->{'exempt_pkg'} ) %></A>
80       </TD>
81       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> - </B></FONT></TD>
82       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
83         <A HREF="<% $exemptlink. $link %>"><% $money_char %><% sprintf('%.2f', $region->{'exempt_monthly'} ) %></A>
84         </TD>
85       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><FONT SIZE="+1"><B> = </B></FONT></TD>
86       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
87         <% $money_char %><% sprintf('%.2f', $region->{'taxable'} ) %></A>
88       </TD>
89       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} eq 'Total' ? '' : '<FONT FACE="sans-serif" SIZE="+1"><B> X </B></FONT>' %></TD>
90       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right"><% $region->{'rate'} %></TD>
91       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} eq 'Total' ? '' : '<FONT FACE="sans-serif" SIZE="+1"><B> = </B></FONT>' %></TD>
92       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
93         <% $money_char %><% sprintf('%.2f', $region->{'owed'} ) %>
94       </TD>
95 % unless ( $cgi->param('show_taxclasses') ) { 
96
97         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
98           <A HREF="<% $baselink. $link %>;istax=1"><% $money_char %><% sprintf('%.2f', $region->{'tax'} ) %></A>
99         </TD>
100 % } 
101
102     </TR>
103 % } 
104
105
106 </TABLE>
107 % if ( $cgi->param('show_taxclasses') ) { 
108
109
110   <BR>
111   <% include('/elements/table-grid.html') %>
112   <TR>
113     <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
114     <TH CLASS="grid" BGCOLOR="#cccccc">Tax invoiced</TH>
115   </TR>
116 % #some false laziness w/above
117 %     $bgcolor1 = '#eeeeee';
118 %     $bgcolor2 = '#ffffff';
119 %     foreach my $region ( @base_regions ) {
120 %
121 %       if ( $bgcolor eq $bgcolor1 ) {
122 %         $bgcolor = $bgcolor2;
123 %       } else {
124 %         $bgcolor = $bgcolor1;
125 %       }
126 %
127 %       my $link = '';
128 %       #if ( $region->{'label'} ne 'Total' ) {
129 %         if ( $region->{'label'} eq $out ) {
130 %           $link = ';out=1';
131 %         } else {
132 %           $link = ';'. $region->{'url_param'};
133 %         }
134 %       #}
135 %  
136
137
138     <TR>
139       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $region->{'label'} %></TD>
140       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
141         <A HREF="<% $baselink. $link %>;istax=1"><% $money_char %><% sprintf('%.2f', $region->{'tax'} ) %></A>
142       </TD>
143     </TR>
144 % } 
145 %
146 %     if ( $bgcolor eq $bgcolor1 ) {
147 %       $bgcolor = $bgcolor2;
148 %     } else {
149 %       $bgcolor = $bgcolor1;
150 %     }
151 %  
152
153
154   <TR>
155    <TD CLASS="grid" BGCOLOR="<% $bgcolor %>">Total</TD>
156     <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ALIGN="right">
157       <A HREF="<% $baselink %>;istax=1"><% $money_char %><% sprintf('%.2f', $tax ) %></A>
158     </TD>
159   </TR>
160
161   </TABLE>
162 % } 
163
164
165 </BODY>
166 </HTML>
167 <%init>
168
169 die "access denied"
170   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
171
172 my $conf = new FS::Conf;
173 my $money_char = $conf->config('money_char') || '$';
174
175 my $user = getotaker;
176
177 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
178
179 my $join_cust = "
180     JOIN cust_bill USING ( invnum ) 
181     LEFT JOIN cust_main USING ( custnum )
182 ";
183 my $from_join_cust = "
184     FROM cust_bill_pkg
185     $join_cust
186 "; 
187 my $join_pkg = "
188     LEFT JOIN cust_pkg USING ( pkgnum )
189     LEFT JOIN part_pkg USING ( pkgpart )
190 ";
191
192 my $where = "WHERE _date >= $beginning AND _date <= $ending ";
193 my @base_param = qw( county county state state country );
194 if ( $conf->exists('tax-ship_address') ) {
195
196   $where .= "
197       AND (    (     ( ship_last IS NULL     OR  ship_last  = '' )
198                  AND ( county       = ? OR ? = '' )
199                  AND ( state        = ? OR ? = '' )
200                  AND   country      = ?
201                )
202             OR (       ship_last IS NOT NULL AND ship_last != ''
203                  AND ( ship_county  = ? OR ? = '' )
204                  AND ( ship_state   = ? OR ? = '' )
205                  AND   ship_country = ?
206                )
207           )
208   ";
209   #    AND payby != 'COMP'
210
211   push @base_param, @base_param;
212
213 } else {
214
215   $where .= "
216       AND ( county  = ? OR ? = '' )
217       AND ( state   = ? OR ? = '' )
218       AND   country = ?
219   ";
220   #    AND payby != 'COMP'
221
222 }
223
224 my $agentname = '';
225 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
226   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
227   die "agent not found" unless $agent;
228   $agentname = $agent->agent;
229   $where .= ' AND agentnum = '. $agent->agentnum;
230 }
231
232 my $gotcust = "
233   WHERE 0 < ( SELECT COUNT(*) FROM cust_main
234 ";
235 if ( $conf->exists('tax-ship_address') ) {
236
237   $gotcust .= "
238                 WHERE
239
240                 (    cust_main_county.country = cust_main.country
241                   OR cust_main_county.country = cust_main.ship_country
242                 )
243
244                 AND
245
246                 ( 
247
248                   (     ( ship_last IS NULL     OR  ship_last = '' )
249                     AND (    cust_main_county.country = cust_main.country )
250                     AND (    cust_main_county.state = cust_main.state
251                           OR cust_main_county.state = ''
252                           OR cust_main_county.state IS NULL )
253                     AND (    cust_main_county.county = cust_main.county
254                           OR cust_main_county.county = ''
255                           OR cust_main_county.county IS NULL )
256                   )
257   
258                   OR
259   
260                   (       ship_last IS NOT NULL AND ship_last != ''
261                     AND (    cust_main_county.country = cust_main.ship_country )
262                     AND (    cust_main_county.state = cust_main.ship_state
263                           OR cust_main_county.state = ''
264                           OR cust_main_county.state IS NULL )
265                     AND (    cust_main_county.county = cust_main.ship_county
266                           OR cust_main_county.county = ''
267                           OR cust_main_county.county IS NULL )
268                   )
269
270                 )
271
272                 LIMIT 1
273             )
274   ";
275
276 } else {
277
278   $gotcust .= "
279                 WHERE ( cust_main.county  = cust_main_county.county
280                         OR cust_main_county.county = ''
281                         OR cust_main_county.county IS NULL )
282                   AND ( cust_main.state   = cust_main_county.state
283                         OR cust_main_county.state = ''
284                         OR cust_main_county.state IS NULL )
285                   AND ( cust_main.country = cust_main_county.country )
286                 LIMIT 1
287             )
288   ";
289
290 }
291
292 my($total, $tot_taxable, $owed, $tax) = ( 0, 0, 0, 0, 0 );
293 my( $exempt_cust, $exempt_pkg, $exempt_monthly ) = ( 0, 0 );
294 my $out = 'Out of taxable region(s)';
295 my %regions = ();
296 foreach my $r (qsearch('cust_main_county', {}, '', $gotcust) ) {
297   #warn $r->county. ' '. $r->state. ' '. $r->country. "\n";
298
299   my $label = getlabel($r);
300   $regions{$label}->{'label'} = $label;
301   $regions{$label}->{'url_param'} = join(';', map "$_=".$r->$_(), qw( county state country ) );
302
303   my @param = @base_param;
304   my $mywhere = $where;
305
306   if ( $r->taxclass ) {
307     $mywhere .= " AND taxclass = ? ";
308     push @param, 'taxclass';
309     $regions{$label}->{'url_param'} .= ';taxclass='. $r->taxclass
310       if $cgi->param('show_taxclasses');
311   }
312
313   my $fromwhere = $from_join_cust. $join_pkg. $mywhere. " AND payby != 'COMP' ";
314
315 #  my $label = getlabel($r);
316 #  $regions{$label}->{'label'} = $label;
317
318   my $nottax = 'pkgnum != 0';
319
320   ## calculate total for this region
321
322   my $t = scalar_sql($r, \@param,
323     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere AND $nottax"
324   );
325   $total += $t;
326   $regions{$label}->{'total'} += $t;
327
328   ## calculate customer-exemption for this region
329
330 ##  my $taxable = $t;
331
332 #  my($taxable, $x_cust) = (0, 0);
333 #  foreach my $e ( grep { $r->get($_.'tax') !~ /^Y/i }
334 #                       qw( cust_bill_pkg.setup cust_bill_pkg.recur ) ) {
335 #    $taxable += scalar_sql($r, \@param, 
336 #      "SELECT SUM($e) $fromwhere AND $nottax AND ( tax != 'Y' OR tax IS NULL )"
337 #    );
338 #
339 #    $x_cust += scalar_sql($r, \@param, 
340 #      "SELECT SUM($e) $fromwhere AND $nottax AND tax = 'Y'"
341 #    );
342 #  }
343
344   my $x_cust = scalar_sql($r, \@param,
345     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur)
346      $fromwhere AND $nottax AND tax = 'Y' "
347   );
348
349   $exempt_cust += $x_cust;
350   $regions{$label}->{'exempt_cust'} += $x_cust;
351   
352   ## calculate package-exemption for this region
353
354   my $x_pkg = scalar_sql($r, \@param,
355     "SELECT SUM(
356                  ( CASE WHEN part_pkg.setuptax = 'Y'
357                         THEN cust_bill_pkg.setup
358                         ELSE 0
359                    END
360                  )
361                  +
362                  ( CASE WHEN part_pkg.recurtax = 'Y'
363                         THEN cust_bill_pkg.recur
364                         ELSE 0
365                    END
366                  )
367                )
368        $fromwhere
369        AND $nottax
370        AND (
371                 ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
372              OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 )
373            )
374        AND ( tax != 'Y' OR tax IS NULL )
375     "
376   );
377   $exempt_pkg += $x_pkg;
378   $regions{$label}->{'exempt_pkg'} += $x_pkg;
379
380   ## calculate monthly exemption (texas tax) for this region
381
382   # count up all the cust_tax_exempt_pkg records associated with
383   # the actual line items.
384
385   my $x_monthly = scalar_sql($r, \@param,
386     "SELECT SUM(amount)
387        FROM cust_tax_exempt_pkg
388        JOIN cust_bill_pkg USING ( billpkgnum )
389        $join_cust $join_pkg
390      $mywhere"
391   );
392 #  if ( $x_monthly ) {
393 #    #warn $r->taxnum(). ": $x_monthly\n";
394 #    $taxable -= $x_monthly;
395 #  }
396
397   $exempt_monthly += $x_monthly;
398   $regions{$label}->{'exempt_monthly'} += $x_monthly;
399
400   my $taxable = $t - $x_cust - $x_pkg - $x_monthly;
401
402   $tot_taxable += $taxable;
403   $regions{$label}->{'taxable'} += $taxable;
404
405   $owed += $taxable * ($r->tax/100);
406   $regions{$label}->{'owed'} += $taxable * ($r->tax/100);
407
408   if ( defined($regions{$label}->{'rate'})
409        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
410     $regions{$label}->{'rate'} = 'variable';
411   } else {
412     $regions{$label}->{'rate'} = $r->tax.'%';
413   }
414
415 }
416
417 my $taxwhere = "$from_join_cust $where AND payby != 'COMP' ";
418 my @taxparam = @base_param;
419 my %base_regions = ();
420 #foreach my $label ( keys %regions ) {
421 foreach my $r (
422   qsearch( 'cust_main_county',
423            {},
424            'DISTINCT ON (country, state, county, taxname) *',
425            $gotcust
426          )
427 ) {
428
429   #warn join('-', map { $r->$_() } qw( country state county taxname ) )."\n";
430
431   my $label = getlabel($r);
432
433   #my $fromwhere = $join_pkg. $where. " AND payby != 'COMP' ";
434   #my @param = @base_param; 
435
436   #match itemdesc if necessary!
437   my $named_tax =
438     $r->taxname
439       ? 'AND itemdesc = '. dbh->quote($r->taxname)
440       : "AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
441   my $x = scalar_sql($r, \@taxparam,
442     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $taxwhere ".
443     "AND pkgnum = 0 $named_tax",
444   );
445   $tax += $x;
446   $regions{$label}->{'tax'} += $x;
447
448   if ( $cgi->param('show_taxclasses') ) {
449     my $base_label = getlabel($r, 'no_taxclass'=>1 );
450     $base_regions{$base_label}->{'label'} = $base_label;
451     $base_regions{$base_label}->{'url_param'} =
452       join(';', map "$_=".$r->$_(), qw( county state country ) );
453     $base_regions{$base_label}->{'tax'} += $x;
454   }
455
456 }
457
458 #ordering
459 my @regions =
460   map $regions{$_},
461   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
462   keys %regions;
463
464 my @base_regions =
465   map $base_regions{$_},
466   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
467   keys %base_regions;
468
469 push @regions, {
470   'label'          => 'Total',
471   'url_param'      => '',
472   'total'          => $total,
473   'exempt_cust'    => $exempt_cust,
474   'exempt_pkg'     => $exempt_pkg,
475   'exempt_monthly' => $exempt_monthly,
476   'taxable'        => $tot_taxable,
477   'rate'           => '',
478   'owed'           => $owed,
479   'tax'            => $tax,
480 };
481
482 #-- 
483
484 sub getlabel {
485   my $r = shift;
486   my %opt = @_;
487
488   my $label;
489   if (
490     $r->tax == 0 
491     && ! scalar( qsearch('cust_main_county', { 'state'   => $r->state,
492                                                'county'  => $r->county,
493                                                'country' => $r->country,
494                                                'tax' => { op=>'>', value=>0 },
495                                              }
496                         )
497                )
498
499   ) {
500     #kludge to avoid "will not stay shared" warning
501     my $out = 'Out of taxable region(s)';
502     $label = $out;
503   } elsif ( $r->taxname ) {
504     $label = $r->taxname;
505 #    $regions{$label}->{'taxname'} = $label;
506 #    push @{$regions{$label}->{$_}}, $r->$_() foreach qw( county state country );
507   } else {
508     $label = $r->country;
509     $label = $r->state.", $label" if $r->state;
510     $label = $r->county." county, $label" if $r->county;
511     $label = "$label (". $r->taxclass. ")"
512       if $r->taxclass
513       && $cgi->param('show_taxclasses')
514       && ! $opt{'no_taxclass'};
515     #$label = $r->taxname. " ($label)" if $r->taxname;
516   }
517   return $label;
518 }
519
520 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
521 #to FS::Report or FS::Record or who the fuck knows where)
522 sub scalar_sql {
523   my( $r, $param, $sql ) = @_;
524   #warn "$sql\n";
525   my $sth = dbh->prepare($sql) or die dbh->errstr;
526   $sth->execute( map $r->$_(), @$param )
527     or die "Unexpected error executing statement $sql: ". $sth->errstr;
528   $sth->fetchrow_arrayref->[0] || 0;
529 }
530
531
532
533 my $dateagentlink = "begin=$beginning;end=$ending";
534 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
535   if length($agentname);
536 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
537 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
538
539 </%init>