summaryrefslogtreecommitdiff
path: root/httemplate/search/cust_bill_pkg.cgi
blob: 7d9172acaae1494e5bdd467c5133700b0aba0a5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
<& elements/search.html,
                 'title'       => emt('Line items'),
                 'name'        => emt('line items'),
                 'query'       => $query,
                 'count_query' => $count_query,
                 'count_addl'  => \@total_desc,
                 'header'      => [
                   @pkgnum_header,
                   emt('Pkg Def'),
                   emt('Description'),
                   @post_desc_header,
                   @peritem_desc,
                   @currency_desc,
                   emt('Invoice'),
                   emt('Date'),
                   emt('Paid'),
                   emt('Credited'),
                   FS::UI::Web::cust_header(),
                 ],
                 'fields'      => [
                   @pkgnum,
                   sub { $_[0]->pkgnum > 0
                           # possibly use override.pkg but i think this correct
                           ? $_[0]->get('pkgpart')
                           : ''
                       },
                   sub { $_[0]->pkgnum > 0
                           # possibly use override.pkg but i think this correct
                           ? $_[0]->get('pkg')     
                           : $_[0]->get('itemdesc')
                       },
                   @post_desc,
                   #strikethrough or "N/A ($amount)" or something these when
                   # they're not applicable to pkg_tax search
                   @peritem_sub,
                   @currency_sub,
                   'invnum',
                   sub { time2str('%b %d %Y', shift->_date ) },
                   sub { sprintf($money_char.'%.2f', shift->get('pay_amount')) },
                   sub { sprintf($money_char.'%.2f', shift->get('credit_amount')) },
                   \&FS::UI::Web::cust_fields,
                 ],
                 'sort_fields' => [
                   @pkgnum_null,
                   '',
                   '',
                   @post_desc_null,
                   @peritem,
                   @currency,
                   'invnum',
                   '_date',
                   #'pay_amount',
                   #'credit_amount',
                 ],
                 'links'       => [
                   @pkgnum_null,
                   '',
                   '',
                   @post_desc_null,
                   @peritem_null,
                   @currency_null,
                   $ilink,
                   $ilink,
                   $pay_link,
                   $credit_link,
                   ( map { $_ ne 'Cust. Status' ? $clink : '' }
                         FS::UI::Web::cust_header()
                   ),
                 ],
                 #'align' => 'rlrrrc'.FS::UI::Web::cust_aligns(),
                 'align' => $pkgnum_align.
                            'rl'.
                            $post_desc_align.
                            $peritem_align.
                            $currency_align.
                            'rcrr'.
                            FS::UI::Web::cust_aligns(),
                 'color' => [ 
                              @pkgnum_null,
                              '',
                              '',
                              @post_desc_null,
                              @peritem_null,
                              @currency_null,
                              '',
                              '',
                              '',
                              '',
                              FS::UI::Web::cust_colors(),
                            ],
                 'style' => [ 
                              @pkgnum_null,
                              '',
                              '',
                              @post_desc_null,
                              @peritem_null,
                              @currency_null,
                              '',
                              '',
                              '',
                              '',
                              FS::UI::Web::cust_styles(),
                            ],
&>
<%doc>

Output control parameters:
- distribute: Boolean.  If true, recurring fees will be "prorated" for the 
  portion of the package date range (sdate-edate) that falls within the date
  range of the report.  Line items will be limited to those for which this 
  portion is > 0.  This disables filtering on invoice date.

- usage: Separate usage (cust_bill_pkg_detail records) from
  recurring charges.  If set to "usage", will show usage instead of 
  recurring charges.  If set to "recurring", will deduct usage and only
  show the flat rate charge.  If not passed, the "recurring charge" column
  will include usage charges also.

Filtering parameters:
- begin, end: Date range.  Applies to invoice date, not necessarily package
  date range.  But see "distribute".

- status: Customer status (active, suspended, etc.).  This will filter on 
  _current_ customer status, not status at the time the invoice was generated.

- agentnum: Filter on customer agent.

- refnum: Filter on customer reference source.

- cust_classnum: Filter on customer class.

- classnum: Filter on package class.

- use_override: Apply "classnum" and "taxclass" filtering based on the 
  override (bundle) pkgpart, rather than always using the true pkgpart.

- nottax: Limit to items that are not taxes (pkgnum > 0).

- istax: Limit to items that are taxes (pkgnum == 0).

- taxnum: Limit to items whose tax definition matches this taxnum.
  With "nottax" that means items that are subject to that tax;
  with "istax" it's the tax charges themselves.  Can be specified 
  more than once to include multiple taxes.

- country, state, county, city: Limit to items whose tax location 
  matches these fields.  If "nottax" it's the tax location of the package;
  if "istax" the location of the tax.

- taxname, taxnameNULL: With "nottax", limit to items whose tax location
  matches a tax with this name.  With "istax", limit to items that have
  this tax name.  taxnameNULL is equivalent to "taxname = '' OR taxname 
  = 'Tax'".

- out: With "nottax", limit to items that don't match any tax definition.
  With "istax", find tax items that are unlinked to their tax definitions.
  Current Freeside (> July 2012) always creates tax links, but unlinked
  items may result from an incomplete upgrade of legacy data.

- locationtaxid: With "nottax", limit to packages matching this 
  tax_rate_location ID; with "tax", limit to taxes generated from that 
  location.

- taxclass: Filter on package taxclass.

- taxclassNULL: With "nottax", limit to items that would be subject to the
  tax with taxclass = NULL.  This doesn't necessarily mean part_pkg.taxclass
  is NULL; it also includes taxclasses that don't have a tax in this region.

- itemdesc: Limit to line items with this description.  Note that non-tax
  packages usually have a description of NULL.  (Deprecated.)

- report_group: Can contain '=' or '!=' followed by a string to limit to 
  line items where itemdesc starts with, or doesn't start with, the string.

- cust_tax: Limit to customers who are tax-exempt.  If "taxname" is also
  specified, limit to customers who are also specifically exempt from that 
  tax.

- pkg_tax: Limit to packages that are tax-exempt, and only include the 
  exempt portion (setup, recurring, or both) when calculating totals.

- taxable: Limit to packages that are subject to tax, i.e. where a
  cust_bill_pkg_tax_location record exists.

- credit: Limit to line items that received a credit application.  The
  amount of the credit will also be shown.

</%doc>
<%init>

my $curuser = $FS::CurrentUser::CurrentUser;

die "access denied" unless $curuser->access_right('Financial reports');

my $conf = new FS::Conf;
my $money_char = $conf->config('money_char') || '$';

my @select = ( 'cust_bill_pkg.*', 'cust_bill._date' );
my @total = ( 'COUNT(*)', 'SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)');
my @total_desc = ( $money_char.'%.2f total' ); # sprintf strings

my @peritem = ( 'setup', 'recur' );
my @peritem_desc = ( 'Setup charge', 'Recurring charge' );

my @currency_desc = ();
my @currency_sub = ();
my @currency = ();
if ( $conf->config('currencies') ) {
  @currency_desc = ( 'Setup billed', 'Recurring billed' );
  @currency_sub = (
    map {
      my $what = $_;
      sub { my $currency = $_[0]->get($what.'_billed_currency') or return '';
            $currency. ' '. currency_symbol($currency, SYM_HTML).
              $_[0]->get($what.'_billed_amount');
          };
    } qw( setup recur )
  );
  @currency = ( 'setup_billed_amount', 'recur_billed_amount' ); #for sorting
}

my @pkgnum_header = ();
my @pkgnum = ();
my @pkgnum_null;
my $pkgnum_align = '';
if ( $curuser->option('show_pkgnum') ) {
  push @select, 'cust_bill_pkg.pkgnum';
  push @pkgnum_header, 'Pkg Num';
  push @pkgnum, sub { $_[0]->pkgnum > 0 ? $_[0]->pkgnum : '' };
  push @pkgnum_null, '';
  $pkgnum_align .= 'r';
}

my @post_desc_header = ();
my @post_desc = ();
my @post_desc_null = ();
my $post_desc_align = '';
if ( $conf->exists('enable_taxclasses') ) {
  push @post_desc_header, 'Tax class';
  push @post_desc, 'taxclass';
  push @post_desc_null, '';
  $post_desc_align .= 'l';
  push @select, 'part_pkg.taxclass'; # or should this use override?
}

# valid in both the tax and non-tax cases
my $join_cust = 
  " LEFT JOIN cust_bill ON (cust_bill_pkg.invnum = cust_bill.invnum)".
  # use cust_pkg.locationnum if it exists
  FS::UI::Web::join_cust_main('cust_bill', 'cust_pkg');

#agent virtualization
my $agentnums_sql =
  $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );

my @where = ( $agentnums_sql );

# date range
my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);

if ( $cgi->param('distribute') == 1 ) {
  push @where, "sdate <= $ending",
               "edate >  $beginning",
  ;
}
else {
  push @where, "cust_bill._date >= $beginning",
               "cust_bill._date <= $ending";
}

# status
if ( $cgi->param('status') =~ /^([a-z]+)$/ ) {
  push @where, FS::cust_main->cust_status_sql . " = '$1'";
}

# agentnum
if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
  push @where, "cust_main.agentnum = $1";
}

# refnum
if ( $cgi->param('refnum') =~ /^(\d+)$/ ) {
  push @where, "cust_main.refnum = $1";
}

# cust_classnum (false laziness w/ elements/cust_main_dayranges.html, elements/cust_pay_or_refund.html, prepaid_income.html, cust_bill_pay.html, cust_bill_pkg_referral.html, unearned_detail.html, cust_credit.html, cust_credit_refund.html, cust_main::Search::search_sql)
if ( grep { $_ eq 'cust_classnum' } $cgi->param ) {
  my @classnums = grep /^\d*$/, $cgi->param('cust_classnum');
  push @where, 'COALESCE( cust_main.classnum, 0) IN ( '.
                   join(',', map { $_ || '0' } @classnums ).
               ' )'
    if @classnums;
}


# custnum
if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
  push @where, "cust_main.custnum = $1";
}

# we want the package and its definition if available
my $join_pkg = 
' LEFT JOIN cust_pkg      USING (pkgnum) 
  LEFT JOIN part_pkg      USING (pkgpart)';

my $part_pkg = 'part_pkg';
if ( $cgi->param('use_override') ) { #"Separate sub-packages from parents"
  # still need the real part_pkg for tax applicability, 
  # so alias this one
  $join_pkg .= " LEFT JOIN part_pkg AS override ON (
  COALESCE(cust_bill_pkg.pkgpart_override, cust_pkg.pkgpart, 0) = override.pkgpart
  )";
  $part_pkg = 'override';
}
push @select, 'part_pkg.pkgpart', 'part_pkg.pkg'; # or should this use override?

# the non-tax case
if ( $cgi->param('nottax') ) {

  push @where, 'cust_bill_pkg.pkgnum > 0';

  my @tax_where; # will go into a subquery
  my @exempt_where; # will also go into a subquery

  # classnum (of override pkgpart if applicable)
  # not specified: all classes
  # 0: empty class
  # N: classnum
  if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
    push @where, "COALESCE($part_pkg.classnum, 0) = $1";
  }

  # taxclass
  if ( $cgi->param('taxclassNULL') ) {
    # a little different from 'taxclass' in that it applies to the
    # effective taxclass, not the real one
    push @tax_where, 'cust_main_county.taxclass IS NULL'
  } elsif ( $cgi->param('taxclass') ) {
    push @tax_where, "$part_pkg.taxclass IN (" .
                 join(', ', map {dbh->quote($_)} $cgi->param('taxclass') ).
                 ')';
  }

  if ( $cgi->param('exempt_cust') eq 'Y' ) {
    # tax-exempt customers
    push @exempt_where, "(exempt_cust = 'Y' OR exempt_cust_taxname = 'Y')";

  } elsif ( $cgi->param('exempt_pkg') eq 'Y' ) { # non-taxable package
    # non-taxable package charges
    push @exempt_where, "(exempt_setup = 'Y' OR exempt_recur = 'Y')";
  }
  # we don't handle exempt_monthly here
  
  if ( $cgi->param('taxname') ) { # specific taxname
      push @tax_where, 'cust_main_county.taxname = '.
                        dbh->quote($cgi->param('taxname'));
  } elsif ( $cgi->param('taxnameNULL') ) {
      push @tax_where, 'cust_main_county.taxname IS NULL OR '.
                       'cust_main_county.taxname = \'Tax\'';
  }

  # country:state:county:city:district (may be repeated)
  # You can also pass a big list of taxnums but that leads to huge URLs.
  # Note that this means "packages whose tax is in this region", not 
  # "packages in this region".  It's meant for links from the tax report.
  if ( $cgi->param('region') ) {
    my @orwhere;
    foreach ( $cgi->param('region') ) {
      my %loc;
      @loc{qw(country state county city district)} = 
        split(':', $cgi->param('region'));
      my $string = join(' AND ',
            map { 
              if ( $loc{$_} ) {
                "$_ = ".dbh->quote($loc{$_});
              } else {
                "$_ IS NULL";
              }
            } keys(%loc)
      );
      push @orwhere, "($string)";
    }
    push @tax_where, '(' . join(' OR ', @orwhere) . ')' if @orwhere;
  }

  # specific taxnums
  if ( $cgi->param('taxnum') ) {
    my $taxnum_in = join(',', 
      grep /^\d+$/, $cgi->param('taxnum')
    );
    push @tax_where, "cust_main_county.taxnum IN ($taxnum_in)"
      if $taxnum_in;
  }

  # If we're showing exempt items, we need to find those with 
  # cust_tax_exempt_pkg records matching the selected taxes.
  # If we're showing taxable items, we need to find those with 
  # cust_bill_pkg_tax_location records.  We also need to find the 
  # exemption records so that we can show the taxable amount.
  # If we're showing all items, we need the union of those.
  # If we're showing 'out' (items that aren't region/class taxable),
  # then we need the set of all items minus the union of those.

  my $exempt_sub;

  if ( @exempt_where or @tax_where 
    or $cgi->param('taxable') or $cgi->param('out') )
  {
    # process exemption restrictions, including @tax_where
    my $exempt_sub = 'SELECT SUM(amount) as exempt_amount, billpkgnum 
    FROM cust_tax_exempt_pkg JOIN cust_main_county USING (taxnum)';

    $exempt_sub .= ' WHERE '.join(' AND ', @tax_where, @exempt_where)
      if (@tax_where or @exempt_where);

    $exempt_sub .= ' GROUP BY billpkgnum';

    $join_pkg .= " LEFT JOIN ($exempt_sub) AS item_exempt
    USING (billpkgnum)";
  }
 
  if ( @tax_where or $cgi->param('taxable') or $cgi->param('out') ) { 
    # process tax restrictions
    unshift @tax_where,
      'cust_main_county.tax > 0';

    my $tax_sub = "SELECT invnum, cust_bill_pkg_tax_location.pkgnum
    FROM cust_bill_pkg_tax_location
    JOIN cust_bill_pkg AS tax_item USING (billpkgnum)
    JOIN cust_main_county USING (taxnum)
    WHERE ". join(' AND ', @tax_where).
    " GROUP BY invnum, cust_bill_pkg_tax_location.pkgnum";

    $join_pkg .= " LEFT JOIN ($tax_sub) AS item_tax
    ON (item_tax.invnum = cust_bill_pkg.invnum AND
        item_tax.pkgnum = cust_bill_pkg.pkgnum)";
  }

  # now do something with that
  if ( @exempt_where ) {

    push @where,    'item_exempt.billpkgnum IS NOT NULL';
    push @select,   'item_exempt.exempt_amount';
    push @peritem,  'exempt_amount';
    push @peritem_desc, 'Exempt';
    push @total,    'SUM(exempt_amount)';
    push @total_desc, "$money_char%.2f tax-exempt";

  } elsif ( $cgi->param('taxable') ) {

    my $taxable = 'cust_bill_pkg.setup + cust_bill_pkg.recur '.
                  '- COALESCE(item_exempt.exempt_amount, 0)';

    push @where,    'item_tax.invnum IS NOT NULL';
    push @select,   "($taxable) AS taxable_amount";
    push @peritem,  'taxable_amount';
    push @peritem_desc, 'Taxable';
    push @total,    "SUM($taxable)";
    push @total_desc, "$money_char%.2f taxable";

  } elsif ( $cgi->param('out') ) {
  
    push @where,    'item_tax.invnum IS NULL',
                    'item_exempt.billpkgnum IS NULL';

  } elsif ( @tax_where ) {

    # union of taxable + all exempt_ cases
    push @where,
      '(item_tax.invnum IS NOT NULL OR item_exempt.billpkgnum IS NOT NULL)';

  }

  # recur/usage separation
  if ( $cgi->param('usage') eq 'recurring' ) {

    my $recur_no_usage = FS::cust_bill_pkg->charged_sql('', '', no_usage => 1);
    push @select, "($recur_no_usage) AS recur_no_usage";
    $peritem[1] = 'recur_no_usage';
    $total[1] = "SUM(cust_bill_pkg.setup + $recur_no_usage)";
    $total_desc[0] .= ' (excluding usage)';

  } elsif ( $cgi->param('usage') eq 'usage' ) {

    my $usage = FS::cust_bill_pkg->usage_sql();
    push @select, "($usage) AS _usage";
    # there's already a method named 'usage'
    $peritem[1] = '_usage';
    $peritem_desc[1] = 'Usage charge';
    $total[1] = "SUM($usage)";
    $total_desc[0] .= ' usage charges';
  }

} elsif ( $cgi->param('istax') ) {

  @peritem = ( 'setup' ); # taxes only have setup
  @peritem_desc = ( 'Tax charge' );

  push @where, 'cust_bill_pkg.pkgnum = 0';

  # tax location when using tax_rate_location
  if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {

    $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
                 ' LEFT JOIN tax_rate_location USING ( taxratelocationnum )';
    push @where, FS::tax_rate_location->location_sql(
                   map { $_ => (scalar($cgi->param($_)) || '') }
                     qw( district city county state locationtaxid )
                 );

    $total[1] = 'SUM(
      COALESCE(cust_bill_pkg_tax_rate_location.amount, 
               cust_bill_pkg.setup + cust_bill_pkg.recur)
    )';

  } elsif ( $cgi->param('out') ) {

    $join_pkg .= '
      LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
    ';
    push @where, 'cust_bill_pkg_tax_location.billpkgnum IS NULL';

    # each billpkgnum should appear only once
    $total[0] = 'COUNT(*)';
    $total[1] = 'SUM(cust_bill_pkg.setup)';

  } else { # not locationtaxid or 'out'--the normal case

    $join_pkg .= '
      LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
      JOIN cust_main_county           USING (taxnum)
    ';

    # don't double-count the components of consolidated taxes
    $total[0] = 'COUNT(DISTINCT cust_bill_pkg.billpkgnum)';
    $total[1] = 'SUM(cust_bill_pkg_tax_location.amount)';
  }

  # taxclass
  if ( $cgi->param('taxclassNULL') ) {
    push @where, 'cust_main_county.taxclass IS NULL';
  }

  # taxname
  if ( $cgi->param('taxnameNULL') ) {
    push @where, 'cust_main_county.taxname IS NULL OR '.
                 'cust_main_county.taxname = \'Tax\'';
  } elsif ( $cgi->param('taxname') ) {
    push @where, 'cust_main_county.taxname = '.
                  dbh->quote($cgi->param('taxname'));
  }

  # specific taxnums
  if ( $cgi->param('taxnum') ) {
    my $taxnum_in = join(',', 
      grep /^\d+$/, $cgi->param('taxnum')
    );
    push @where, "cust_main_county.taxnum IN ($taxnum_in)"
      if $taxnum_in;
  }

  # report group (itemdesc)
  if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ ) {
    my ( $group_op, $group_value ) = ( $1, $2 );
    if ( $group_op eq '=' ) {
      #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
      push @where, 'itemdesc = '. dbh->quote($group_value);
    } elsif ( $group_op eq '!=' ) {
      push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
    } else {
      die "guru meditation #00de: group_op $group_op\n";
    }
  }

  # itemdesc, for some reason
  if ( $cgi->param('itemdesc') ) {
    if ( $cgi->param('itemdesc') eq 'Tax' ) {
      push @where, "(itemdesc='Tax' OR itemdesc is null)";
    } else {
      push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
    }
  }

} # nottax / istax


#total payments
my $pay_sub = "SELECT SUM(cust_bill_pay_pkg.amount)
                 FROM cust_bill_pay_pkg
                   WHERE cust_bill_pkg.billpkgnum = cust_bill_pay_pkg.billpkgnum
              ";
push @select, "($pay_sub) AS pay_amount";


# credit
if ( $cgi->param('credit') ) {

  my $credit_sub;

  if ( $cgi->param('istax') ) {
    # then we need to group/join by billpkgtaxlocationnum, to get only the 
    # relevant part of partial taxes
    my $credit_sub = "SELECT SUM(cust_credit_bill_pkg.amount) AS credit_amount,
      reason.reason as reason_text, access_user.username AS username_text,
      billpkgtaxlocationnum, billpkgnum
    FROM cust_credit_bill_pkg
      JOIN cust_credit_bill USING (creditbillnum)
      JOIN cust_credit USING (crednum)
      LEFT JOIN reason USING (reasonnum)
      LEFT JOIN access_user USING (usernum)
    GROUP BY billpkgnum, billpkgtaxlocationnum, reason.reason, 
      access_user.username";

    if ( $cgi->param('out') ) {

      # find credits that are applied to the line items, but not to 
      # a cust_bill_pkg_tax_location link
      $join_pkg .= " LEFT JOIN ($credit_sub) AS item_credit
        USING (billpkgnum)";
      push @where, 'item_credit.billpkgtaxlocationnum IS NULL';

    } else {

      # find credits that are applied to the CBPTL links that are 
      # considered "interesting" by the report criteria
      $join_pkg .= " LEFT JOIN ($credit_sub) AS item_credit
        USING (billpkgtaxlocationnum)";

    }

  } else {
    # then only group by billpkgnum
    my $credit_sub = "SELECT SUM(cust_credit_bill_pkg.amount) AS credit_amount,
      reason.reason as reason_text, access_user.username AS username_text,
      billpkgnum
    FROM cust_credit_bill_pkg
      JOIN cust_credit_bill USING (creditbillnum)
      JOIN cust_credit USING (crednum)
      LEFT JOIN reason USING (reasonnum)
      LEFT JOIN access_user USING (usernum)
    GROUP BY billpkgnum, reason.reason, access_user.username";
    $join_pkg .= " LEFT JOIN ($credit_sub) AS item_credit USING (billpkgnum)";
  }

  push @where,    'item_credit.billpkgnum IS NOT NULL';
  push @select,   'item_credit.credit_amount',
                  'item_credit.username_text',
                  'item_credit.reason_text';
  push @peritem,  'credit_amount', 'username_text', 'reason_text';
  push @peritem_desc, 'Credited', 'By', 'Reason';
  push @total,    'SUM(credit_amount)';
  push @total_desc, "$money_char%.2f credited";

} else {

  #still want a credit total column

  my $credit_sub = "
    SELECT SUM(cust_credit_bill_pkg.amount)
      FROM cust_credit_bill_pkg
        WHERE cust_bill_pkg.billpkgnum = cust_credit_bill_pkg.billpkgnum
  ";
  push @select, "($credit_sub) AS credit_amount";

}

push @select, 'cust_main.custnum', FS::UI::Web::cust_sql_fields();

my $where = join(' AND ', @where);
$where &&= "WHERE $where";

my $query = {
  'table'     => 'cust_bill_pkg',
  'addl_from' => "$join_pkg $join_cust",
  'hashref'   => {},
  'select'    => join(",\n", @select ),
  'extra_sql' => $where,
  'order_by'  => 'ORDER BY cust_bill._date, cust_bill_pkg.billpkgnum',
};

my $count_query =
  'SELECT ' . join(',', @total) .
  " FROM cust_bill_pkg $join_pkg $join_cust
  $where";

@peritem_desc = map {emt($_)} @peritem_desc;
my @peritem_sub = map {
  my $field = $_;
  if ($field =~ /_text$/) { # kludge for credit reason/username fields
    sub {$_[0]->get($field)};
  } else {
    sub { sprintf($money_char.'%.2f', $_[0]->get($field)) }
  }
} @peritem;
my @peritem_null = map { '' } @peritem; # placeholders
my $peritem_align = 'r' x scalar(@peritem);

@currency_desc = map {emt($_)} @currency_desc;
my @currency_null = map { '' } @currency; # placeholders
my $currency_align = 'r' x scalar(@currency);

my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];

my $pay_link    = ''; #[, 'billpkgnum', ];
my $credit_link = [ "${p}search/cust_credit_bill_pkg.html?billpkgnum=", 'billpkgnum', ];

warn "\n\nQUERY:\n".Dumper($query)."\n\nCOUNT_QUERY:\n$count_query\n\n"
  if $cgi->param('debug');

</%init>