Issue #23255:progress
[xtuple] / foundation-database / public / functions / importbankreccleared.sql
1
2 CREATE OR REPLACE FUNCTION importBankrecCleared(pBankrecid INTEGER) RETURNS BOOLEAN AS $$
3 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4 -- See www.xtuple.com/CPAL for the full text of the software license.
5 DECLARE
6   _result INTEGER := 0;
7   _cleared BOOLEAN;
8   _doctype TEXT;
9   _docid INTEGER;
10   _b RECORD;
11   _r RECORD;
12
13 BEGIN
14   -- cache some information
15   SELECT * INTO _b
16   FROM bankrec JOIN bankaccnt ON (bankaccnt_id=bankrec_bankaccnt_id)
17   WHERE (bankrec_id=pBankrecid);
18   IF (NOT FOUND) THEN
19     RAISE EXCEPTION 'bankrec not found';
20   END IF;
21   IF (_b.bankrec_posted) THEN
22     RAISE EXCEPTION 'bankrec already posted';
23   END IF;
24
25   -- loop thru bankrecimport and toggle cleared items
26   FOR _r IN
27   SELECT *,
28          COALESCE(bankrecimport_debit_amount, 0.0) AS debit,
29          COALESCE(bankrecimport_credit_amount, 0.0) AS credit
30   FROM bankrecimport
31 --  WHERE (bankrecimport_?=_b.bankaccnt=?)
32   LOOP
33
34     IF ( (_r.debit > 0.0) AND (_r.credit > 0.0) ) THEN
35       RAISE NOTICE 'Bankrecimport % cannot determine if debit or credit', _r.bankrecimport_reference;
36       CONTINUE;
37     END IF;
38
39     IF (_r.debit > 0.0) THEN
40       -- check receipts
41       SELECT cashrcpt_id INTO _docid
42       FROM cashrcpt
43       WHERE (cashrcpt_docnumber=_r.bankrecimport_reference)
44         AND (cashrcpt_posted);
45       IF (FOUND) THEN
46         SELECT toggleBankrecCleared(_b.bankrec_id, 'GL', gltrans_id, cashrcpt_curr_rate, _r.debit, _r.bankrecimport_effdate) INTO _cleared
47         FROM cashrcpt JOIN gltrans ON ((gltrans_source='A/R')
48                                   AND (gltrans_doctype='CR')
49                                   AND (gltrans_accnt_id=_b.bankaccnt_accnt_id)
50                                   AND (gltrans_misc_id=cashrcpt_id))
51         WHERE (cashrcpt_id=_docid);
52         CONTINUE;
53       END IF;
54     END IF;
55
56     RAISE NOTICE 'Bankrecimport % not found', _r.bankrecimport_reference;
57
58   END LOOP;
59
60   RETURN _result;
61 END;
62 $$ LANGUAGE 'plpgsql';
63