finish basic implemention of tax exemption by tax name hack, RT#5127
[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 #classnum
87 # not specified: all classes
88 # 0: empty class
89 # N: classnum
90 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
91   if ( $1 == 0 ) {
92     push @where, "classnum IS NULL";
93   } else {
94     push @where, "classnum = $1";
95   }
96 }
97
98 push @where, ' ( '. join(' OR ',
99                       map ' taxclass = '.dbh->quote($_), $cgi->param('taxclass')
100                     ).
101              ' ) '
102   if $cgi->param('taxclass')
103   && ! $cgi->param('istax'); #no part_pkg.taxclass in this case
104                              #(should we save a taxclass or a link to taxnum
105                              # in cust_bill_pkg or something like
106                              # cust_bill_pkg_tax_location?)
107
108 #sub _where {
109 # my $table = shift;
110 # my $prefix = @_ ? shift : '';
111 # "
112 #      (    cust_main_county.county  = $table.${prefix}.county
113 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county  =  '' )
114 #      OR ( cust_main_county.county  =  ''  AND $table.${prefix}.county IS NULL)
115 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county IS NULL)
116 #      )
117 #  AND (    cust_main_county.state   = $table.${prefix}.state
118 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state  =  ''  )
119 #      OR ( cust_main_county.state   =  ''  AND $table.${prefix}.state IS NULL )
120 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state IS NULL )
121 #      )
122 #  AND cust_main_county.country = $table.${prefix}.country
123 # ";
124 #
125 #}
126
127 if ( $cgi->param('out') ) {
128
129   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
130   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
131     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
132   }
133
134   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
135     if $cgi->param('istax');
136
137   push @where, "
138     0 = (
139           SELECT COUNT(*) FROM cust_main_county
140            WHERE cust_main_county.tax > 0
141              AND $loc_sql
142         )
143   ";
144
145   #not linked to by anything, but useful for debugging "out of taxable region"
146   if ( grep $cgi->param($_), qw( county state 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   }
159
160 } elsif ( $cgi->param('country') ) {
161
162   my @counties = $cgi->param('county');
163    
164   if ( scalar(@counties) > 1 ) {
165
166     #hacky, could be more efficient.  care if it is ever used for more than the
167     # tax-report_groups filtering kludge
168
169     my $locs_sql =
170       ' ( '. join(' OR ', map {
171
172           my %ph = ( 'county' => dbh->quote($_),
173                      map { $_ => dbh->quote( $cgi->param($_) ) }
174                        qw( state country )
175                    );
176
177           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
178           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
179             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
180           }
181
182           $loc_sql;
183
184         } @counties
185
186       ). ' ) ';
187
188     push @where, $locs_sql;
189
190   } else {
191
192     my %ph = map { $_ => dbh->quote( $cgi->param($_) ) }
193                  qw( county state country );
194
195     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
196     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
197       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
198     }
199
200     push @where, $loc_sql;
201
202   }
203    
204   if ( $cgi->param('istax') ) {
205     if ( $cgi->param('taxname') ) {
206       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
207     #} elsif ( $cgi->param('taxnameNULL') {
208     } else {
209       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
210     }
211   } elsif ( $cgi->param('nottax') ) {
212     #what can we usefully do with "taxname" ????  look up a class???
213   } else {
214     #warn "neither nottax nor istax parameters specified";
215   }
216
217   if ( $cgi->param('taxclassNULL') ) {
218
219     my %hash = ( 'country' => scalar($cgi->param('country')) );
220     foreach (qw( state county )) {
221       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
222     }
223     my $cust_main_county = qsearchs('cust_main_county', \%hash);
224     die "unknown base region for empty taxclass" unless $cust_main_county;
225
226     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
227     push @where, $same_sql if $same_sql;
228
229   }
230
231 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
232
233   # this should really be shoved out to FS::cust_pkg->location_sql or something
234   # along with the code in report_newtax.cgi
235
236   my %pn = (
237    'county'        => 'tax_rate_location.county',
238    'state'         => 'tax_rate_location.state',
239    'city'          => 'tax_rate_location.city',
240    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
241   );
242
243   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
244            qw( county state city locationtaxid );
245
246   push @where,
247     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
248                    keys %ph
249     );
250
251 }
252
253 if ( $cgi->param('itemdesc') ) {
254   if ( $cgi->param('itemdesc') eq 'Tax' ) {
255     push @where, "(itemdesc='Tax' OR itemdesc is null)";
256   } else {
257     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
258   }
259 }
260
261 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
262   my ( $group_op, $group_value ) = ( $1, $2 );
263   if ( $group_op eq '=' ) {
264     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
265     push @where, 'itemdesc = '. dbh->quote($group_value);
266   } elsif ( $group_op eq '!=' ) {
267     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
268   } else {
269     die "guru meditation #00de: group_op $group_op\n";
270   }
271   
272 }
273
274 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
275 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
276
277 if ( $cgi->param('cust_tax') ) {
278   #false laziness -ish w/report_tax.cgi
279   my $cust_exempt;
280   if ( $cgi->param('taxname') ) {
281     my $q_taxname = dbh->quote($cgi->param('taxname'));
282     $cust_exempt =
283       "( tax = 'Y'
284          OR EXISTS ( SELECT 1 FROM cust_main_exemption
285                        WHERE cust_main_exemption.custnum = cust_main.custnum
286                          AND cust_main_exemption.taxname = $q_taxname )
287        )
288       ";
289   } else {
290     $cust_exempt = " tax = 'Y' ";
291   }
292
293   push @where, $cust_exempt;
294 }
295
296 my $count_query;
297 if ( $cgi->param('pkg_tax') ) {
298
299   $count_query =
300     "SELECT COUNT(*),
301             SUM(
302                  ( CASE WHEN part_pkg.setuptax = 'Y'
303                         THEN cust_bill_pkg.setup
304                         ELSE 0
305                    END
306                  )
307                  +
308                  ( CASE WHEN part_pkg.recurtax = 'Y'
309                         THEN cust_bill_pkg.recur
310                         ELSE 0
311                    END
312                  )
313                )
314     ";
315
316   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
317                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
318                "( tax != 'Y' OR tax IS NULL )";
319
320 } elsif ( $cgi->param('taxable') ) {
321
322   my $setup_taxable = "(
323     CASE WHEN part_pkg.setuptax = 'Y'
324          THEN 0
325          ELSE cust_bill_pkg.setup
326     END
327   )";
328
329   my $recur_taxable = "(
330     CASE WHEN part_pkg.recurtax = 'Y'
331          THEN 0
332          ELSE cust_bill_pkg.recur
333     END
334   )";
335
336   my $exempt = "(
337     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
338       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
339   )";
340
341   $count_query =
342     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
343
344   push @where,
345     #not tax-exempt package (setup or recur)
346     "(
347           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
348             AND cust_bill_pkg.setup > 0 )
349        OR
350           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
351             AND cust_bill_pkg.recur > 0 )
352     )",
353     #not a tax_exempt customer
354     "( tax != 'Y' OR tax IS NULL )";
355     #not covered in full by a monthly tax exemption (texas tax)
356     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
357
358 } else {
359
360   $count_query =
361     "SELECT COUNT(*), SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
362
363 }
364
365 my $where = ' WHERE '. join(' AND ', @where);
366
367 my $join_cust =  '      JOIN cust_bill USING ( invnum ) 
368                    LEFT JOIN cust_main USING ( custnum ) ';
369
370
371 my $join_pkg;
372 if ( $cgi->param('nottax') ) {
373
374   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
375                  LEFT JOIN part_pkg USING ( pkgpart ) ';
376   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
377     if $conf->exists('tax-pkg_address');
378
379 } elsif ( $cgi->param('istax') ) {
380
381   #false laziness w/report_tax.cgi $taxfromwhere
382   if ( $conf->exists('tax-pkg_address') ) {
383     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
384                    LEFT JOIN cust_location              USING ( locationnum ) ';
385
386     #quelle kludge, false laziness w/report_tax.cgi
387     $where =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g; 
388   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
389     $join_pkg .=
390       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
391       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
392   }
393
394 } else { 
395
396   #die?
397   warn "neiether nottax nor istax parameters specified";
398   #same as before?
399   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
400                  LEFT JOIN part_pkg USING ( pkgpart ) ';
401
402 }
403
404 $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
405
406 my @select = (
407                'cust_bill_pkg.*',
408                'cust_bill._date',
409              );
410 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
411 push @select, 'cust_main.custnum',
412               FS::UI::Web::cust_sql_fields();
413
414 my $query = {
415   'table'     => 'cust_bill_pkg',
416   'addl_from' => "$join_cust $join_pkg",
417   'hashref'   => {},
418   'select'    => join(', ', @select ),
419   'extra_sql' => $where,
420   'order_by'  => 'ORDER BY _date, billpkgnum',
421 };
422
423 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
424 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
425
426 my $conf = new FS::Conf;
427 my $money_char = $conf->config('money_char') || '$';
428
429 </%init>