+ $join_pkg .= " LEFT JOIN ($tax_sub) AS item_tax
+ ON (cust_bill_pkg.billpkgnum = item_tax.taxable_billpkgnum)"
+ }
+
+ # now do something with that
+ if ( $cgi->param('taxable') ) {
+ # taxable query: needs sale amount - exempt amount
+ my $taxable = 'cust_bill_pkg.setup + cust_bill_pkg.recur '.
+ '- COALESCE(item_exempt.exempt_amount, 0)';
+
+ push @where, "item_tax.taxable_billpkgnum 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('exempt_cust') or $cgi->param('exempt_pkg') ) {
+
+ 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 ( @tax_where ) {
+ # union of taxable + all exempt_ cases
+ push @where,
+ '(item_tax.taxable_billpkgnum IS NOT NULL OR item_exempt.billpkgnum IS NOT NULL)';
+
+ }
+
+ } # handle all joins to cust_main_county
+
+ # setup/recur/usage separation
+ my %charges = map { $_ => 1 } split('', $cgi->param('charges') || 'SRU');
+
+ if ( $charges{S} and $charges{R} and $charges{U} ) {
+ # in this case, show discounts
+
+ $join_pkg .= ' JOIN (
+ SELECT billpkgnum, COALESCE(SUM(amount), 0) AS discounted
+ FROM cust_bill_pkg_discount RIGHT JOIN cust_bill_pkg USING (billpkgnum)
+ GROUP BY billpkgnum
+ ) AS _discount ON (cust_bill_pkg.billpkgnum = _discount.billpkgnum)
+ ';
+ push @select, '_discount.discounted';
+
+ push @peritem, 'discounted';
+ push @peritem_desc, 'Discount';
+ push @total, 'SUM(cust_bill_pkg.setup + cust_bill_pkg.recur + discounted)',
+ 'SUM(discounted)',
+ 'SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)';
+ push @total_desc, "$money_char%.2f gross sales",
+ "− $money_char%.2f discounted",
+ "= $money_char%.2f invoiced";