ALTER TABLE TBMANIFESTO_LOTE
ADD "MANUAL" INTEGER 
DEFAULT 0;


CREATE TRIGGER TBMANIFESTO_LOTE_B02I FOR TBMANIFESTO_LOTE
ACTIVE BEFORE INSERT POSITION 2
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);

BEGIN
    HISTORICO = '';

    IF ( NEW.ID > 0) THEN
    BEGIN
        IF(NEW."MANUAL" = 0) THEN
        BEGIN
            HISTORICO = HISTORICO||' SEQ. '||NEW.SEQUENCIAL||' INCLUIDO AUTOMATICO.';
        END ELSE
            HISTORICO = HISTORICO||' SEQ. '||NEW.SEQUENCIAL||' INCLUIDO MANUALMENTE.';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBMANIFESTO_NF',NEW.MANIFESTO_ID, HISTORICO);
    END
END;

CREATE OR ALTER TRIGGER TBMANIFESTO_LOTE_B01D FOR TBMANIFESTO_LOTE
ACTIVE BEFORE DELETE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);

BEGIN
    HISTORICO = '';

    IF ( OLD.ID > 0) THEN
    BEGIN
       HISTORICO = HISTORICO||' SEQ. '||OLD.SEQUENCIAL||' EXCLUIDO MANUALMENTE.';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBMANIFESTO_NF',OLD.MANIFESTO_ID, HISTORICO);
    END
END;


CREATE TRIGGER TBMANIFESTO_LOTE_BU0 FOR TBMANIFESTO_LOTE
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    
    HISTORICO = '';

    IF ( OLD.LOTE <> NEW.LOTE) THEN
    BEGIN
        HISTORICO = HISTORICO||' LOTE:'|| OLD.LOTE||'->'||NEW.LOTE;
    END

    IF (OLD.SEQUENCIAL <> NEW.SEQUENCIAL) THEN
    BEGIN
        HISTORICO = HISTORICO||' SEQ.'|| OLD.SEQUENCIAL||'->'||NEW.SEQUENCIAL;
    END

    IF (OLD.PROTOCOLO <> NEW.PROTOCOLO) THEN
    BEGIN
        HISTORICO = HISTORICO||' PROT.'|| OLD.PROTOCOLO||'->'||NEW.PROTOCOLO;
    END

    IF (OLD.TIPO_EVENTO <> NEW.TIPO_EVENTO) THEN
    BEGIN
        HISTORICO = HISTORICO||' EVENTO: '|| OLD.TIPO_EVENTO||'->'||NEW.TIPO_EVENTO;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBMANIFESTO_NF', NEW.MANIFESTO_ID, HISTORICO);
    END
    
END;