Issue #23416:apply price uom ratio to unit cost
[xtuple] / foundation-database / public / functions / calcquoteamt.sql
1 CREATE OR REPLACE FUNCTION calcQuoteAmt(pQuheadid 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 calcQuoteAmt(pQuheadid, 'T');
7
8 END;
9 $$ LANGUAGE 'plpgsql';
10
11 CREATE OR REPLACE FUNCTION calcQuoteAmt(pQuheadid INTEGER,
12                                         pType TEXT) RETURNS NUMERIC STABLE AS $$
13 -- Copyright (c) 1999-2014 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((quitem_qtyord * quitem_qty_invuomratio) *
31                             (quitem_price / quitem_price_invuomratio), 2)), 0.0),
32          COALESCE(SUM(ROUND((quitem_qtyord * quitem_qty_invuomratio) *
33                             (quitem_unitcost / quitem_price_invuomratio), 2)), 0.0)
34          INTO _subtotal, _cost
35   FROM quitem
36   WHERE (quitem_quhead_id=pQuheadid);
37
38   IF (pType IN ('T', 'X')) THEN
39     SELECT COALESCE(ROUND(SUM(taxdetail_tax), 2), 0.0) INTO _tax
40     FROM calculateTaxDetailSummary('Q', pQuheadid, 'T');
41   END IF;
42
43   IF (pType = 'T') THEN
44     SELECT COALESCE(quhead_freight, 0), COALESCE(quhead_misc, 0) INTO _freight, _misc
45     FROM quhead
46     WHERE (quhead_id=pQuheadid);
47   END IF;
48
49   _amount := CASE pType WHEN 'S' THEN (_subtotal)
50                         WHEN 'T' THEN (_subtotal + _tax + _freight + _misc)
51                         WHEN 'X' THEN (_tax)
52                         WHEN 'M' THEN (_subtotal - _cost)
53                         ELSE 0.0
54              END;
55
56   RETURN _amount;
57
58 END;
59 $$ LANGUAGE 'plpgsql';