CREATE OR ALTER TRIGGER TBNFS_EMBARQUE_B01I FOR TBNFS_EMBARQUE
ACTIVE BEFORE INSERT POSITION 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);

BEGIN
    HISTORICO = '';

    IF ( NEW.NFS_CONTROLE > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' REGISTRO DE EMBARQUE INCLUIDO: '||FN_DATE(NEW.DATA_SAIDA, 'DD/MM/YYYY');
    END

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

END;

CREATE OR ALTER TRIGGER TBNFS_EMBARQUE_B02I FOR TBNFS_EMBARQUE
ACTIVE BEFORE INSERT POSITION 2
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);

BEGIN
    HISTORICO = '';

    IF ( NEW.DATA_ENTREGA IS NOT NULL) THEN
    BEGIN
        HISTORICO = HISTORICO||' ENTREGA REGISTRADA : '||FN_DATE(NEW.DATA_ENTREGA, 'DD/MM/YYYY');
    END

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

END;


CREATE OR ALTER TRIGGER TBNFS_EMBARQUE_B01D FOR TBNFS_EMBARQUE
ACTIVE BEFORE DELETE POSITION 0
AS

DECLARE VARIABLE HISTORICO VARCHAR(500);

BEGIN
    HISTORICO = '';

    IF ( OLD.NFS_CONTROLE > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' REGISTRO DE EMBARQUE EXCLUIDO';
    END

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

END;

CREATE OR ALTER TRIGGER TBNFS_EMBARQUE_B01U FOR TBNFS_EMBARQUE
ACTIVE BEFORE UPDATE POSITION 1
AS

DECLARE VARIABLE HISTORICO VARCHAR(5000);

BEGIN
    HISTORICO = '';

    IF(NEW.DATA_SAIDA IS NOT NULL AND OLD.DATA_SAIDA IS NOT NULL AND NEW.DATA_SAIDA <> OLD.DATA_SAIDA) THEN
    BEGIN                  
        HISTORICO = HISTORICO||' DATA DE EMBARQUE: '||FN_DATE(OLD.DATA_SAIDA, 'DD/MM/YYYY')||' -> '||FN_DATE(NEW.DATA_SAIDA, 'DD/MM/YYYY');
    END

    IF(NEW.DATA_ENTREGA IS NOT NULL AND OLD.DATA_ENTREGA IS NOT NULL AND NEW.DATA_ENTREGA <> OLD.DATA_ENTREGA) THEN
    BEGIN                  
        HISTORICO = HISTORICO||' DT.ENTREGA: '||FN_DATE(OLD.DATA_ENTREGA, 'DD/MM/YYYY')||' -> '||FN_DATE(NEW.DATA_ENTREGA, 'DD/MM/YYYY');
    END

    IF(NEW.DATA_ENTREGA IS NOT NULL AND OLD.DATA_ENTREGA IS NULL) THEN
    BEGIN                  
        HISTORICO = HISTORICO||' ENTREGA REGISTRADA: '||FN_DATE(NEW.DATA_ENTREGA, 'DD/MM/YYYY');
    END

    IF(NEW.DATA_ENTREGA IS NULL AND OLD.DATA_ENTREGA IS NOT NULL) THEN
    BEGIN                  
        HISTORICO = HISTORICO||' ENTREGA EXCLUIDA';
    END



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

END;