Issue #9295 Issue #23537 Fix InvoiceListItem performance.
[xtuple] / foundation-database / public / functions / determinediscountdate.sql
1 CREATE OR REPLACE FUNCTION determineDiscountDate(INTEGER, DATE) RETURNS DATE 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 DECLARE
5   pTermsid ALIAS FOR $1;
6   pSourceDate ALIAS FOR $2;
7   _discDate DATE;
8   _p RECORD;
9
10 BEGIN
11
12   SELECT terms_type, terms_discdays, terms_cutoffday INTO _p
13   FROM terms
14   WHERE (terms_id=pTermsid);
15   IF (NOT FOUND) THEN
16     _discDate := pSourceDate;
17
18 --  Handle type D terms
19   ELSIF (_p.terms_type = 'D') THEN
20     _discDate := (pSourceDate + _p.terms_discdays);
21
22 --  Handle type P terms
23   ELSIF (_p.terms_type = 'P') THEN
24     IF (date_part('day', pSourceDate) <= _p.terms_cutoffday) THEN
25       _discDate := (DATE(date_trunc('month', pSourceDate)) + (_p.terms_discdays - 1));
26     ELSE
27       _discDate := (DATE(date_trunc('month', pSourceDate)) + (_p.terms_discdays - 1) + INTERVAL '1 month');
28     END IF;
29
30 --  Handle unknown terms
31   ELSE
32     _discDate := pSourceDate;
33   END IF;
34
35   RETURN _discDate;
36
37 END;
38 $$ LANGUAGE 'plpgsql';