Issue #23758:correctly calc costs and margins for kits
[xtuple] / foundation-database / public / functions / itemcost.sql
1 CREATE OR REPLACE FUNCTION itemCost(pItemid INTEGER,
2                                     pCustid INTEGER,
3                                     pShiptoid INTEGER,
4                                     pQty NUMERIC,
5                                     pQtyUOM INTEGER,
6                                     pPriceUOM INTEGER,
7                                     pCurrid INTEGER,
8                                     pEffective DATE,
9                                     pAsOf DATE,
10                                     pSiteid INTEGER) RETURNS NUMERIC STABLE AS $$
11 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
12 -- See www.xtuple.com/CPAL for the full text of the software license.
13 --
14 -- Overload for future costing enhancements
15 --
16 DECLARE
17   _r RECORD;
18   _cost NUMERIC := 0.0;
19 BEGIN
20   -- cache item info
21   SELECT * INTO _r
22   FROM itemsite, item
23   WHERE (itemsite_item_id=pItemid)
24     AND (itemsite_warehous_id=pSiteid)
25     AND (item_id=pItemid);
26
27   IF (_r.item_type = 'K') THEN
28     SELECT SUM(roundQty(itemuomfractionalbyuom(bomitem_item_id, bomitem_uom_id),
29                                                (bomitem_qtyfxd + bomitem_qtyper) * (1 + bomitem_scrap))
30                * stdCost(bomitem_item_id)) INTO _cost
31     FROM bomitem
32     WHERE (bomitem_parent_item_id=_r.item_id)
33       AND (bomitem_rev_id=getActiveRevid('BOM', _r.item_id))
34       AND (pEffective BETWEEN bomitem_effective AND (bomitem_expires - 1));
35   ELSEIF (fetchMetricBool('WholesalePriceCosting')) THEN
36     _cost := _r.item_listcost;
37   ELSE
38     SELECT itemcost(_r.itemsite_id) INTO _cost;
39   END IF;
40
41   RETURN _cost;
42 END;
43 $$ LANGUAGE 'plpgsql';
44
45 CREATE OR REPLACE FUNCTION itemCost(pItemsiteid INTEGER) RETURNS NUMERIC STABLE AS $$
46 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
47 -- See www.xtuple.com/CPAL for the full text of the software license.
48 DECLARE
49   _cost NUMERIC;
50 BEGIN
51   SELECT CASE WHEN (itemsite_costmethod='A' AND itemsite_qtyonhand != 0.0) THEN (itemsite_value / itemsite_qtyonhand)
52               WHEN (itemsite_costmethod='A' AND itemsite_qtyonhand = 0.0) THEN 0.0
53               WHEN (itemsite_costmethod='N') THEN 0.0
54               ELSE stdCost(itemsite_item_id)
55          END INTO _cost
56     FROM itemsite
57    WHERE(itemsite_id=pItemsiteid);
58   RETURN _cost;
59 END;
60 $$ LANGUAGE 'plpgsql';