CREATE OR REPLACE FUNCTION food600.odpocet_polotovarov(
	mmeno character varying,
	cdata integer,
	mcstredisk integer,
	mmenaakt integer,
	mdavka character varying,
	narast integer,
	mbuffer character varying)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE mckarty INTEGER;
	pocetriadkov INTEGER DEFAULT 1000;
	pocetvsk INTEGER;
	mdone INTEGER DEFAULT 0;
	vystup INTEGER;
	odp_c_hl CURSOR FOR SELECT DISTINCT c_karty FROM food600.davky WHERE c_data=cdata AND davka=mdavka AND c_stredisk=mcstredisk AND mnozstvi<>0;
BEGIN
DELETE FROM food600.sk1 WHERE c_data=cdata AND menobuf=mmeno;
DELETE FROM food600.buffer WHERE menobuf=mmeno AND c_data=cdata;
DELETE FROM food600.bufferd WHERE menobuf=mmeno AND c_data=cdata;
DELETE FROM food600.odp_log WHERE menobuf=mmeno AND c_data=cdata;
OPEN odp_c_hl;
WHILE (mdone<pocetriadkov) LOOP
	mdone:=mdone+1;
	FETCH odp_c_hl INTO mckarty;
	IF mckarty ISNULL THEN
		pocetriadkov:=0;
	END IF;
	IF mdone<=pocetriadkov THEN
		DELETE FROM food600.sk1 WHERE menobuf=mmeno AND c_data=cdata;
		INSERT INTO food600.sk1 (menobuf, c_data, c_karty, mnozstvi) SELECT mmeno as menobuf, cdata as c_data, c_karty, SUM(mnozstvi) as mnozstvi FROM food600.davky WHERE davka=mdavka AND c_data=cdata AND c_karty=mckarty AND c_stredisk=mcstredisk GROUP BY c_karty, menobuf, c_data;
		SELECT COUNT(*) INTO pocetvsk FROM food600.sk1 WHERE menobuf=mmeno AND c_data=cdata;
		IF pocetvsk>0 THEN
			SELECT food600.kalkuluj_polotovary(mmeno, mcstredisk, mmenaakt, cdata, narast, mckarty) INTO vystup;
			DELETE FROM food600.sk1 WHERE menobuf=mmeno AND c_data=cdata;
		END IF;
	END IF;
END LOOP;
CLOSE odp_c_hl;
DELETE FROM food600.sk1 WHERE c_data=cdata AND menobuf=mmeno;
UPDATE food600.buffer SET nazev=karty.nazev FROM food600.karty WHERE buffer.c_karty=karty.c_karty AND buffer.c_data=karty.c_data AND buffer.menobuf=mmeno AND buffer.c_data=cdata;
UPDATE food600.buffer SET cena=odpocet_askl.cena_prum, zustatek=odpocet_askl.zustatek FROM food600.odpocet_askl WHERE buffer.c_karty=odpocet_askl.c_karty AND buffer.c_data=odpocet_askl.c_data AND buffer.menobuf=odpocet_askl.menobuf AND buffer.menobuf=mmeno AND buffer.c_data=cdata;
UPDATE food600.buffer SET cena=food600.prep_meny(karty.c_mena_n,mmenaakt,karty.cena_prum), serial_no='CENA0' FROM food600.karty WHERE buffer.c_karty=karty.c_karty AND buffer.c_data=karty.c_data AND buffer.menobuf=mmeno AND buffer.c_data=cdata AND mnozstvi=0 AND cena=0;
INSERT INTO food600.bufferd (operace, datum_dokl, pz1, c_partner, menobuf, c_data, c_stredisk, c_mena) VALUES ('VP', current_date, mdavka, mcstredisk, mmeno, cdata, mcstredisk, mmenaakt);
DELETE FROM food600.odpocet_askl WHERE menobuf=mmeno AND c_data=cdata;
DELETE FROM food600.odpocet_kalk WHERE menobuf=mmeno AND c_data=cdata;
RETURN 1;
END
$BODY$;
