Trigger checking MaintainUsers priv before updating table to avoid bug 24255
[xtuple] / foundation-database / public / functions / balanceitemsite.sql
1 CREATE OR REPLACE FUNCTION balanceItemsite(INTEGER) RETURNS INTEGER 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 DECLARE
5   pItemsiteid ALIAS FOR $1;
6   _itemlocseries INTEGER;
7   _balanced NUMERIC;
8   _qoh NUMERIC;
9   _nnQoh NUMERIC;
10
11 BEGIN
12
13 --  Make sure that that passed Itemsite is MLC or Lot/Serial controlled
14   IF ( ( SELECT (NOT ( (itemsite_loccntrl) OR (itemsite_controlmethod IN ('L', 'S')) ))
15          FROM itemsite
16          WHERE (itemsite_id=pItemsiteid) ) ) THEN
17     RETURN 0;
18   END IF;
19
20   IF ( ( SELECT itemsite_freeze
21            FROM itemsite
22           WHERE(itemsite_id=pItemsiteid) ) ) THEN
23     RETURN -1;
24   END IF;
25
26 --  Calculate the Netable portion
27   SELECT COALESCE(SUM(itemloc_qty), 0) INTO _balanced
28   FROM itemloc LEFT OUTER JOIN location ON (itemloc_location_id=location_id)
29   WHERE ( ( (location_id IS NULL) OR (location_netable) )
30    AND (itemloc_itemsite_id=pItemsiteid) );
31
32 --  Post an AD Transaction for the Netable portion
33   SELECT invAdjustment( itemsite_id, (_balanced - itemsite_qtyonhand),
34                         'Balance', 'Inventory Balance' ) INTO _itemlocseries
35   FROM itemsite
36   WHERE (itemsite_id=pItemsiteid);
37
38 --  Post the itemloc series which will postIntoTrialBalance and postInvHist
39   PERFORM postItemlocSeries(_itemlocseries);
40
41 --  Kill the resultant distribution records
42   DELETE FROM itemlocdist
43   WHERE (itemlocdist_series=_itemlocseries);
44
45 --  Calculate and write the Non-Netable portion directly
46   SELECT COALESCE(SUM(itemloc_qty), 0) INTO _nnQoh
47   FROM itemloc, location
48   WHERE ( (itemloc_location_id=location_id)
49    AND (NOT location_netable)
50    AND (itemloc_itemsite_id=pItemsiteid) );
51
52   UPDATE itemsite
53   SET itemsite_nnqoh = _nnQoh
54   WHERE (itemsite_id=pItemsiteid);
55
56   RETURN 1;
57
58 END;
59 $$ LANGUAGE 'plpgsql';