ALTER FUNCTION "DBA"."get_eak_itemsum"( in a_id_dk_earve integer, in a_id_dk_earve_rida integer )
RETURNS decimal(20,2)
BEGIN
  declare ldc_return decimal(20,2);
  declare ldc_summa decimal(20,2);
  declare ldc_discount decimal(20,2);
  set ldc_return=0;
  set ldc_summa=0;
  select sum(if "dk_earve_ext"."text1"='DSC' then -1*abs(cast(trim("dk_earve_ext"."text4") as decimal(20,2))) else abs(cast(trim("dk_earve_ext"."text4") as decimal(20,2))) endif) into ldc_discount from "dk_earve_ext" where "dk_earve_ext"."id_dk_earve"=a_id_dk_earve and "dk_earve_ext"."id_dk_earve_rida"=a_id_dk_earve_rida and "dk_earve_ext"."parent"='ItemEntry' and "dk_earve_ext"."name"='Addition';
  if ldc_discount is null then
    set ldc_discount=0
  end if;
  select (if (sumbeforevat is null or sumbeforevat=0) then (if (itemtotal is null or itemtotal=0) then itemsum+ldc_discount else itemtotal-(if vatsum is null then 0 else vatsum endif) endif) else sumbeforevat endif) into ldc_summa from "dk_earve_rida" where "dk_earve_rida"."id_dk_earve"=a_id_dk_earve and "dk_earve_rida"."id"=a_id_dk_earve_rida;
  if ldc_summa is not null then
    set ldc_return=ldc_return+ldc_summa
  end if;
  set ldc_summa=0;
  select "dk_earve_sum"."rounding" into ldc_summa from "dk_earve_sum" where "dk_earve_sum"."id_dk_earve"=a_id_dk_earve and "dk_earve_sum"."id"=1 and a_id_dk_earve_rida=1;
  if ldc_summa is not null then
    set ldc_return=ldc_return+ldc_summa
  end if;
  return ldc_return;
END