Projekt

Allgemein

Profil

Fehler #342 » glinetotal_0_1.sql

G. Richardson, 06.02.2018 13:14

 
1
CREATE OR REPLACE FUNCTION public.glinetotal(in_qty real, in_sellprice numeric, in_price_factor numeric, in_discount real, in_exchangerate numeric, in_taxincluded boolean, in_taxrate numeric, OUT linetotal_net numeric, OUT linetotal_gross numeric, OUT linetotal_tax_amount numeric, OUT linetotal_discount_amount numeric, OUT sellprice_net numeric)
2
 RETURNS record
3
 LANGUAGE plpgsql
4
AS $function$
5
DECLARE
6
  num_dec   int;
7
  discount  numeric(15,5);
8
  sellprice numeric(15,5);
9
  linetotal numeric(15,5);
10
  tax       numeric(15,5);
11
  qty       numeric(15,5);
12
  linetotal_no_discount numeric(15,5);
13
BEGIN
14
  -- some assumptions: qty = base_qty
15

    
16
  -- linetotals must always be rounded to two digits
17
  num_dec := 2;
18

    
19
  sellprice := in_sellprice::numeric;
20
  qty       := in_qty::numeric;
21

    
22
  linetotal_no_discount := ROUND(in_sellprice                            * qty / in_price_factor, num_dec)::numeric(15,5);
23
  linetotal             := ROUND(in_sellprice * (1-in_discount)::numeric * qty / in_price_factor, num_dec)::numeric(15,5);
24
  -- RAISE NOTICE 'linetotal_no_discount = %, linetotal = %', linetotal_no_discount, linetotal;
25

    
26
  linetotal_discount_amount := linetotal_no_discount - linetotal;
27

    
28
  IF in_taxincluded THEN
29
    -- sellprice is gross
30
    linetotal_gross := linetotal;
31
    linetotal_net   := ROUND( linetotal_gross / (1+in_taxrate) , num_dec);
32
  ELSE
33
    -- sellprice is net
34
    linetotal_net   := linetotal;
35
    tax             := ROUND(linetotal_net * in_taxrate,2);
36
    linetotal_gross := linetotal_net + tax;
37
  END IF;
38

    
39
  linetotal_tax_amount := linetotal_gross - linetotal_net;
40
  sellprice_net := (linetotal_net / qty)::numeric(15,5);
41

    
42
  RETURN;
43
END;
44
$function$;
45

    
46
select * from glinetotal(1000, 4.5::numeric, 1, 0.05, 1, 'f', 0.19);
47
--           linetotal_net             | 4275.00000
48
--           linetotal_gross           | 5087.25000
49
--           linetotal_tax_amount      | 812.25000
50
--           linetotal_discount_amount | 225.00000
51
--           sellprice_net             | 4.27500
52

    
53
select * from glinetotal(1000, (4.5*1.19)::numeric, 1, 0.05, 1, 't', 0.19);
54
--           linetotal_net             | 4275.00
55
--           linetotal_gross           | 5087.25000
56
--           linetotal_tax_amount      | 812.25000
57
--           linetotal_discount_amount | 267.75000
58
--           sellprice_net             | 4.27500
59

    
    (1-1/1)