SET TERM ^ ;

CREATE OR ALTER trigger ttbpdv_cfe_b04iu for tbpdv_cfe
active before insert or update position 4
AS
DECLARE VARIABLE QTD_DIAS_SAIDA INTEGER;
DECLARE VARIABLE CHECK_DATA_SAIDA INTEGER;
DECLARE VARIABLE ESTAB_UF VARCHAR(2);
BEGIN

    :CHECK_DATA_SAIDA = 0;
    IF(INSERTING) THEN
    BEGIN
        :CHECK_DATA_SAIDA = 1;

    END ELSE IF(OLD.DATA_EMISSAO IS DISTINCT FROM NEW.DATA_EMISSAO) THEN
    BEGIN
        :CHECK_DATA_SAIDA = 1;
    END

    IF(:CHECK_DATA_SAIDA = 1) THEN
    BEGIN
        :QTD_DIAS_SAIDA = CAST(FN_PARAMETRO('SISTEMA.DIAS_DATA_SAIDA') AS INTEGER);

        IF(:QTD_DIAS_SAIDA > 0) THEN
        BEGIN
            :ESTAB_UF = COALESCE((SELECT FIRST 1 T.UF FROM TBESTABELECIMENTO T WHERE T.CODIGO = NEW.ESTABELECIMENTO_ID), '');

            IF(:ESTAB_UF <> '' AND TRIM(:ESTAB_UF) <> TRIM(NEW.CLIENTE_UF) AND TRIM(NEW.CLIENTE_IE) = '') THEN
            BEGIN
                NEW.DATA_SAIDA  = FN_DIA_UTIL(DATEADD(DAY, :QTD_DIAS_SAIDA, NEW.DATA_EMISSAO));
            END ELSE
            BEGIN
                NEW.DATA_SAIDA = NEW.DATA_EMISSAO;
            END
            

        END ELSE
        BEGIN
            NEW.DATA_SAIDA = NEW.DATA_EMISSAO;
        END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER trigger ttbnfs_b04iu for tbnfs
active before insert or update position 4
AS
DECLARE VARIABLE QTD_DIAS_SAIDA INTEGER;
DECLARE VARIABLE CHECK_DATA_SAIDA INTEGER;
DECLARE VARIABLE ESTAB_UF VARCHAR(2);
BEGIN
    :CHECK_DATA_SAIDA = 0;
    IF(INSERTING) THEN
    BEGIN
        :CHECK_DATA_SAIDA = 1;

    END ELSE IF(OLD.DATA_EMISSAO IS DISTINCT FROM NEW.DATA_EMISSAO) THEN
    BEGIN
        :CHECK_DATA_SAIDA = 1;
    END

    IF(:CHECK_DATA_SAIDA = 1) THEN
    BEGIN
        :QTD_DIAS_SAIDA = CAST(FN_PARAMETRO('SISTEMA.DIAS_DATA_SAIDA') AS INTEGER);

        IF(:QTD_DIAS_SAIDA > 0) THEN
        BEGIN
            :ESTAB_UF = COALESCE((SELECT FIRST 1 T.UF FROM TBESTABELECIMENTO T WHERE T.CODIGO = NEW.ESTABELECIMENTO_CODIGO), '');

            IF(:ESTAB_UF <> '' AND TRIM(:ESTAB_UF) <> TRIM(NEW.EMPRESA_UF) AND TRIM(NEW.EMPRESA_IE) = '') THEN
            BEGIN
                NEW.DATA_SAIDA  = FN_DIA_UTIL(DATEADD(DAY, :QTD_DIAS_SAIDA, NEW.DATA_EMISSAO));
            END ELSE
            BEGIN
                NEW.DATA_SAIDA = NEW.DATA_EMISSAO;
            END
        END ELSE
        BEGIN
            NEW.DATA_SAIDA = NEW.DATA_EMISSAO;
        END
    END

END
^

SET TERM ; ^

