fix color/style after removal of billpkgnum display
[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                    ( $use_usage eq 'usage'
12                      ? 'Usage charge'
13                      : 'Recurring charge'
14                    ),
15                    'Invoice',
16                    'Date',
17                    FS::UI::Web::cust_header(),
18                  ],
19                  'fields'      => [
20                    #'billpkgnum',
21                    sub { $_[0]->pkgnum > 0
22                            ? $_[0]->get('pkg')      # possibly use override.pkg
23                            : $_[0]->get('itemdesc') # but i think this correct
24                        },
25                    #strikethrough or "N/A ($amount)" or something these when
26                    # they're not applicable to pkg_tax search
27                    sub { sprintf($money_char.'%.2f', shift->setup ) },
28                    sub { my $row = shift;
29                          my $value = 0;
30                          if ( $use_usage eq 'recurring' ) {
31                            $value = $row->recur - $row->usage;
32                          } elsif ( $use_usage eq 'usage' ) {
33                            $value = $row->usage;
34                          } else {
35                            $value = $row->recur;
36                          }
37                          sprintf($money_char.'%.2f', $value );
38                        },
39                    'invnum',
40                    sub { time2str('%b %d %Y', shift->_date ) },
41                    \&FS::UI::Web::cust_fields,
42                  ],
43                  'links'       => [
44                    #'',
45                    '',
46                    '',
47                    '',
48                    $ilink,
49                    $ilink,
50                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
51                          FS::UI::Web::cust_header()
52                    ),
53                  ],
54                  #'align' => 'rlrrrc'.FS::UI::Web::cust_aligns(),
55                  'align' => 'lrrrc'.FS::UI::Web::cust_aligns(),
56                  'color' => [ 
57                               #'',
58                               '',
59                               '',
60                               '',
61                               '',
62                               '',
63                               FS::UI::Web::cust_colors(),
64                             ],
65                  'style' => [ 
66                               #'',
67                               '',
68                               '',
69                               '',
70                               '',
71                               '',
72                               FS::UI::Web::cust_styles(),
73                             ],
74            )
75 %>
76 <%init>
77
78 #LOTS of false laziness below w/cust_credit_bill_pkg.cgi
79
80 die "access denied"
81   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
82
83 my $conf = new FS::Conf;
84
85 #here is the agent virtualization
86 my $agentnums_sql =
87   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
88
89 my @where = ( $agentnums_sql );
90
91 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
92 push @where, "_date >= $beginning",
93              "_date <= $ending";
94
95 push @where , " payby != 'COMP' "
96   unless $cgi->param('include_comp_cust');
97
98 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
99   push @where, "cust_main.agentnum = $1";
100 }
101
102 #classnum
103 # not specified: all classes
104 # 0: empty class
105 # N: classnum
106 my $use_override = $cgi->param('use_override');
107 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
108   my $comparison = '';
109   if ( $1 == 0 ) {
110     $comparison = "IS NULL";
111   } else {
112     $comparison = "= $1";
113   }
114
115   if ( $use_override ) {
116     push @where, "(
117       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
118       override.classnum $comparison AND pkgpart_override IS NOT NULL
119     )";
120   } else {
121     push @where, "part_pkg.classnum $comparison";
122   }
123 }
124
125 if ( $cgi->param('taxclass')
126      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
127                                 #(should we save a taxclass or a link to taxnum
128                                 # in cust_bill_pkg or something like
129                                 # cust_bill_pkg_tax_location?)
130    )
131 {
132
133   #override taxclass when use_override is specified?  probably
134   #if ( $use_override ) {
135   #
136   #  push @where,
137   #    ' ( '. join(' OR ',
138   #                  map {
139   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
140   #                        '      AND pkgpart_override IS NULL '.
141   #                        '   OR '.
142   #                        '      override.taxclass = '. dbh->quote($_).
143   #                        '      AND pkgpart_override IS NOT NULL '.
144   #                        ' ) '
145   #                      }
146   #                      $cgi->param('taxclass')
147   #               ).
148   #    ' ) ';
149   #
150   #} else {
151
152     push @where,
153       ' ( '. join(' OR ',
154                     map ' part_pkg.taxclass = '.dbh->quote($_),
155                         $cgi->param('taxclass')
156                  ).
157       ' ) ';
158
159   #}
160
161 }
162
163 my @loc_param = qw( city county state country );
164
165 if ( $cgi->param('out') ) {
166
167   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
168   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
169     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
170   }
171
172   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
173     if $cgi->param('istax');
174
175   push @where, "
176     0 = (
177           SELECT COUNT(*) FROM cust_main_county
178            WHERE cust_main_county.tax > 0
179              AND $loc_sql
180         )
181   ";
182
183   #not linked to by anything, but useful for debugging "out of taxable region"
184   if ( grep $cgi->param($_), @loc_param ) {
185
186     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
187
188     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
189     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
190       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
191     }
192
193     push @where, $loc_sql;
194
195   }
196
197 } elsif ( $cgi->param('country') ) {
198
199   my @counties = $cgi->param('county');
200    
201   if ( scalar(@counties) > 1 ) {
202
203     #hacky, could be more efficient.  care if it is ever used for more than the
204     # tax-report_groups filtering kludge
205
206     my $locs_sql =
207       ' ( '. join(' OR ', map {
208
209           my %ph = ( 'county' => dbh->quote($_),
210                      map { $_ => dbh->quote( $cgi->param($_) ) }
211                        qw( city state country )
212                    );
213
214           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
215           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
216             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
217           }
218
219           $loc_sql;
220
221         } @counties
222
223       ). ' ) ';
224
225     push @where, $locs_sql;
226
227   } else {
228
229     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
230
231     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
232     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
233       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
234     }
235
236     push @where, $loc_sql;
237
238   }
239    
240   if ( $cgi->param('istax') ) {
241     if ( $cgi->param('taxname') ) {
242       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
243     #} elsif ( $cgi->param('taxnameNULL') {
244     } else {
245       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
246     }
247   } elsif ( $cgi->param('nottax') ) {
248     #what can we usefully do with "taxname" ????  look up a class???
249   } else {
250     #warn "neither nottax nor istax parameters specified";
251   }
252
253   if ( $cgi->param('taxclassNULL') ) {
254
255     my %hash = ( 'country' => scalar($cgi->param('country')) );
256     foreach (qw( state county )) {
257       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
258     }
259     my $cust_main_county = qsearchs('cust_main_county', \%hash);
260     die "unknown base region for empty taxclass" unless $cust_main_county;
261
262     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
263     push @where, $same_sql if $same_sql;
264
265   }
266
267 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
268
269   # this should really be shoved out to FS::cust_pkg->location_sql or something
270   # along with the code in report_newtax.cgi
271
272   my %pn = (
273    'county'        => 'tax_rate_location.county',
274    'state'         => 'tax_rate_location.state',
275    'city'          => 'tax_rate_location.city',
276    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
277   );
278
279   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
280            qw( city county state locationtaxid );
281
282   push @where,
283     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
284                    keys %ph
285     );
286
287 }
288
289 if ( $cgi->param('itemdesc') ) {
290   if ( $cgi->param('itemdesc') eq 'Tax' ) {
291     push @where, "(itemdesc='Tax' OR itemdesc is null)";
292   } else {
293     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
294   }
295 }
296
297 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
298   my ( $group_op, $group_value ) = ( $1, $2 );
299   if ( $group_op eq '=' ) {
300     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
301     push @where, 'itemdesc = '. dbh->quote($group_value);
302   } elsif ( $group_op eq '!=' ) {
303     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
304   } else {
305     die "guru meditation #00de: group_op $group_op\n";
306   }
307   
308 }
309
310 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
311 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
312
313 if ( $cgi->param('cust_tax') ) {
314   #false laziness -ish w/report_tax.cgi
315   my $cust_exempt;
316   if ( $cgi->param('taxname') ) {
317     my $q_taxname = dbh->quote($cgi->param('taxname'));
318     $cust_exempt =
319       "( tax = 'Y'
320          OR EXISTS ( SELECT 1 FROM cust_main_exemption
321                        WHERE cust_main_exemption.custnum = cust_main.custnum
322                          AND cust_main_exemption.taxname = $q_taxname )
323        )
324       ";
325   } else {
326     $cust_exempt = " tax = 'Y' ";
327   }
328
329   push @where, $cust_exempt;
330 }
331
332 my $use_usage = $cgi->param('use_usage');
333
334 my $count_query;
335 if ( $cgi->param('pkg_tax') ) {
336
337   $count_query =
338     "SELECT COUNT(*),
339             SUM(
340                  ( CASE WHEN part_pkg.setuptax = 'Y'
341                         THEN cust_bill_pkg.setup
342                         ELSE 0
343                    END
344                  )
345                  +
346                  ( CASE WHEN part_pkg.recurtax = 'Y'
347                         THEN cust_bill_pkg.recur
348                         ELSE 0
349                    END
350                  )
351                )
352     ";
353
354   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
355                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
356                "( tax != 'Y' OR tax IS NULL )";
357
358 } elsif ( $cgi->param('taxable') ) {
359
360   my $setup_taxable = "(
361     CASE WHEN part_pkg.setuptax = 'Y'
362          THEN 0
363          ELSE cust_bill_pkg.setup
364     END
365   )";
366
367   my $recur_taxable = "(
368     CASE WHEN part_pkg.recurtax = 'Y'
369          THEN 0
370          ELSE cust_bill_pkg.recur
371     END
372   )";
373
374   my $exempt = "(
375     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
376       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
377   )";
378
379   $count_query =
380     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
381
382   push @where,
383     #not tax-exempt package (setup or recur)
384     "(
385           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
386             AND cust_bill_pkg.setup > 0 )
387        OR
388           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
389             AND cust_bill_pkg.recur > 0 )
390     )",
391     #not a tax_exempt customer
392     "( tax != 'Y' OR tax IS NULL )";
393     #not covered in full by a monthly tax exemption (texas tax)
394     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
395
396 } else {
397
398   $count_query = "SELECT COUNT(*), ";
399
400   if ( $use_usage eq 'recurring' ) {
401     $count_query .= "SUM(setup + recur - usage)";
402   } elsif ( $use_usage eq 'usage' ) {
403     $count_query .= "SUM(usage)";
404   } else {
405     $count_query .= "SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
406   }
407
408 }
409
410 my $join_cust =  '      JOIN cust_bill USING ( invnum ) 
411                    LEFT JOIN cust_main USING ( custnum ) ';
412
413
414 my $join_pkg;
415 if ( $cgi->param('nottax') ) {
416
417   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
418                  LEFT JOIN part_pkg USING ( pkgpart )
419                  LEFT JOIN part_pkg AS override
420                    ON pkgpart_override = override.pkgpart ';
421   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
422     if $conf->exists('tax-pkg_address');
423
424 } elsif ( $cgi->param('istax') ) {
425
426   #false laziness w/report_tax.cgi $taxfromwhere
427   if ( $conf->exists('tax-pkg_address') ) {
428     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
429                    LEFT JOIN cust_location              USING ( locationnum ) ';
430
431     #quelle kludge, somewhat false laziness w/report_tax.cgi
432     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
433   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
434             $cgi->param('iscredit') eq 'rate') {
435     $join_pkg .=
436       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
437       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
438   }
439
440   if ( $cgi->param('iscredit') ) {
441     $join_pkg .= ' JOIN cust_credit_bill_pkg USING ( billpkgnum';
442     if ( $conf->exists('tax-pkg_address') ) {
443       $join_pkg .= ', billpkgtaxlocationnum )';
444       push @where, "billpkgtaxratelocationnum IS NULL";
445     } elsif ( $cgi->param('iscredit') eq 'rate' ) {
446       $join_pkg .= ', billpkgtaxratelocationnum )';
447     } else {
448       $join_pkg .= ' )';
449       push @where, "billpkgtaxratelocationnum IS NULL";
450     }
451   }
452
453 } else { 
454
455   #die?
456   warn "neiether nottax nor istax parameters specified";
457   #same as before?
458   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
459                  LEFT JOIN part_pkg USING ( pkgpart ) ';
460
461 }
462
463 my $where = ' WHERE '. join(' AND ', @where);
464
465 if ($use_usage) {
466   $count_query .=
467     " FROM (SELECT cust_bill_pkg.setup, cust_bill_pkg.recur, 
468              ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_bill_pkg_detail
469                WHERE cust_bill_pkg.billpkgnum = cust_bill_pkg_detail.billpkgnum
470              ) AS usage FROM cust_bill_pkg  $join_cust $join_pkg $where
471            ) AS countquery";
472 } else {
473   $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
474 }
475
476 my @select = (
477                'cust_bill_pkg.*',
478                'cust_bill._date',
479              );
480 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
481 push @select, 'cust_main.custnum',
482               FS::UI::Web::cust_sql_fields();
483
484 my $query = {
485   'table'     => 'cust_bill_pkg',
486   'addl_from' => "$join_cust $join_pkg",
487   'hashref'   => {},
488   'select'    => join(', ', @select ),
489   'extra_sql' => $where,
490   'order_by'  => 'ORDER BY _date, billpkgnum',
491 };
492
493 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
494 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
495
496 my $conf = new FS::Conf;
497 my $money_char = $conf->config('money_char') || '$';
498
499 </%init>