CREATE OR REPLACE FUNCTION food600.ulozinventuru(cdata integer, cstredisk integer, mmenobuf character varying, isvybrane integer, cmena integer)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
DELETE FROM food600.inv_uloz WHERE kdy < current_date - 77 ;
INSERT INTO food600.inv_uloz (c_stredisk, c_karty, mnozstvi, na_sklade, kdy, c_data) SELECT c_stredisk, c_karty, mnozstvi, na_sklade, current_timestamp(1), c_data FROM food600.buffer WHERE buffer.c_data=cdata AND buffer.menobuf=mmenobuf;
IF isvybrane=0 THEN
	DELETE FROM food600.inventur WHERE c_data=cdata AND c_stredisk=cstredisk AND vk<>'V';
	INSERT INTO food600.inventur (c_karty, c_stredisk, mnozstvi,c_data) SELECT c_karty, cstredisk, mnozstvi, cdata FROM food600.buffer WHERE buffer.c_data=cdata AND buffer.menobuf=mmenobuf;
ELSE
	DELETE FROM food600.inventur WHERE c_data=cdata AND c_stredisk=cstredisk AND vk='V';
	INSERT INTO food600.inventur (c_karty, c_stredisk, mnozstvi,c_data, vk) SELECT c_karty, cstredisk as c_stredisk, mnozstvi, cdata, 'V' as vk FROM food600.buffer WHERE buffer.c_data=cdata AND buffer.menobuf=mmenobuf;
END IF;
DELETE FROM food600.davky WHERE c_data=cdata AND c_stredisk=cstredisk AND davka='__INVENTURA__';
INSERT INTO food600.davky (c_stredisk, c_karty, mnozstvi, davka, c_mena) SELECT c_stredisk, c_karty, mnozstvi, '__INVENTURA__', cmena FROM food600.buffer WHERE buffer.c_data=cdata AND buffer.menobuf=mmenobuf AND buffer.mnozstvi>0 AND buffer.mnozstvi>buffer.na_sklade AND c_karty IN (SELECT DISTINCT c_karty FROM food600.polozky);
END
$function$
;
