CREATE OR REPLACE FUNCTION food600.opravainventurytest(
	cdata integer,
	cstredisk integer,
	mmenobuf character varying,
	cdokl integer,
	mmena_akt integer,
	oldmenobuf character varying)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE 
AS $BODY$
DECLARE kkarty CURSOR FOR SELECT c_karty, c_dokl, na_sklade FROM food600.buffer WHERE buffer.menobuf=mmenobuf AND buffer.c_data=cdata;
	ckarty INTEGER;
	ccdokl INTEGER;
	mzustatek numeric(20,10);
	nasklade numeric(20,10);
BEGIN
DELETE FROM food600.buffer WHERE c_data=cdata AND menobuf=mmenobuf;

INSERT INTO food600.buffer (c_dokl, c_karty, mnozstvi, menobuf, c_data) SELECT c_dokl, c_karty, mnozstvi, mmenobuf as menobuf, cdata as c_data FROM food600.obraty WHERE obraty.c_data=cdata AND obraty.c_stredisk=cstredisk AND obraty.c_dokl=cdokl;
INSERT INTO food600.buffer (c_karty, menobuf, c_data) SELECT c_karty, mmenobuf as menobuf, cdata as c_data FROM food600.buffer WHERE buffer.c_data=cdata AND buffer.menobuf=oldmenobuf EXCEPT SELECT c_karty, menobuf, c_data FROM food600.buffer WHERE menobuf=mmenobuf AND c_data=cdata;
UPDATE food600.buffer SET c_dokl= 0, mnozstvi= -1 WHERE buffer.c_data=cdata AND buffer.menobuf=mmenobuf;
UPDATE food600.buffer SET c_dokl=aaa.c_dokl FROM (SELECT MIN(c_dokl) as c_dokl, c_karty FROM food600.obraty WHERE obraty.c_dokl>cdokl AND c_stredisk=cstredisk AND operace='PI' AND c_data=cdata GROUP BY c_karty) aaa WHERE buffer.c_karty=aaa.c_karty AND buffer.menobuf=mmenobuf AND buffer.c_data=cdata;
UPDATE food600.buffer SET c_dokl=2000111222 WHERE buffer.menobuf=mmenobuf AND buffer.c_data=cdata AND buffer.c_dokl IS NULL;
OPEN kkarty;
LOOP
	FETCH kkarty INTO ckarty, ccdokl, nasklade;
	EXIT WHEN NOT FOUND;
	SELECT MIN(zustatek) INTO mzustatek FROM food600.obraty WHERE obraty.c_stredisk=cstredisk AND obraty.c_data=cdata AND obraty.c_karty=ckarty AND (food600.left(obraty.operace,1)='P' OR food600.left(obraty.operace,1)='V') AND obraty.c_dokl>cdokl AND obraty.c_dokl<ccdokl;
	IF mzustatek IS NULL THEN
	ELSE
		UPDATE food600.buffer SET mnozstvi=mzustatek WHERE buffer.menobuf=mmenobuf AND buffer.c_data=cdata AND buffer.c_karty=ckarty;
	END IF; 
END LOOP;
CLOSE kkarty;
END
$BODY$;
