48eb96c73099e07628298f7fa1c72ac9b246d531
[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                                     $unearned ? ( $money_char. '%.2f unearned revenue' ) : (),
8                                   ],
9                  'header'      => [
10                    @pkgnum_header,
11                    emt('Pkg Def'),
12                    emt('Description'),
13                    @post_desc_header,
14                    ( $unearned
15                      ? ( emt('Unearned'), 
16                          emt('Owed'), # useful in 'paid' mode?
17                          emt('Payment date') )
18                      : ( emt('Setup charge') )
19                    ),
20                    ( $use_usage eq 'usage'
21                      ? emt('Usage charge')
22                      : emt('Recurring charge')
23                    ),
24                    ( $unearned
25                      ? ( emt('Charge start'), emt('Charge end') )
26                      : ()
27                    ),
28                    emt('Invoice'),
29                    emt('Date'),
30                    emt('Paid'),
31                    emt('Credited'),
32                    FS::UI::Web::cust_header(),
33                  ],
34                  'fields'      => [
35                    @pkgnum,
36                    sub { $_[0]->pkgnum > 0
37                            # possibly use override.pkg but i think this correct
38                            ? $_[0]->get('pkgpart')
39                            : ''
40                        },
41                    sub { $_[0]->pkgnum > 0
42                            # possibly use override.pkg but i think this correct
43                            ? $_[0]->get('pkg')     
44                            : $_[0]->get('itemdesc')
45                        },
46                    @post_desc,
47                    #strikethrough or "N/A ($amount)" or something these when
48                    # they're not applicable to pkg_tax search
49                    sub { my $cust_bill_pkg = shift;
50                          if ( $unearned ) {
51
52                            sprintf($money_char.'%.2f', 
53                              $cust_bill_pkg->unearned_revenue)
54
55                          } else {
56                            sprintf($money_char.'%.2f', $cust_bill_pkg->setup );
57                          }
58                        },
59                    ( $unearned
60                      ? ( $owed_sub, $payment_date_sub, )
61                      : ()
62                    ),
63                    sub { my $row = shift;
64                          my $value = 0;
65                          if ( $use_usage eq 'recurring' or $unearned ) {
66                            $value = $row->recur - $row->usage;
67                          } elsif ( $use_usage eq 'usage' ) {
68                            $value = $row->usage;
69                          } else {
70                            $value = $row->recur;
71                          }
72                          sprintf($money_char.'%.2f', $value );
73                        },
74                    ( $unearned
75                      ? ( sub { time2str('%b %d %Y', shift->sdate ) },
76                        # shift edate back a day
77                        # 82799 = 3600*23 - 1
78                        # (to avoid skipping a day during DST)
79                          sub { time2str('%b %d %Y', shift->edate - 82799 ) },
80                        )
81                      : ()
82                    ),
83                    'invnum',
84                    sub { time2str('%b %d %Y', shift->_date ) },
85                    sub { sprintf($money_char.'%.2f', shift->get('pay_amount')) },
86                    sub { sprintf($money_char.'%.2f', shift->get('credit_amount')) },
87                    \&FS::UI::Web::cust_fields,
88                  ],
89                  'sort_fields' => [
90                    @pkgnum_null,
91                    '',
92                    '',
93                    @post_desc_null,
94                    'setup', #broken in $unearned case i guess
95                    ( $unearned ? ('', '') : () ),
96                    ( $use_usage eq 'recurring' or $unearned
97                         ? 'recur - usage' :
98                      $use_usage eq 'usage' 
99                         ? 'usage'
100                         : 'recur'
101                    ),
102                    ( $unearned ? ('sdate', 'edate') : () ),
103                    'invnum',
104                    '_date',
105                    #'pay_amount',
106                    #'credit_amount',
107                  ],
108                  'links'       => [
109                    @pkgnum_null,
110                    '',
111                    '',
112                    @post_desc_null,
113                    '',
114                    ( $unearned ? ( '', '' ) : () ),
115                    '',
116                    ( $unearned ? ( '', '' ) : () ),
117                    $ilink,
118                    $ilink,
119                    $pay_link,
120                    $credit_link,
121                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
122                          FS::UI::Web::cust_header()
123                    ),
124                  ],
125                  #'align' => 'rlrrrc'.FS::UI::Web::cust_aligns(),
126                  'align' => $pkgnum_align.
127                             'rl'.
128                             $post_desc_align.
129                             'r'.
130                             ( $unearned ? 'rc' : '' ).
131                             'r'.
132                             ( $unearned ? 'cc' : '' ).
133                             'rcrr'.
134                             FS::UI::Web::cust_aligns(),
135                  'color' => [ 
136                               @pkgnum_null,
137                               '',
138                               '',
139                               @post_desc_null,
140                               '',
141                               ( $unearned ? ( '', '' ) : () ),
142                               '',
143                               ( $unearned ? ( '', '' ) : () ),
144                               '',
145                               '',
146                               '',
147                               '',
148                               FS::UI::Web::cust_colors(),
149                             ],
150                  'style' => [ 
151                               @pkgnum_null,
152                               '',
153                               '',
154                               @post_desc_null,
155                               '',
156                               ( $unearned ? ( '', '' ) : () ),
157                               '',
158                               ( $unearned ? ( '', '' ) : () ),
159                               '',
160                               '',
161                               '',
162                               '',
163                               FS::UI::Web::cust_styles(),
164                             ],
165 &>
166 <%init>
167
168 #LOTS of false laziness below w/cust_credit_bill_pkg.cgi
169
170 my $curuser = $FS::CurrentUser::CurrentUser;
171
172 die "access denied" unless $curuser->access_right('Financial reports');
173
174 my $conf = new FS::Conf;
175
176 my $unearned = '';
177 my $unearned_mode = '';
178 my $unearned_base = '';
179 my $unearned_sql = '';
180
181 my @select = ( 'cust_bill_pkg.*', 'cust_bill._date' );
182
183 my @pkgnum_header = ();
184 my @pkgnum = ();
185 my @pkgnum_null;
186 my $pkgnum_align = '';
187 if ( $curuser->option('show_pkgnum') ) {
188   push @select, 'cust_bill_pkg.pkgnum';
189   push @pkgnum_header, 'Pkg Num';
190   push @pkgnum, sub { $_[0]->pkgnum > 0 ? $_[0]->pkgnum : '' };
191   push @pkgnum_null, '';
192   $pkgnum_align .= 'r';
193 }
194
195 my @post_desc_header = ();
196 my @post_desc = ();
197 my @post_desc_null = ();
198 my $post_desc_align = '';
199 if ( $conf->exists('enable_taxclasses') ) {
200   push @post_desc_header, 'Tax class';
201   push @post_desc, 'taxclass';
202   push @post_desc_null, '';
203   $post_desc_align .= 'l';
204   push @select, 'part_pkg.taxclass'; # or should this use override?
205 }
206
207 #here is the agent virtualization
208 my $agentnums_sql =
209   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
210
211 my @where = ( $agentnums_sql );
212
213 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
214
215 if ( $cgi->param('status') =~ /^([a-z]+)$/ ) {
216   push @where, FS::cust_main->cust_status_sql . " = '$1'";
217 }
218
219 if ( $cgi->param('distribute') == 1 ) {
220   push @where, "sdate <= $ending",
221                "edate >  $beginning",
222   ;
223 }
224 else {
225   push @where, "cust_bill._date >= $beginning",
226                "cust_bill._date <= $ending";
227 }
228
229 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
230   push @where, "cust_main.agentnum = $1";
231 }
232
233 if ( $cgi->param('refnum') =~ /^(\d+)$/ ) {
234   push @where, "cust_main.refnum = $1";
235 }
236
237 # cust_classnum
238 if ( $cgi->param('cust_classnum') ) {
239   my @classnums = grep /^\d+$/, $cgi->param('cust_classnum');
240   push @where, 'cust_main.classnum IN('.join(',',@classnums).')'
241     if @classnums;
242 }
243
244 # custnum
245 if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
246   push @where, "cust_main.custnum = $1";
247 }
248
249 #classnum
250 # not specified: all classes
251 # 0: empty class
252 # N: classnum
253 my $use_override = $cgi->param('use_override');
254 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
255   my $comparison = '';
256   if ( $1 == 0 ) {
257     $comparison = "IS NULL";
258   } else {
259     $comparison = "= $1";
260   }
261
262   if ( $use_override ) {
263     push @where, "(
264       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
265       override.classnum $comparison AND pkgpart_override IS NOT NULL
266     )";
267   } else {
268     push @where, "part_pkg.classnum $comparison";
269   }
270 }
271
272 if ( $cgi->param('taxclass')
273      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
274                                 #(should we save a taxclass or a link to taxnum
275                                 # in cust_bill_pkg or something like
276                                 # cust_bill_pkg_tax_location?)
277    )
278 {
279
280   #override taxclass when use_override is specified?  probably
281   #if ( $use_override ) {
282   #
283   #  push @where,
284   #    ' ( '. join(' OR ',
285   #                  map {
286   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
287   #                        '      AND pkgpart_override IS NULL '.
288   #                        '   OR '.
289   #                        '      override.taxclass = '. dbh->quote($_).
290   #                        '      AND pkgpart_override IS NOT NULL '.
291   #                        ' ) '
292   #                      }
293   #                      $cgi->param('taxclass')
294   #               ).
295   #    ' ) ';
296   #
297   #} else {
298
299     push @where, ' part_pkg.taxclass IN ( '.
300                    join(', ', map dbh->quote($_), $cgi->param('taxclass') ).
301                  ' ) ';
302
303   #}
304
305 }
306
307 my @loc_param = qw( district city county state country );
308
309 if ( $cgi->param('out') ) {
310
311   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
312   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
313     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
314   }
315
316   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
317     if $cgi->param('istax');
318
319   push @where, "
320     0 = (
321           SELECT COUNT(*) FROM cust_main_county
322            WHERE cust_main_county.tax > 0
323              AND $loc_sql
324         )
325   ";
326
327   #not linked to by anything, but useful for debugging "out of taxable region"
328   if ( grep $cgi->param($_), @loc_param ) {
329
330     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
331
332     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
333     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
334       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
335     }
336
337     push @where, $loc_sql;
338
339   }
340
341 } elsif ( $cgi->param('country') ) {
342
343   my @counties = $cgi->param('county');
344    
345   if ( scalar(@counties) > 1 ) {
346
347     #hacky, could be more efficient.  care if it is ever used for more than the
348     # tax-report_groups filtering kludge
349
350     my $locs_sql =
351       ' ( '. join(' OR ', map {
352
353           my %ph = ( 'county' => dbh->quote($_),
354                      map { $_ => dbh->quote( $cgi->param($_) ) }
355                        qw( district city state country )
356                    );
357
358           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
359           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
360             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
361           }
362
363           $loc_sql;
364
365         } @counties
366
367       ). ' ) ';
368
369     push @where, $locs_sql;
370
371   } else {
372
373     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
374
375     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
376     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
377       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
378     }
379
380     push @where, $loc_sql;
381
382   }
383    
384   if ( $cgi->param('istax') ) {
385     if ( $cgi->param('taxname') ) {
386       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
387     #} elsif ( $cgi->param('taxnameNULL') {
388     } else {
389       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
390     }
391   } elsif ( $cgi->param('nottax') ) {
392     #what can we usefully do with "taxname" ????  look up a class???
393   } else {
394     #warn "neither nottax nor istax parameters specified";
395   }
396
397   if ( $cgi->param('taxclassNULL')
398        && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
399                                   #(see comment above?)
400      )
401   {
402     my %hash = ( 'country' => scalar($cgi->param('country')) );
403     foreach (qw( state county )) {
404       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
405     }
406     my $cust_main_county = qsearchs('cust_main_county', \%hash);
407     die "unknown base region for empty taxclass" unless $cust_main_county;
408
409     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
410     $same_sql =~ s/taxclass/part_pkg.taxclass/g;
411     push @where, $same_sql if $same_sql;
412
413   }
414
415 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
416
417   push @where, FS::tax_rate_location->location_sql(
418                  map { $_ => (scalar($cgi->param($_)) || '') }
419                    qw( district city county state locationtaxid )
420                );
421
422 }
423
424 # unearned revenue mode
425 if ( $cgi->param('unearned_now') =~ /^(\d+)$/ ) {
426
427   $unearned = $1;
428   $unearned_mode = $cgi->param('mode');
429
430   push @where, "cust_bill_pkg.sdate < $unearned",
431                "cust_bill_pkg.edate > $unearned",
432                "cust_bill_pkg.recur != 0",
433                "part_pkg.freq != '0'";
434
435   if ( !$cgi->param('include_monthly') ) {
436     push @where,
437                "part_pkg.freq != '1'",
438                "part_pkg.freq NOT LIKE '%h'",
439                "part_pkg.freq NOT LIKE '%d'",
440                "part_pkg.freq NOT LIKE '%w'";
441   }
442
443   my $usage_sql = FS::cust_bill_pkg->usage_sql;
444   push @select, "($usage_sql) AS usage"; # we need this
445   my $paid_sql = 'GREATEST(' .
446     FS::cust_bill_pkg->paid_sql($unearned, '', setuprecur => 'recur') .
447     " - $usage_sql, 0)";
448
449   push @select, "$paid_sql AS paid_no_usage"; # need this either way
450
451   if ( $unearned_mode eq 'paid' ) {
452     # then use the amount paid, minus usage charges
453     $unearned_base = $paid_sql;
454   }
455   else {
456     # use the amount billed, minus usage charges and credits
457     $unearned_base = "GREATEST( cust_bill_pkg.recur - ".
458       FS::cust_bill_pkg->credited_sql($unearned, '', setuprecur => 'recur') .
459       " - $usage_sql, 0)";
460       # include only rows that have some non-usage, non-credited portion
461   }
462   # whatever we're using as the base, only show rows where it's positive
463   push @where, "$unearned_base > 0";
464
465   my $period = "CAST(cust_bill_pkg.edate - cust_bill_pkg.sdate AS REAL)";
466   my $elapsed = "GREATEST( $unearned - cust_bill_pkg.sdate, 0 )";
467   my $remaining = "(1 - $elapsed/$period)";
468
469   $unearned_sql = "CAST( $unearned_base * $remaining AS DECIMAL(10,2) )";
470   push @select, "$unearned_sql AS unearned_revenue";
471
472   # last payment/credit date
473   my %t = (pay => 'cust_bill_pay', credit => 'cust_credit_bill');
474   foreach my $x (qw(pay credit)) {
475     my $table = $t{$x};
476     my $link = $table.'_pkg';
477     my $pkey = dbdef->table($table)->primary_key;
478     my $last_date_sql = "SELECT MAX(_date) 
479     FROM $table JOIN $link USING ($pkey)
480     WHERE $link.billpkgnum = cust_bill_pkg.billpkgnum 
481     AND $table._date <= $unearned";
482     push @select, "($last_date_sql) AS last_$x";
483   }
484
485 }
486
487 if ( $cgi->param('itemdesc') ) {
488   if ( $cgi->param('itemdesc') eq 'Tax' ) {
489     push @where, "(itemdesc='Tax' OR itemdesc is null)";
490   } else {
491     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
492   }
493 }
494
495 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
496   my ( $group_op, $group_value ) = ( $1, $2 );
497   if ( $group_op eq '=' ) {
498     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
499     push @where, 'itemdesc = '. dbh->quote($group_value);
500   } elsif ( $group_op eq '!=' ) {
501     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
502   } else {
503     die "guru meditation #00de: group_op $group_op\n";
504   }
505   
506 }
507
508 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
509 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
510
511 if ( $cgi->param('cust_tax') ) {
512   #false laziness -ish w/report_tax.cgi
513   my $cust_exempt;
514   if ( $cgi->param('taxname') ) {
515     my $q_taxname = dbh->quote($cgi->param('taxname'));
516     $cust_exempt =
517       "( tax = 'Y'
518          OR EXISTS ( SELECT 1 FROM cust_main_exemption
519                        WHERE cust_main_exemption.custnum = cust_main.custnum
520                          AND cust_main_exemption.taxname = $q_taxname )
521        )
522       ";
523   } else {
524     $cust_exempt = " tax = 'Y' ";
525   }
526
527   push @where, $cust_exempt;
528 }
529
530 my $use_usage = $cgi->param('use_usage');
531
532 my $count_query;
533 if ( $cgi->param('pkg_tax') ) {
534
535   $count_query =
536     "SELECT COUNT(*),
537             SUM(
538                  ( CASE WHEN part_pkg.setuptax = 'Y'
539                         THEN cust_bill_pkg.setup
540                         ELSE 0
541                    END
542                  )
543                  +
544                  ( CASE WHEN part_pkg.recurtax = 'Y'
545                         THEN cust_bill_pkg.recur
546                         ELSE 0
547                    END
548                  )
549                )
550     ";
551
552   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
553                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
554                "( tax != 'Y' OR tax IS NULL )";
555
556 } elsif ( $cgi->param('taxable') ) {
557
558   my $setup_taxable = "(
559     CASE WHEN part_pkg.setuptax = 'Y'
560          THEN 0
561          ELSE cust_bill_pkg.setup
562     END
563   )";
564
565   my $recur_taxable = "(
566     CASE WHEN part_pkg.recurtax = 'Y'
567          THEN 0
568          ELSE cust_bill_pkg.recur
569     END
570   )";
571
572   my $exempt = "(
573     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
574       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
575   )";
576
577   $count_query =
578     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
579
580   push @where,
581     #not tax-exempt package (setup or recur)
582     "(
583           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
584             AND cust_bill_pkg.setup > 0 )
585        OR
586           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
587             AND cust_bill_pkg.recur > 0 )
588     )",
589     #not a tax_exempt customer
590     "( tax != 'Y' OR tax IS NULL )";
591     #not covered in full by a monthly tax exemption (texas tax)
592     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
593
594 } else {
595
596   if ( $use_usage ) {
597     $count_query = "SELECT COUNT(*), ";
598   } else {
599     $count_query = "SELECT COUNT(DISTINCT billpkgnum), ";
600   }
601
602   if ( $unearned ) {
603     $count_query .= "SUM( $unearned_base ), SUM( $unearned_sql )";
604   } elsif ( $use_usage eq 'recurring' ) {
605     $count_query .= "SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - usage)";
606   } elsif ( $use_usage eq 'usage' ) {
607     $count_query .= "SUM(usage)";
608   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
609     $count_query .= "SUM( COALESCE(cust_bill_pkg_tax_rate_location.amount, cust_bill_pkg.setup + cust_bill_pkg.recur))";
610   } elsif ( $cgi->param('iscredit') eq 'rate') {
611     $count_query .= "SUM( cust_credit_bill_pkg.amount )";
612   } else {
613     $count_query .= "SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
614   }
615
616 }
617
618 my $join_cust =  '        JOIN cust_bill USING ( invnum )
619                      LEFT JOIN cust_main USING ( custnum ) ';
620
621 # we want the package and its definition if available
622 my $join_pkg = 
623 ' LEFT JOIN cust_pkg      USING (pkgnum) 
624   LEFT JOIN part_pkg      USING (pkgpart)';
625
626 my $part_pkg = 'part_pkg';
627 if ( $cgi->param('use_override') ) { #"Separate sub-packages from parents"
628   # still need the real part_pkg for tax applicability, 
629   # so alias this one
630   $join_pkg .= " LEFT JOIN part_pkg AS override ON (
631   COALESCE(cust_bill_pkg.pkgpart_override, cust_pkg.pkgpart, 0) = override.pkgpart
632   )";
633   $part_pkg = 'override';
634 }
635
636 if ( $cgi->param('nottax') ) {
637
638   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
639     if $conf->exists('tax-pkg_address');
640
641 } elsif ( $cgi->param('istax') ) {
642
643   #false laziness w/report_tax.cgi $taxfromwhere
644   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
645             $cgi->param('iscredit') eq 'rate') {
646
647     $join_pkg .=
648       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
649       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
650
651   } elsif ( $conf->exists('tax-pkg_address') ) {
652
653     $join_pkg .= '
654       LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
655       LEFT JOIN cust_location ON cust_bill_pkg_tax_location.locationnum
656                                  = cust_location.locationnum
657     ';
658
659     #quelle kludge, somewhat false laziness w/report_tax.cgi
660     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
661   }
662
663   if ( $cgi->param('iscredit') ) {
664     $join_pkg .= ' JOIN cust_credit_bill_pkg USING ( billpkgnum';
665     if ( $cgi->param('iscredit') eq 'rate' ) {
666       $join_pkg .= ', billpkgtaxratelocationnum )';
667     } elsif ( $conf->exists('tax-pkg_address') ) {
668       $join_pkg .= ', billpkgtaxlocationnum )';
669       push @where, "billpkgtaxratelocationnum IS NULL";
670     } else {
671       $join_pkg .= ' )';
672       push @where, "billpkgtaxratelocationnum IS NULL";
673     }
674   }
675
676 } # nottax / istax
677
678
679 #total payments
680 my $pay_sub = "SELECT SUM(cust_bill_pay_pkg.amount)
681                  FROM cust_bill_pay_pkg
682                    WHERE cust_bill_pkg.billpkgnum = cust_bill_pay_pkg.billpkgnum
683               ";
684 push @select, "($pay_sub) AS pay_amount";
685
686 #total credits
687 my $credit_sub = "
688   SELECT SUM(cust_credit_bill_pkg.amount)
689     FROM cust_credit_bill_pkg
690       WHERE cust_bill_pkg.billpkgnum = cust_credit_bill_pkg.billpkgnum
691 ";
692 push @select, "($credit_sub) AS credit_amount";
693
694 my $where = ' WHERE '. join(' AND ', @where);
695
696 if ($use_usage) {
697   $count_query .=
698     " FROM (SELECT cust_bill_pkg.setup, cust_bill_pkg.recur, 
699              ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_bill_pkg_detail
700                WHERE cust_bill_pkg.billpkgnum = cust_bill_pkg_detail.billpkgnum
701              ) AS usage FROM cust_bill_pkg  $join_cust $join_pkg $where
702            ) AS countquery";
703 } else {
704   $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
705 }
706
707 push @select, 'part_pkg.pkgpart',
708               'part_pkg.pkg',
709               'part_pkg.freq';
710
711 push @select, 'cust_main.custnum',
712               FS::UI::Web::cust_sql_fields();
713
714 my $query = {
715   'table'     => 'cust_bill_pkg',
716   'addl_from' => "$join_cust $join_pkg",
717   'hashref'   => {},
718   'select'    => join(",\n", @select ),
719   'extra_sql' => $where,
720   'order_by'  => 'ORDER BY cust_bill._date, billpkgnum',
721 };
722
723 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
724 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
725 my $pay_link    = ''; #[, 'billpkgnum', ];
726 my $credit_link = [ "${p}search/cust_credit_bill_pkg.html?billpkgnum=", 'billpkgnum', ];
727
728 my $conf = new FS::Conf;
729 my $money_char = $conf->config('money_char') || '$';
730
731 my $owed_sub = sub {
732   $money_char . shift->get('owed') # owed_recur is not correct here
733 };
734 my $payment_date_sub = sub {
735   #my $cust_bill_pkg = shift;
736   my @cust_pay = sort { $a->_date <=> $b->_date }
737                       map $_->cust_bill_pay->cust_pay,
738                           shift->cust_bill_pay_pkg('recur') #recur :/
739     or return '';
740   time2str('%b %d %Y', $cust_pay[-1]->_date );
741 };
742
743 warn "\n\nQUERY:\n".Dumper($query)."\n\nCOUNT_QUERY:\n$count_query\n\n"
744   if $cgi->param('debug');
745
746 </%init>