CREATE OR REPLACE FUNCTION food600.maz_odpocet_novy(
	mucet integer,
	mcdata integer,
	mcstredisk integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE 
	prdoklady CURSOR FOR SELECT c_dokl FROM food600.doklady WHERE c_data=mcdata AND c_stredisk=mcstredisk AND operace='VK' AND pz2 IN (SELECT sleva_txt FROM food600.sk__pol_pom WHERE ucet=mucet) ;
	karty CURSOR FOR SELECT DISTINCT c_karty FROM food600.obraty WHERE c_dokl IN (SELECT c_dokl FROM food600.doklady WHERE operace='VK' and c_stredisk=mcstredisk and pz2 in (select sleva_txt FROM food600.sk__pol_pom WHERE ucet=mucet));
	pztky CURSOR FOR SELECT sleva_txt FROM food600.sk__pol_pom WHERE ucet=mucet;
	mcdokl INTEGER;
	mdone INTEGER DEFAULT 0;
	midman CHARACTER VARYING;
	mcuzaverka INTEGER;
	mckarty INTEGER;
	mpz2 CHARACTER(15);
BEGIN
SELECT id INTO midman FROM food600.food_dat WHERE c_stredisk=mcstredisk AND c_data=mcdata;
OPEN karty;
mdone:=10100;
WHILE (mdone>0) LOOP
	FETCH karty INTO mckarty;
	IF mckarty ISNULL THEN
		mdone:=0;
	ELSE
		SELECT MIN(c_dokl) INTO mcdokl FROM (SELECT DISTINCT c_dokl FROM food600.obraty WHERE c_karty=mckarty AND c_stredisk=mcstredisk AND c_dokl IN (SELECT c_dokl FROM food600.doklady WHERE operace='VK' and c_stredisk=mcstredisk and pz2 in (select sleva_txt FROM food600.sk__pol_pom WHERE ucet=mucet))) aaa;
		UPDATE food600.obraty SET dan=9 WHERE c_karty=mckarty AND c_stredisk=mcstredisk AND c_dokl IN (SELECT c_dokl FROM food600.doklady WHERE operace='VK' and c_stredisk=mcstredisk and pz2 in (select sleva_txt FROM food600.sk__pol_pom WHERE ucet=mucet)) AND c_dokl<>mcdokl;
	END IF;
END LOOP;
CLOSE karty;
OPEN prdoklady;
mdone:=10100;
WHILE (mdone>0) LOOP
	FETCH prdoklady INTO mcdokl;
	IF mcdokl ISNULL THEN
		mdone:=0;
	ELSE
		DELETE FROM food600.obraty WHERE c_dokl=mcdokl AND c_data=mcdata AND dan=9;
	END IF;
END LOOP;
CLOSE prdoklady;
RETURN 1;
END
$BODY$;
