CREATE OR REPLACE FUNCTION food600.ulozinventuru_storno(
	cdata integer,
	cstredisk integer,
	cdokl bigint,
	autor character varying,
	mmena_akt integer,
	meno character varying)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE 
AS $BODY$
DECLARE mhalere BIGINT;
c_dokl_kon INTEGER;
c_dokl_medzi INTEGER;
BEGIN
INSERT INTO food600.inv_uloz (c_stredisk, c_karty, mnozstvi, kdy, c_data) SELECT c_stredisk, c_karty, zustatek as mnozstvi, now() as kdy, cdata as c_data FROM food600.obraty WHERE obraty.c_data=cdata AND obraty.c_dokl=c_dokl;
DELETE FROM food600.inventur WHERE c_data=cdata AND c_stredisk=cstredisk  AND inventur.vk<>'V';
INSERT INTO food600.inventur (c_karty, c_stredisk, mnozstvi,c_data) SELECT c_karty, cstredisk as c_stredisk, zustatek as mnozstvi, cdata as c_data FROM food600.obraty WHERE obraty.c_data=cdata AND obraty.c_dokl=cdokl;
DELETE FROM food600.obraty WHERE obraty.c_data=cdata AND obraty.c_dokl=cdokl;
SELECT halere::bigint into mhalere FROM food600.doklady WHERE doklady.c_data=cdata AND doklady.c_dokl=cdokl;
IF mhalere>0 THEN
	DELETE FROM food600.obraty WHERE obraty.c_data=cdata AND obraty.c_dokl=mhalere;
	DELETE FROM food600.doklady WHERE doklady.c_data=cdata AND doklady.c_dokl=mhalere;
END IF;	
UPDATE food600.doklady SET operace='II', pz1='Stornoval '||autor, platba=food600.left(pz2,5), pz2=substring(clock_timestamp()::text,1,15) WHERE doklady.c_data=cdata AND doklady.c_dokl=cdokl;
SELECT MIN(c_dokl) INTO c_dokl_kon FROM food600.doklady WHERE c_stredisk = cstredisk AND c_dokl > cdokl AND operace = 'KK' ;
IF c_dokl_kon IS NOT NULL THEN
	SELECT MIN(c_dokl) INTO c_dokl_medzi FROM food600.doklady WHERE c_stredisk = cstredisk AND c_dokl > cdokl AND c_dokl<c_dokl_kon;
	IF c_dokl_medzi IS NOT NULL THEN
        UPDATE food600.doklady SET operace = 'xx', platba = 'KKsto' WHERE c_dokl = c_dokl_kon;
    END IF; 
END IF; 
IF mhalere>0 THEN
--	PERFORM food600.prepoddokl(mmena_akt,meno,LEAST(cdokl,mhalere),cdata,0);
ELSE
--	PERFORM food600.prepoddokl(mmena_akt,meno,cdokl,cdata,0);
END IF;

END
$BODY$;
