- USING (billpkgnum)";
- }
-
- # process tax restrictions
- unshift @tax_where,
- 'cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum',
- 'cust_main_county.tax > 0';
-
- my $tax_sub = "SELECT 1
- 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);
-
- # 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 @select, "($taxable) AS taxable_amount";
- push @where, "EXISTS($tax_sub)";
- push @peritem, 'taxable_amount';
- push @peritem_desc, 'Taxable';
- push @total, "SUM($taxable)";
- push @total_desc, "$money_char%.2f taxable";
+ ON (cust_bill_pkg.billpkgnum = item_exempt.billpkgnum)";
+
+ my $credit_sub = 'SELECT SUM(amount) AS credit_amount, billpkgnum
+ FROM cust_credit_bill_pkg GROUP BY billpkgnum';
+
+ $join_pkg .= " LEFT JOIN ($credit_sub) AS item_credit
+ ON (cust_bill_pkg.billpkgnum = item_credit.billpkgnum)";
+
+ if ( @tax_where or $cgi->param('taxable') ) {
+ # process tax restrictions
+ unshift @tax_where,
+ 'cust_main_county.tax > 0';
+
+ my $tax_sub = "SELECT taxable_billpkgnum AS billpkgnum
+ FROM cust_bill_pkg_tax_location
+ JOIN cust_main_county USING (taxnum)
+ WHERE ". join(' AND ', @tax_where).
+ " GROUP BY taxable_billpkgnum";
+
+ $join_pkg .= " LEFT JOIN ($tax_sub) AS item_tax
+ ON (cust_bill_pkg.billpkgnum = item_tax.billpkgnum)"
+ }