let's get build_app running on a masterref database
[xtuple] / foundation-database / public / trigger_functions / cntslip.sql
1 CREATE OR REPLACE FUNCTION _cntslipTrigger() RETURNS TRIGGER 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   _p RECORD;
6   _comments TEXT;
7   _temp TEXT;
8
9 BEGIN
10   IF (TG_OP = ''DELETE'') THEN
11     SELECT itemsite_loccntrl, itemsite_controlmethod,
12            cntslip_posted, cntslip_lotserial, cntslip_comments,
13            cntslip_number, cntslip_qty INTO _p
14       FROM cntslip, invcnt, itemsite
15      WHERE ( (cntslip_cnttag_id=invcnt_id)
16        AND   (invcnt_itemsite_id=itemsite_id)
17        AND   (cntslip_id=OLD.cntslip_id) );
18
19     IF(_p.cntslip_posted) THEN
20       SELECT ( ''
21 Count Slip #'' || _p.cntslip_number ||
22              '' deleted '' || formatQty(_p.cntslip_qty) ) INTO _comments;
23
24 --  Add the Location name if the itemsite is MLC
25       IF (_p.itemsite_loccntrl) THEN
26         SELECT ( '', Location:'' || location_name ) INTO _temp
27           FROM location, cntslip
28          WHERE ( (cntslip_location_id=location_id)
29            AND   (cntslip_id=OLD.cntslip_id) );
30
31         _comments := (_comments || _temp);
32       END IF;
33
34 --  Add the Lot/Serial if the itemsite is Lot or Serial controlled
35       IF (_p.itemsite_controlmethod = ''L'') THEN
36         _comments := (_comments || ( '', Lot #:'' || _p.cntslip_lotserial));
37       ELSIF (_p.itemsite_controlmethod = ''S'') THEN
38         _comments := (_comments || ( '', Serial #:'' || _p.cntslip_lotserial));
39       END IF;
40
41       _comments := (_comments || '' '' || _p.cntslip_comments);
42
43       UPDATE invcnt
44          SET invcnt_qoh_after = ( COALESCE(invcnt_qoh_after, 0) - cntslip_qty),
45              invcnt_comments = (invcnt_comments || _comments)
46         FROM cntslip
47        WHERE ( (cntslip_cnttag_id=invcnt_id)
48          AND   (NOT invcnt_posted)
49          AND   (cntslip_id=OLD.cntslip_id) );
50
51     END IF;
52
53     RETURN OLD;
54   END IF;
55
56   RETURN NEW;
57 END;
58 ' LANGUAGE 'plpgsql';
59
60 DROP TRIGGER IF EXISTS cntslipTrigger ON cntslip;
61 CREATE TRIGGER cntslipTrigger BEFORE INSERT OR UPDATE OR DELETE ON cntslip FOR EACH ROW EXECUTE PROCEDURE _cntslipTrigger();