improved taxproduct tax report RT#4783
[freeside.git] / httemplate / search / cust_bill_pkg.cgi
1 <% include( 'elements/search.html',
2                  'title'       => 'Line items',
3                  'name'        => 'line items',
4                  'query'       => $query,
5                  'count_query' => $count_query,
6                  'count_addl'  => [ $money_char. '%.2f total', ],
7                  'header'      => [
8                    '#',
9                    'Description',
10                    'Setup charge',
11                    'Recurring charge',
12                    'Invoice',
13                    'Date',
14                    FS::UI::Web::cust_header(),
15                  ],
16                  'fields'      => [
17                    'billpkgnum',
18                    sub { $_[0]->pkgnum > 0
19                            ? $_[0]->get('pkg')
20                            : $_[0]->get('itemdesc')
21                        },
22                    #strikethrough or "N/A ($amount)" or something these when
23                    # they're not applicable to pkg_tax search
24                    sub { sprintf($money_char.'%.2f', shift->setup ) },
25                    sub { sprintf($money_char.'%.2f', shift->recur ) },
26                    'invnum',
27                    sub { time2str('%b %d %Y', shift->_date ) },
28                    \&FS::UI::Web::cust_fields,
29                  ],
30                  'links'       => [
31                    '',
32                    '',
33                    '',
34                    '',
35                    $ilink,
36                    $ilink,
37                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
38                          FS::UI::Web::cust_header()
39                    ),
40                  ],
41                  'align' => 'rlrrrc'.FS::UI::Web::cust_aligns(),
42                  'color' => [ 
43                               '',
44                               '',
45                               '',
46                               '',
47                               '',
48                               '',
49                               FS::UI::Web::cust_colors(),
50                             ],
51                  'style' => [ 
52                               '',
53                               '',
54                               '',
55                               '',
56                               '',
57                               '',
58                               FS::UI::Web::cust_styles(),
59                             ],
60            )
61 %>
62 <%init>
63
64 die "access denied"
65   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
66
67 my $conf = new FS::Conf;
68
69 #here is the agent virtualization
70 my $agentnums_sql =
71   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
72
73 my @where = ( $agentnums_sql );
74
75 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
76 push @where, "_date >= $beginning",
77              "_date <= $ending";
78
79 push @where , " payby != 'COMP' "
80   unless $cgi->param('include_comp_cust');
81
82 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
83   push @where, "cust_main.agentnum = $1";
84 }
85
86 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
87   if ( $1 == 0 ) {
88     push @where, "classnum IS NULL";
89   } else {
90     push @where, "classnum = $1";
91   }
92 }
93
94 #sub _where {
95 # my $table = shift;
96 # my $prefix = @_ ? shift : '';
97 # "
98 #      (    cust_main_county.county  = $table.${prefix}.county
99 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county  =  '' )
100 #      OR ( cust_main_county.county  =  ''  AND $table.${prefix}.county IS NULL)
101 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county IS NULL)
102 #      )
103 #  AND (    cust_main_county.state   = $table.${prefix}.state
104 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state  =  ''  )
105 #      OR ( cust_main_county.state   =  ''  AND $table.${prefix}.state IS NULL )
106 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state IS NULL )
107 #      )
108 #  AND cust_main_county.country = $table.${prefix}.country
109 # ";
110 #
111 #}
112
113 if ( $cgi->param('out') ) {
114
115   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
116   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
117     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
118   }
119
120   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
121     if $cgi->param('istax');
122
123   push @where, "
124     0 = (
125           SELECT COUNT(*) FROM cust_main_county
126            WHERE cust_main_county.tax > 0
127              AND $loc_sql
128         )
129   ";
130
131   #not linked to by anything, but useful for debugging "out of taxable region"
132   if ( grep $cgi->param($_), qw( county state country ) ) {
133
134     my %ph = map { $_ => dbh->quote( $cgi->param($_) ) }
135                  qw( county state country );
136
137     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
138     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
139       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
140     }
141
142     push @where, $loc_sql;
143
144   }
145
146 } elsif ( $cgi->param('country' ) ) {
147
148   my %ph = map { $_ => dbh->quote( $cgi->param($_) ) }
149                qw( county state country );
150
151   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
152   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
153     $loc_sql =~ s/\?/$ph{shift(@param)}/e;
154   }
155
156   push @where, $loc_sql;
157    
158   if ( $cgi->param('istax') ) {
159     if ( $cgi->param('taxname') ) {
160       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
161     #} elsif ( $cgi->param('taxnameNULL') {
162     } else {
163       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
164     }
165   } elsif ( $cgi->param('nottax') ) {
166     #what can we usefully do with "taxname" ????  look up a class???
167   } else {
168     #warn "neither nottax nor istax parameters specified";
169   }
170
171   push @where, ' taxclass = '. dbh->quote( $cgi->param('taxclass') )
172     if $cgi->param('taxclass')
173     && ! $cgi->param('istax'); #no part_pkg.taxclass in this case
174                                #(should we save a taxclass or a link to taxnum
175                                # in cust_bill_pkg or something like
176                                # cust_bill_pkg_tax_location?)
177
178   if ( $cgi->param('taxclassNULL') ) {
179
180     my %hash = ( 'country' => scalar($cgi->param('country')) );
181     foreach (qw( state county )) {
182       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
183     }
184     my $cust_main_county = qsearchs('cust_main_county', \%hash);
185     die "unknown base region for empty taxclass" unless $cust_main_county;
186
187     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
188     push @where, $same_sql if $same_sql;
189
190   }
191
192  } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
193
194   # this should really be shoved out to FS::cust_pkg->location_sql or something
195   # along with the code in report_newtax.cgi
196
197   my %pn = (
198    'county'        => 'tax_rate_location.county',
199    'state'         => 'tax_rate_location.state',
200    'city'          => 'tax_rate_location.city',
201    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
202   );
203
204   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
205            qw( county state city locationtaxid );
206
207   push @where,
208     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
209                    keys %ph
210     );
211
212 }
213
214 if ($cgi->param('itemdesc')) {
215   if ($cgi->param('itemdesc') eq 'Tax') {
216     push @where, "(itemdesc='Tax' OR itemdesc is null)";
217   }else{
218     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
219   }
220 }
221 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
222 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
223
224 push @where, " tax = 'Y' " if $cgi->param('cust_tax');
225
226 my $count_query;
227 if ( $cgi->param('pkg_tax') ) {
228
229   $count_query =
230     "SELECT COUNT(*),
231             SUM(
232                  ( CASE WHEN part_pkg.setuptax = 'Y'
233                         THEN cust_bill_pkg.setup
234                         ELSE 0
235                    END
236                  )
237                  +
238                  ( CASE WHEN part_pkg.recurtax = 'Y'
239                         THEN cust_bill_pkg.recur
240                         ELSE 0
241                    END
242                  )
243                )
244     ";
245
246   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
247                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
248                "( tax != 'Y' OR tax IS NULL )";
249
250 } elsif ( $cgi->param('taxable') ) {
251
252   my $setup_taxable = "(
253     CASE WHEN part_pkg.setuptax = 'Y'
254          THEN 0
255          ELSE cust_bill_pkg.setup
256     END
257   )";
258
259   my $recur_taxable = "(
260     CASE WHEN part_pkg.recurtax = 'Y'
261          THEN 0
262          ELSE cust_bill_pkg.recur
263     END
264   )";
265
266   my $exempt = "(
267     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
268       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
269   )";
270
271   $count_query =
272     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
273
274   push @where,
275     #not tax-exempt package (setup or recur)
276     "(
277           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
278             AND cust_bill_pkg.setup > 0 )
279        OR
280           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
281             AND cust_bill_pkg.recur > 0 )
282     )",
283     #not a tax_exempt customer
284     "( tax != 'Y' OR tax IS NULL )";
285     #not covered in full by a monthly tax exemption (texas tax)
286     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
287
288 } else {
289
290   $count_query =
291     "SELECT COUNT(*), SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
292
293 }
294
295 my $where = ' WHERE '. join(' AND ', @where);
296
297 my $join_cust =  '      JOIN cust_bill USING ( invnum ) 
298                    LEFT JOIN cust_main USING ( custnum ) ';
299
300
301 my $join_pkg;
302 if ( $cgi->param('nottax') ) {
303
304   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
305                  LEFT JOIN part_pkg USING ( pkgpart ) ';
306   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
307     if $conf->exists('tax-pkg_address');
308
309 } elsif ( $cgi->param('istax') ) {
310
311   #false laziness w/report_tax.cgi $taxfromwhere
312   if ( $conf->exists('tax-pkg_address') ) {
313     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
314                    LEFT JOIN cust_location              USING ( locationnum ) ';
315
316     #quelle kludge, false laziness w/report_tax.cgi
317     $where =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g; 
318   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
319     $join_pkg .=
320       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
321       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
322   }
323
324 } else { 
325
326   #die?
327   warn "neiether nottax nor istax parameters specified";
328   #same as before?
329   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
330                  LEFT JOIN part_pkg USING ( pkgpart ) ';
331
332 }
333
334 $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
335
336 my @select = (
337                'cust_bill_pkg.*',
338                'cust_bill._date',
339              );
340 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
341 push @select, 'cust_main.custnum',
342               FS::UI::Web::cust_sql_fields();
343
344 my $query = {
345   'table'     => 'cust_bill_pkg',
346   'addl_from' => "$join_cust $join_pkg",
347   'hashref'   => {},
348   'select'    => join(', ', @select ),
349   'extra_sql' => $where,
350   'order_by'  => 'ORDER BY _date, billpkgnum',
351 };
352
353 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
354 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
355
356 my $conf = new FS::Conf;
357 my $money_char = $conf->config('money_char') || '$';
358
359 </%init>