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