CREATE OR REPLACE FUNCTION food600.prep_odpocet(
	mmenobuf character varying,
	cdata integer,
	mmenaakt integer,
	cstredisk integer,
	ajinventura smallint)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE zapisuj INTEGER DEFAULT 0;
pocetkariet BIGINT DEFAULT 0;
mdone2 BIGINT DEFAULT 0;
ckarty BIGINT DEFAULT 0;
mc_mena INTEGER;
mc_mena_z INTEGER;
mc_mena_na INTEGER;
mzostatok numeric(20,10);
mzostatok2 numeric(20,10);
mnovacena numeric(20,10);
zaokruhlenie INTEGER DEFAULT 10;
prep2 CURSOR FOR SELECT DISTINCT c_karty FROM food600.odpocet_askl WHERE menobuf=mmenobuf AND c_data=cdata AND prepocet=0;
BEGIN
SELECT COUNT(DISTINCT c_karty) INTO pocetkariet FROM food600.odpocet_askl WHERE menobuf=mmenobuf AND c_data=cdata AND prepocet=0;
OPEN prep2;
WHILE mdone2<pocetkariet LOOP
	mdone2:=mdone2+1;
	FETCH prep2 INTO ckarty;
	IF ajinventura=1 THEN
		SELECT cena_prum, zustatek, c_mena INTO mnovacena, mzostatok, mc_mena_na FROM food600.skl_buf WHERE c_karty=ckarty AND c_data=cdata AND c_stredisk=cstredisk;
		SELECT mnozstvi INTO mzostatok2 FROM food600.inventur WHERE c_karty=ckarty AND c_data=cdata AND c_stredisk=cstredisk;
		IF mzostatok2 IS NOT NULL THEN
			mzostatok:=mzostatok+mzostatok2;
		END IF;
	ELSE
		SELECT cena_prum, zustatek, c_mena INTO mnovacena, mzostatok, mc_mena_na FROM food600.sklad WHERE c_karty=ckarty AND c_data=cdata AND c_stredisk=cstredisk;
	END IF;	
	IF mnovacena IS NULL THEN
		mnovacena:=0;
		mc_mena:=mmenaakt;
		mc_mena_na:=mmenaakt;
		mzostatok:=0;
	END IF;
	IF mc_mena_na<>mmenaakt THEN
		mnovacena:=ROUND(CAST(food600.prep_meny(mc_mena_na,mmenaakt,mnovacena) AS NUMERIC),zaokruhlenie);
	END IF;
	UPDATE food600.odpocet_askl SET c_mena=mmenaakt, k_odpoctu=mzostatok, zustatek=mzostatok, cena_prum=mnovacena, prepocet=1 WHERE c_karty=ckarty AND menobuf=mmenobuf AND c_data=cdata;
END LOOP;
CLOSE prep2;
END
$BODY$;
