CREATE OR REPLACE FUNCTION food600.zalohapouzavierke(
	cstredisk integer,
	mmesiac integer,
	mrok integer,
	cdata integer,
	meno character varying,
	ku_dokladu integer,
	cmena integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE tenmesiac INTEGER DEFAULT mrok*12+mmesiac;
	oldmesiac INTEGER DEFAULT 0;
BEGIN
oldmesiac:=tenmesiac-3;
DELETE FROM food600.archivsklad WHERE c_data=cdata AND c_stredisk=cstredisk AND (rok*12+mesiac)<oldmesiac;
DELETE FROM food600.archivsklad WHERE c_data=cdata AND c_stredisk=cstredisk AND  (rok*12+mesiac)=tenmesiac;
DELETE FROM food600.archivdoklady WHERE c_data=cdata AND c_stredisk=cstredisk AND (rok*12+mesiac)=tenmesiac;
DELETE FROM food600.archivdoklady WHERE c_data=cdata AND c_stredisk=cstredisk AND (rok*12+mesiac)<oldmesiac;
DELETE FROM food600.archivobraty WHERE c_data=cdata AND c_stredisk=cstredisk AND (rok*12+mesiac)<oldmesiac;
DELETE FROM food600.archivobraty WHERE c_data=cdata AND c_stredisk=cstredisk AND (rok*12+mesiac)=tenmesiac;
INSERT INTO food600.archivdoklady (mesiac, rok,c_stredisk, c_dokl,c_partner, doklad, datum_dokl,operace, pz1, pz2, platba, trzba1, splatnost, sleva_abs, sleva_proc, cen_hlad, zaloha, halere, provedl, uctsuma, c_mena, kdy, c_data, typ_pohybu) SELECT mmesiac as mesiac, mrok as rok,c_stredisk, c_dokl,c_partner, doklad, datum_dokl,operace, pz1, pz2, platba, trzba1, splatnost, sleva_abs, sleva_proc, cen_hlad, zaloha, halere, provedl, uctsuma, c_mena, kdy, c_data,typ_pohybu FROM food600.doklady WHERE c_data=cdata AND c_stredisk=cstredisk;
INSERT INTO food600.archivobraty (mesiac, rok, c_stredisk, operace, c_dokl, c_karty, mnozstvi, cena, cena_part, zustatek, cena_prum, dan, serial_no, poradi, c_data) SELECT mmesiac as mesiac, mrok as rok,c_stredisk, operace, c_dokl, c_karty, mnozstvi, cena, cena_part, zustatek, cena_prum, dan, serial_no, poradi, c_data FROM food600.obraty WHERE c_data=cdata AND c_stredisk=cstredisk;
PERFORM food600.gen_stav(cstredisk,ku_dokladu,cmena,meno, cdata);
INSERT INTO food600.archivsklad (c_karty, c_stredisk, zustatek, cena_prum, c_mena, c_data, mesiac, rok) SELECT c_karty, c_stredisk, zustatek, cena_prum, c_mena, c_data, mmesiac as mesiac, mrok as rok FROM food600.genstav WHERE c_data=cdata AND menostlp=meno;
DELETE FROM food600.genstav WHERE c_data=cdata AND menostlp=meno;
RETURN 1;
END
$BODY$;
