RT#37125: Include discounts in report: customer accounting summary
[freeside.git] / FS / FS / Report / Table.pm
index 0a0d24a..ffa1172 100644 (file)
@@ -272,17 +272,53 @@ sub netrefunds {
 
 sub discounted {
   my( $self, $speriod, $eperiod, $agentnum, %opt) = @_;
-  $self->scalar_sql('SELECT SUM(cust_bill_pkg_discount.amount)
-    FROM cust_bill_pkg_discount
-      JOIN cust_bill_pkg USING  ( billpkgnum )
-      JOIN cust_bill     USING  ( invnum )
-      JOIN cust_main     USING  ( custnum )
-    WHERE '. $self->in_time_period_and_agent( $speriod,
-                                              $eperiod,
-                                              $agentnum,
-                                              'cust_bill._date'
-                                            ).
-              $self->for_opts(%opt)
+
+  my $sql = 'SELECT SUM(';
+  if ($opt{'setuprecur'}) {
+    $sql .= <<EOF;
+CASE
+  WHEN discount.setup = 'Y' 
+    AND ((COALESCE(cust_bill_pkg.unitsetup,0) > 0) 
+          OR (COALESCE(cust_bill_pkg.unitrecur,0) > 0))
+  THEN
+EOF
+    if ($opt{'setuprecur'} eq 'setup') {
+      $sql .= '    (COALESCE(cust_bill_pkg.unitsetup,0)';
+    } elsif ($opt{'setuprecur'} eq 'recur') {
+      $sql .= '    (COALESCE(cust_bill_pkg.unitrecur,0)';
+    } else {
+      die 'Unrecognized value for setuprecur';
+    }
+    $sql .= ' / (COALESCE(cust_bill_pkg.unitsetup,0) + COALESCE(cust_bill_pkg.unitrecur,0)))';
+    $sql .= " * cust_bill_pkg_discount.amount\n";
+    $sql .= <<EOF;
+  ELSE cust_bill_pkg_discount.amount
+END
+EOF
+  } else {
+    $sql .= "cust_bill_pkg_discount.amount\n";
+  }
+  $sql .= <<EOF;
+) FROM cust_bill_pkg_discount
+  JOIN cust_bill_pkg     USING  ( billpkgnum )
+  JOIN cust_bill         USING  ( invnum )
+  JOIN cust_main         USING  ( custnum )
+EOF
+  if ($opt{'setuprecur'}) {
+    $sql .= <<EOF;
+  JOIN cust_pkg_discount USING ( pkgdiscountnum )
+  LEFT JOIN discount          USING ( discountnum )
+EOF
+  }
+  $self->scalar_sql(
+    $sql 
+    . 'WHERE '
+    . $self->in_time_period_and_agent( $speriod,
+                                       $eperiod,
+                                       $agentnum,
+                                       'cust_bill._date'
+                                      )
+    . $self->for_opts(%opt)
   );
 }