CREATE OR REPLACE FUNCTION food600.odpocet_stop_limity(
	mmeno character varying,
	cdata integer,
	mcstredisk integer,
	mmenaakt integer,
	idlimit integer,
	idden integer,
	idrov integer,
	ajinventura smallint)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE 
AS $BODY$
DECLARE pocetvsk INTEGER;
	vystup INTEGER;
BEGIN
DELETE FROM food600.sk1 WHERE c_data=cdata AND menobuf=mmeno;
DELETE FROM food600.odp_log WHERE menobuf=mmeno AND c_data=cdata;
--Odpocet z novych limitov
INSERT INTO food600.sk1 (menobuf, c_data, c_karty, mnozstvi) SELECT mmeno as menobuf, nlimity.c_data, nlimity.c_karty, SUM(nlimity.mnozstvi) AS mnozstvi FROM food600.nlimity WHERE  nlimity.c_data = cdata AND  nlimity.id_limit=idlimit AND nlimity.id_den=idden AND nlimity.id_rov=idrov AND nlimity.c_stredisk=mcstredisk AND c_karty NOT IN (SELECT c_karty FROM food600.karty WHERE c_druhk IN (SELECT c_druh FROM food600.skupiny WHERE spart_kas='SRV'))  GROUP BY nlimity.c_karty, nlimity.c_data, menobuf ;
SELECT COUNT(*) INTO pocetvsk FROM food600.sk1 WHERE menobuf=mmeno AND c_data=cdata;
IF pocetvsk>0 THEN
	SELECT food600.kalkuluj(mmeno, mcstredisk, mmenaakt, cdata, '', '', '', ajinventura::smallint) INTO vystup;
	DELETE FROM food600.sk1 WHERE menobuf=mmeno AND c_data=cdata;
END IF;
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$;
