SET TERM ^ ;

CREATE OR ALTER trigger ttbemail_b03iu for tbemail
active before insert or update position 3
AS
DECLARE VARIABLE CONFIG_EMAIL_MOD INTEGER;
BEGIN

    IF(INSERTING OR (UPDATING AND NEW.MODULO_EMAIL <> OLD.MODULO_EMAIL)) THEN
    BEGIN
        /* BUSCAR CONFIG DO MODULO DO EMAIL INSERIDO */
        :CONFIG_EMAIL_MOD = COALESCE((SELECT FIRST 1 T.ID FROM TBCONFIGURACAO_EMAIL T WHERE T.MODULO_EMAIL = NEW.MODULO_EMAIL AND T.STATUS = 1 AND NEW.MODULO_EMAIL <> 0), 0);
    
        IF(:CONFIG_EMAIL_MOD = 0) THEN
        BEGIN
            /* CASO NAO ENCONTRAR CONFIG PARA O MODULO, DEFINIR A CONFIG PADRAO PARA OS EMAILS */
            NEW.CONFIGURACAO_EMAIL_ID = COALESCE((SELECT FIRST 1 T.ID FROM TBCONFIGURACAO_EMAIL T WHERE T.MODULO_EMAIL = 0 AND T.STATUS = 1), 0);
            NEW.MODULO_EMAIL = 0;
        END ELSE
        BEGIN
            NEW.CONFIGURACAO_EMAIL_ID = :CONFIG_EMAIL_MOD;
        END
    END

    IF(NEW.DE IS NULL) THEN
    BEGIN
        NEW.DE = COALESCE((SELECT FIRST 1 T.EMAIL_RESPOSTAS FROM TBCONFIGURACAO_EMAIL T WHERE T.ID = NEW.CONFIGURACAO_EMAIL_ID), '');
    END
    
END
^

SET TERM ; ^



COMMENT ON TRIGGER TTBEMAIL_B03IU IS 'ATRIBUIR CONFIGURACAO DO EMAIL POR MODULOS DO SISTEMA';

