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