CREATE OR ALTER TRIGGER TTBNF_LOTE_B05U FOR TBNF_LOTE
ACTIVE BEFORE UPDATE POSITION 5
AS

DECLARE VARIABLE GC_WEB INTEGER;

BEGIN

    IF((OLD.XML = '05' AND NEW.XML = '09') OR (OLD.XML = '07' AND NEW.XML = '08')) THEN
    BEGIN

       IF(NEW.NFS_CONTROLE > 0 ) THEN
       BEGIN
            GC_WEB = (SELECT T.GC_WEB FROM TBNFS T WHERE T.CONTROLE = NEW.NFS_CONTROLE);

            IF(GC_WEB = 1) THEN
            BEGIN
                UPDATE TBNFS_ITEM T SET T.NF_SITUACAO = 3 WHERE T.NFS_CONTROLE = NEW.NFS_CONTROLE;

                UPDATE TBNFS_PARCELAMENTO T SET T.NF_SITUACAO = 3 WHERE T.NFS_CONTROLE = NEW.NFS_CONTROLE;
            END
       END ELSE
       IF(NEW.NFE_CONTROLE > 0) THEN
       BEGIN
            GC_WEB = (SELECT T.GC_WEB FROM TBNFE T WHERE T.CONTROLE = NEW.NFE_CONTROLE);

            IF(GC_WEB = 1) THEN
            BEGIN
                UPDATE TBNFE_ITEM T SET T.NF_SITUACAO = 3 WHERE T.NFE_CONTROLE = NEW.NFS_CONTROLE;
    
                UPDATE TBNFE_PARCELAMENTO T SET T.NF_SITUACAO = 3 WHERE T.NFE_CONTROLE = NEW.NFS_CONTROLE;
            END
       END
    END

END;

COMMENT ON TRIGGER TTBNF_LOTE_B05U IS 'ATUALIZAÇÃO DE ITEM E PARCELAS PARA XML CANCELADO OU DENEGADO';