Merge pull request #1 from shackbarth/keith1
[xtuple] / foundation-database / public / functions / calcinvoiceamt.sql
1 CREATE OR REPLACE FUNCTION calcInvoiceAmt(pInvcheadid INTEGER) RETURNS NUMERIC STABLE AS $$
2 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3 -- See www.xtuple.com/CPAL for the full text of the software license.
4 BEGIN
5
6   RETURN calcInvoiceAmt(pInvcheadid, 'T');
7
8 END;
9 $$ LANGUAGE 'plpgsql';
10
11 CREATE OR REPLACE FUNCTION calcInvoiceAmt(pInvcheadid INTEGER,
12                                           pType TEXT) RETURNS NUMERIC STABLE AS $$
13 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
14 -- See www.xtuple.com/CPAL for the full text of the software license.
15 DECLARE
16   _subtotal NUMERIC := 0.0;
17   _cost NUMERIC := 0.0;
18   _tax NUMERIC := 0.0;
19   _freight NUMERIC := 0.0;
20   _misc NUMERIC := 0.0;
21   _amount NUMERIC := 0.0;
22
23 BEGIN
24
25   -- pType: S = line item subtotal
26   --        T = total
27   --        X = tax
28   --        M = margin
29
30   SELECT COALESCE(SUM(ROUND((invcitem_billed * invcitem_qty_invuomratio) *
31                             (invcitem_price / COALESCE(invcitem_price_invuomratio, 1.0)), 2)), 0.0),
32          COALESCE(SUM(ROUND((invcitem_billed * invcitem_qty_invuomratio) *
33                             COALESCE(coitem_unitcost, itemCost(itemsite_id), 0.0), 2)), 0.0)
34          INTO _subtotal, _cost
35   FROM invcitem LEFT OUTER JOIN coitem ON (coitem_id=invcitem_coitem_id)
36                 LEFT OUTER JOIN itemsite ON (itemsite_item_id=invcitem_item_id AND itemsite_warehous_id=invcitem_warehous_id)
37   WHERE (invcitem_invchead_id=pInvcheadid);
38
39   IF (pType IN ('T', 'X')) THEN
40     SELECT COALESCE(SUM(tax), 0.0) INTO _tax
41     FROM (SELECT COALESCE(ROUND(SUM(taxdetail_tax), 2), 0.0) AS tax
42           FROM tax
43                JOIN calculateTaxDetailSummary('I', pInvcheadid, 'T')ON (taxdetail_tax_id=tax_id)
44           GROUP BY tax_id) AS data;
45   END IF;
46
47   IF (pType = 'T') THEN
48     SELECT COALESCE(invchead_freight, 0), COALESCE(invchead_misc_amount, 0)
49            INTO _freight, _misc
50     FROM invchead
51     WHERE (invchead_id=pinvcheadid);
52   END IF;
53
54   _amount := CASE pType WHEN 'S' THEN (_subtotal)
55                         WHEN 'T' THEN (_subtotal + _tax + _freight + _misc)
56                         WHEN 'X' THEN (_tax)
57                         WHEN 'M' THEN (_subtotal - _cost)
58                         ELSE 0.0
59              END;
60
61   RETURN _amount;
62
63 END;
64 $$ LANGUAGE 'plpgsql';