Option to ignore old CDRs, RT#81480
[freeside.git] / httemplate / search / cust_bill_pkg.cgi
index 7d9172a..ab5aad7 100644 (file)
                  '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')
-                       },
+                   'itemdesc', # is part_pkg.pkg if applicable
                    @post_desc,
                    #strikethrough or "N/A ($amount)" or something these when
                    # they're not applicable to pkg_tax search
@@ -49,8 +44,9 @@
                    @currency,
                    'invnum',
                    '_date',
-                   #'pay_amount',
-                   #'credit_amount',
+                   'pay_amount',
+                   'credit_amount',
+                   FS::UI::Web::cust_sort_fields(),
                  ],
                  'links'       => [
                    @pkgnum_null,
@@ -110,11 +106,7 @@ Output control parameters:
   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.
+- charges: 'S'etup, 'R'ecur, 'U'sage, or any string combination of those.
 
 Filtering parameters:
 - begin, end: Date range.  Applies to invoice date, not necessarily package
@@ -131,17 +123,21 @@ Filtering parameters:
 
 - classnum: Filter on package class.
 
+- report_optionnum: Filter on package report class.  Can be a single report
+  class number or a comma-separated list (where 0 is "no report class"), or the
+  word "multiple".
+
 - 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).
+- nottax: Limit to items that are not taxes (pkgnum > 0 or feepart > 0).
 
-- istax: Limit to items that are taxes (pkgnum == 0).
+- istax: Limit to items that are taxes (pkgnum == 0 and feepart = null).
 
 - 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.
+  with "istax" it's the tax charges themselves.  Can be a comma-separated
+  list 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;
@@ -197,11 +193,11 @@ 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 @total = ( 'COUNT(*)' );
+my @total_desc = ();
 
 my @peritem = ( 'setup', 'recur' );
-my @peritem_desc = ( 'Setup charge', 'Recurring charge' );
+my @peritem_desc = ( 'Setup charges', 'Recurring charges' );
 
 my @currency_desc = ();
 my @currency_sub = ();
@@ -241,9 +237,11 @@ if ( $conf->exists('enable_taxclasses') ) {
   push @post_desc, 'taxclass';
   push @post_desc_null, '';
   $post_desc_align .= 'l';
-  push @select, 'part_pkg.taxclass'; # or should this use override?
 }
 
+# used in several places
+my $itemdesc = 'COALESCE(cust_bill_pkg.itemdesc, part_fee.itemdesc, part_pkg.pkg, cust_bill_pkg.itemdesc)';
+
 # valid in both the tax and non-tax cases
 my $join_cust = 
   " LEFT JOIN cust_bill ON (cust_bill_pkg.invnum = cust_bill.invnum)".
@@ -263,8 +261,7 @@ if ( $cgi->param('distribute') == 1 ) {
   push @where, "sdate <= $ending",
                "edate >  $beginning",
   ;
-}
-else {
+} else {
   push @where, "cust_bill._date >= $beginning",
                "cust_bill._date <= $ending";
 }
@@ -279,6 +276,7 @@ if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
   push @where, "cust_main.agentnum = $1";
 }
 
+# salesnum--see below
 # refnum
 if ( $cgi->param('refnum') =~ /^(\d+)$/ ) {
   push @where, "cust_main.refnum = $1";
@@ -302,10 +300,13 @@ if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
 # we want the package and its definition if available
 my $join_pkg = 
 ' LEFT JOIN cust_pkg      USING (pkgnum) 
-  LEFT JOIN part_pkg      USING (pkgpart)';
+  LEFT JOIN part_pkg      USING (pkgpart)
+  LEFT JOIN part_fee      USING (feepart)';
 
 my $part_pkg = 'part_pkg';
-if ( $cgi->param('use_override') ) { #"Separate sub-packages from parents"
+# "Separate sub-packages from parents"
+my $use_override = $cgi->param('use_override') ? 1 : 0;
+if ( $use_override ) {
   # still need the real part_pkg for tax applicability, 
   # so alias this one
   $join_pkg .= " LEFT JOIN part_pkg AS override ON (
@@ -313,12 +314,17 @@ if ( $cgi->param('use_override') ) { #"Separate sub-packages from parents"
   )";
   $part_pkg = 'override';
 }
-push @select, 'part_pkg.pkgpart', 'part_pkg.pkg'; # or should this use override?
+push @select, "$part_pkg.pkgpart", "$part_pkg.pkg";
+push @select, "($itemdesc) AS itemdesc"; # available in all report modes
+
+push @select, "COALESCE($part_pkg.taxclass, part_fee.taxclass) AS taxclass"
+  if $conf->exists('enable_taxclasses');
 
 # the non-tax case
 if ( $cgi->param('nottax') ) {
 
-  push @where, 'cust_bill_pkg.pkgnum > 0';
+  push @where,
+    '(cust_bill_pkg.pkgnum > 0 OR cust_bill_pkg.feepart IS NOT NULL)';
 
   my @tax_where; # will go into a subquery
   my @exempt_where; # will also go into a subquery
@@ -327,8 +333,25 @@ if ( $cgi->param('nottax') ) {
   # not specified: all classes
   # 0: empty class
   # N: classnum
-  if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
-    push @where, "COALESCE($part_pkg.classnum, 0) = $1";
+  if ( grep { $_ eq 'classnum' } $cgi->param ) {
+    my @classnums = grep /^\d+$/, $cgi->param('classnum');
+    push @where, "COALESCE(part_fee.classnum, $part_pkg.classnum, 0) IN ( ".
+                     join(',', @classnums ).
+                 ' )'
+      if @classnums;
+  }
+
+  if ( grep { $_ eq 'report_optionnum' } $cgi->param ) {
+    my $num = join(',', grep /^[\d,]+$/, $cgi->param('report_optionnum'));
+    my $not_num = join(',', grep /^[\d,]+$/, $cgi->param('not_report_optionnum'));
+    my $all = $cgi->param('all_report_options') ? 1 : 0;
+    push @where, # code reuse FTW
+      FS::Report::Table->with_report_option(
+        report_optionnum      => $num,
+        not_report_optionnum  => $not_num,
+        use_override          => $use_override,
+        all_report_options    => $all,
+      );
   }
 
   # taxclass
@@ -337,7 +360,7 @@ if ( $cgi->param('nottax') ) {
     # 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 (" .
+    push @tax_where, "COALESCE(part_fee.taxclass, $part_pkg.taxclass) IN (" .
                  join(', ', map {dbh->quote($_)} $cgi->param('taxclass') ).
                  ')';
   }
@@ -353,11 +376,8 @@ if ( $cgi->param('nottax') ) {
   # we don't handle exempt_monthly here
   
   if ( $cgi->param('taxname') ) { # specific taxname
-      push @tax_where, 'cust_main_county.taxname = '.
+      push @tax_where, "COALESCE(cust_main_county.taxname, 'Tax') = ".
                         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)
@@ -385,12 +405,8 @@ if ( $cgi->param('nottax') ) {
   }
 
   # 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 ( $cgi->param('taxnum') =~ /^([\d,]+)$/) {
+    push @tax_where, "cust_main_county.taxnum IN ($1)";
   }
 
   # If we're showing exempt items, we need to find those with 
@@ -402,189 +418,286 @@ if ( $cgi->param('nottax') ) {
   # 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;
+  # Always exclude cust_tax_exempt_pkg records with non-NULL creditbillpkgnum.
 
-  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)';
+  if ( $cgi->param('out') ) {
+    # separate from the rest, in that we're not going to join cust_main_county
+    # in the outer query
 
-    $exempt_sub .= ' WHERE '.join(' AND ', @tax_where, @exempt_where)
-      if (@tax_where or @exempt_where);
+    my @exclude = ( 'cust_tax_exempt_pkg.billpkgnum',
+                    'cust_bill_pkg_tax_location.taxable_billpkgnum'
+                  );
+    foreach my $col (@exclude) {
+      my ($table) = split(/\./, $col);
+      my $this_where = 'WHERE ' .  join(' AND ',
+        "$col = cust_bill_pkg.billpkgnum",
+        @tax_where
+      );
 
-    $exempt_sub .= ' GROUP BY billpkgnum';
+      push @where,
+      "NOT EXISTS(SELECT 1 FROM $table
+        JOIN cust_main_county USING (taxnum)
+        $this_where
+      )";
+    }
+  
+  } else {
+    # everything that returns things joined to a tax definition
 
-    $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)";
-  }
+    if ( @exempt_where or @tax_where or $cgi->param('taxable') ) {
 
-  # now do something with that
-  if ( @exempt_where ) {
+      push @exempt_where, "cust_tax_exempt_pkg.creditbillpkgnum IS NULL";
 
-    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";
+      # 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)';
 
-  } elsif ( $cgi->param('taxable') ) {
+      $exempt_sub .= ' WHERE '.join(' AND ', @tax_where, @exempt_where);
 
-    my $taxable = 'cust_bill_pkg.setup + cust_bill_pkg.recur '.
-                  '- COALESCE(item_exempt.exempt_amount, 0)';
+      $exempt_sub .= ' GROUP BY billpkgnum';
 
-    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";
+      $join_pkg .= " LEFT JOIN ($exempt_sub) AS item_exempt
+      ON (cust_bill_pkg.billpkgnum = item_exempt.billpkgnum)";
 
-  } elsif ( $cgi->param('out') ) {
-  
-    push @where,    'item_tax.invnum IS NULL',
-                    'item_exempt.billpkgnum IS NULL';
+    }
 
-  } elsif ( @tax_where ) {
+    if ( @tax_where or $cgi->param('taxable') ) {
+      # process tax restrictions
+      unshift @tax_where,
+        'cust_main_county.tax > 0';
 
-    # union of taxable + all exempt_ cases
-    push @where,
-      '(item_tax.invnum IS NOT NULL OR item_exempt.billpkgnum IS NOT NULL)';
+      my $tax_sub = "SELECT taxable_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.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';
 
-  # recur/usage separation
-  if ( $cgi->param('usage') eq 'recurring' ) {
+    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",
+                      "&minus; $money_char%.2f discounted",
+                      "= $money_char%.2f invoiced";
 
-    my $recur_no_usage = FS::cust_bill_pkg->charged_sql('', '', no_usage => 1);
+  } elsif ( $charges{R} and $charges{U} ) {
+
+    # hide rows with no recurring fee, and show the sum of recurring fees only
+    push @where, 'cust_bill_pkg.recur > 0';
+    push @total, "SUM(cust_bill_pkg.recur)";
+    push @total_desc, "$money_char%.2f recurring";
+
+  } elsif ( $charges{R} and !$charges{U} ) {
+
+    my $recur_no_usage = FS::cust_bill_pkg->charged_sql('', '', 
+      setuprecur => 'recur', 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)';
+    $peritem_desc[1] = 'Recurring charges (excluding usage)';
+    push @total, "SUM($recur_no_usage)";
+    push @total_desc, "$money_char%.2f recurring";
+    if ( !$charges{S} ) {
+      push @where, "($recur_no_usage) > 0";
+    }
 
-  } elsif ( $cgi->param('usage') eq 'usage' ) {
+  } elsif ( !$charges{R} and $charges{U} ) {
 
     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';
-  }
+    push @total, "SUM($usage)";
+    push @total_desc, "$money_char%.2f usage charges";
+    if ( !$charges{S} ) {
+      push @where, "($usage) > 0";
+    }
+
+  } elsif ( $charges{S} ) {
+
+    push @where, "cust_bill_pkg.setup > 0";
+    push @total, "SUM(cust_bill_pkg.setup)";
+    push @total_desc, "$money_char%.2f setup";
+
+  } # else huh? you have to have SOME charges
 
 } elsif ( $cgi->param('istax') ) {
 
-  @peritem = ( 'setup' ); # taxes only have setup
-  @peritem_desc = ( 'Tax charge' );
+  # ensure that it is a tax:
+  push @where, 'cust_bill_pkg.pkgnum = 0',
+               'cust_bill_pkg.feepart IS NULL';
 
-  push @where, 'cust_bill_pkg.pkgnum = 0';
+  # We MUST NOT join cust_bill_pkg to any table that it's 1:many to.
+  # Otherwise we get duplication of the cust_bill_pkg records, 
+  # inaccurate totals, nonsensical paging behavior, etc.
+  # We CAN safely join it to a subquery that has unique billpkgnums, and 
+  # that's what we'll do.
+
+  my $tax_subquery;
+  my @tax_where;
 
   # tax location when using tax_rate_location
-  if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
+  if ( $cgi->param('vendortax') ) {
 
-    $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 )
-                 );
+    $tax_subquery = '
+      SELECT billpkgnum, SUM(amount) as tax_total
+      FROM cust_bill_pkg_tax_rate_location AS tax
+        JOIN tax_rate_location USING (taxratelocationnum)
+    ';
+    foreach (qw( state county city locationtaxid)) {
+      if ( scalar($cgi->param($_)) ) {
+        my $place = dbh->quote( $cgi->param($_) );
+        push @tax_where, "tax_rate_location.$_ = $place";
+      }
+    }
 
-    $total[1] = 'SUM(
-      COALESCE(cust_bill_pkg_tax_rate_location.amount, 
-               cust_bill_pkg.setup + cust_bill_pkg.recur)
-    )';
+    # itemdesc, for breakdown from the vendor tax report
+    # (this is definitely used)
+    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'));
+      }
+    }
 
-  } elsif ( $cgi->param('out') ) {
+  } else { # the internal-tax case
+
+    my $tax_select = 'SELECT tax.billpkgnum, SUM(tax.amount) as tax_total';
+    my $tax_from = ' FROM cust_bill_pkg_tax_location AS tax JOIN cust_main_county USING (taxnum)';
+
+    # package classnum
+    if ( grep { $_ eq 'classnum' } $cgi->param ) {
+      my @classnums = grep /^\d*$/, $cgi->param('classnum');
+      $tax_from .= '
+        JOIN cust_bill_pkg AS taxed_item
+          ON (tax.taxable_billpkgnum = taxed_item.billpkgnum)
+        LEFT JOIN cust_pkg AS taxed_pkg ON (taxed_item.pkgnum = taxed_pkg.pkgnum)
+        LEFT JOIN part_pkg AS taxed_part_pkg ON (taxed_pkg.pkgpart = taxed_part_pkg.pkgpart)
+        LEFT JOIN part_fee AS taxed_part_fee ON (taxed_item.feepart = taxed_part_fee.feepart)
+      ';
+      push @tax_where,
+        "COALESCE(taxed_part_pkg.classnum, taxed_part_fee.classnum,0) IN ( ".
+                       join(',', @classnums ).
+                   ' )'
+        if @classnums;
+    }
 
-    $join_pkg .= '
-      LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
-    ';
-    push @where, 'cust_bill_pkg_tax_location.billpkgnum IS NULL';
+    # taxclass
+    if ( $cgi->param('taxclassNULL') ) {
+      push @tax_where, 'cust_main_county.taxclass IS NULL';
+    }
 
-    # each billpkgnum should appear only once
-    $total[0] = 'COUNT(*)';
-    $total[1] = 'SUM(cust_bill_pkg.setup)';
+    # taxname
+    if ( $cgi->param('taxnameNULL') ) {
+      push @tax_where, 'cust_main_county.taxname IS NULL OR '.
+                   'cust_main_county.taxname = \'Tax\'';
+    } elsif ( $cgi->param('taxname') ) {
+      push @tax_where, 'cust_main_county.taxname = '.
+                    dbh->quote($cgi->param('taxname'));
+    }
 
-  } else { # not locationtaxid or 'out'--the normal case
+    # itemdesc, for breakdown from the vendor tax report
+    # (is this even used? vendor tax report shouldn't use cust_bill_pkg.cgi)
+    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'));
+      }
+    }
 
-    $join_pkg .= '
-      LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
-      JOIN cust_main_county           USING (taxnum)
-    ';
+    # specific taxnums (the usual way)
+    if ( $cgi->param('taxnum') =~ /^([\d,]+)$/) {
+      push @tax_where, "cust_main_county.taxnum IN ($1)";
+    }
 
-    # 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)';
-  }
+    $tax_subquery = "$tax_select $tax_from";
 
-  # taxclass
-  if ( $cgi->param('taxclassNULL') ) {
-    push @where, 'cust_main_county.taxclass IS NULL';
-  }
+  } # end of internal-tax case
 
-  # 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'));
+  if (@tax_where) {
+    $tax_subquery .= '
+      WHERE ' . join(' AND ', map "($_)", @tax_where);
   }
+  $tax_subquery .= ' GROUP BY tax.billpkgnum ';
 
-  # 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;
-  }
+  # now join THAT into the main report
+  # (inner join, so that tax line items that don't match the tax_where 
+  # conditions don't appear in the output.)
 
-  # 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";
-    }
-  }
+  $join_pkg .= " JOIN ($tax_subquery) AS _istax USING (billpkgnum) ";
 
-  # 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'));
-    }
+  push @select, 'tax_total';
+
+  @peritem = ( 'setup' ); # total tax on the invoice, not just the filtered tax
+  @peritem_desc = ( 'Tax charge' );
+
+  @total = ( 'COUNT(cust_bill_pkg.billpkgnum)',
+             'SUM(cust_bill_pkg.setup)' );
+  @total_desc = ( "$money_char%.2f total tax" );
+
+  if ( @tax_where ) {
+    # then also show the filtered tax
+    push @peritem, 'tax_total';
+    push @peritem_desc, 'Tax in category';
+    push @total, 'SUM(tax_total)';
+    push @total_desc, "$money_char%.2f tax in this category";
+    # would also be nice to include a line explaining what the category is
   }
 
 } # nottax / istax
 
-
 #total payments
 my $pay_sub = "SELECT SUM(cust_bill_pay_pkg.amount)
                  FROM cust_bill_pay_pkg
@@ -592,80 +705,52 @@ my $pay_sub = "SELECT SUM(cust_bill_pay_pkg.amount)
               ";
 push @select, "($pay_sub) AS pay_amount";
 
+# showing credited amount, optionally with date filtering
+my $credit_where = '';
+if ( $cgi->param('credit_begin') or $cgi->param('credit_end') ) {
+  my($cr_begin, $cr_end) = FS::UI::Web::parse_beginning_ending($cgi, 'credit');
+  $credit_where = "WHERE cust_credit_bill._date >= $cr_begin " .
+                  "AND cust_credit_bill._date <= $cr_end";
+}
 
-# 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)";
+my $credit_sub = "SELECT SUM(cust_credit_bill_pkg.amount) AS credit_amount, billpkgnum
+                  FROM cust_credit_bill_pkg
+                  JOIN cust_credit_bill USING (creditbillnum)
+                  $credit_where
+                  GROUP BY billpkgnum";
 
-    }
+$join_pkg .= " LEFT JOIN ($credit_sub) AS item_credit
+  ON (cust_bill_pkg.billpkgnum = item_credit.billpkgnum)";
+push @select, 'credit_amount';
 
-  } 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)";
-  }
+# standard customer fields
+push @select, 'cust_main.custnum', FS::UI::Web::cust_sql_fields();
 
-  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";
+#salesnum
+if ( $cgi->param('salesnum') =~ /^(\d+)$/ ) {
 
-} else {
+  my $salesnum = $1;
+  my $sales = FS::sales->by_key($salesnum)
+    or die "salesnum $salesnum not found";
 
-  #still want a credit total column
+  my $subsearch = $sales->cust_bill_pkg_search('', '',
+    'cust_main_sales' => ($cgi->param('cust_main_sales') ? 1 : 0),
+    'paid'            => ($cgi->param('paid') ? 1 : 0),
+    'classnum'        => scalar($cgi->param('classnum'))
+  );
+  $join_pkg .= " JOIN sales_pkg_class ON ( COALESCE(sales_pkg_class.classnum, 0) = COALESCE( part_fee.classnum, part_pkg.classnum, 0) )";
 
-  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";
+  my $extra_sql = $subsearch->{extra_sql};
+  $extra_sql =~ s/^WHERE//;
+  push @where, $extra_sql;
 
+  $cgi->param('classnum', 0) unless $cgi->param('classnum');
 }
 
-push @select, 'cust_main.custnum', FS::UI::Web::cust_sql_fields();
+#credit flag (include only those that have credit(s) applied)
+if ( $cgi->param('credit') ) {
+  push @where, 'credit_amount > 0';
+}
 
 my $where = join(' AND ', @where);
 $where &&= "WHERE $where";
@@ -704,7 +789,13 @@ 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', ];
+my $credit_param = '';
+foreach ('credit_begin', 'credit_end') {
+  if ( $cgi->param($_) ) {
+    $credit_param .= "$_=" . $cgi->param($_) . ';';
+  }
+}
+my $credit_link = [ "${p}search/cust_credit_bill_pkg.html?${credit_param}billpkgnum=", 'billpkgnum', ];
 
 warn "\n\nQUERY:\n".Dumper($query)."\n\nCOUNT_QUERY:\n$count_query\n\n"
   if $cgi->param('debug');