-- TBCASO_PAINEL_CONF

SET TERM ^ ;

CREATE OR ALTER TRIGGER TTBCASO_PAINEL_CONF_B02D FOR TBCASO_PAINEL_CONF
ACTIVE BEFORE DELETE POSITION 1
AS
BEGIN
   IF(OLD.ID > 0) THEN
   BEGIN
      DELETE FROM TBCASO_PAINEL_CONF_ITENS I WHERE I.CAMPO_ID = OLD.ID;
      DELETE FROM TBCASO_CAMPO_DEPENDENCIA D WHERE D.CAMPO_ID = OLD.ID;
   END
END
^

SET TERM ; ^

-- TBCASO_CAMPO_DEPENDENCIA

DROP TRIGGER TBCASO_CAMPO_DEPENDENCIA_BI;

SET TERM ^ ;

CREATE OR ALTER TRIGGER TTBCASO_CAMPO_DEPENDENCIA_B01I FOR TBCASO_CAMPO_DEPENDENCIA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBCASO_CAMPO_DEPENDENCIA,1);
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE TRIGGER TTBCASO_CAMPO_DEPENDENCIA_B02I FOR TBCASO_CAMPO_DEPENDENCIA
ACTIVE BEFORE INSERT POSITION 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
DECLARE VARIABLE PAINEL_CONF VARCHAR(500);
BEGIN

    HISTORICO = '';
    PAINEL_CONF = COALESCE((SELECT FIRST 1 FN_LPAD(A.ID,4,0)||' - '||A.DESCRICAO FROM TBCASO_PAINEL_CONF A WHERE A.ID = NEW.CAMPO_ID),'');

    IF(NEW.ID > 0) THEN
    BEGIN
       HISTORICO = HISTORICO||'DEPEND: '||FN_LPAD(NEW.ID,4,0)||', INCLUIDO NO CAMPO: '||PAINEL_CONF;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBCASO_PAINEL', NEW.PAINEL_ID,FN_ELIPSES(:HISTORICO,500));
    END
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE TRIGGER TTBCASO_CAMPO_DEPENDENCIA_B01D FOR TBCASO_CAMPO_DEPENDENCIA
ACTIVE BEFORE DELETE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
DECLARE VARIABLE PAINEL_CONF VARCHAR(500);
BEGIN

    HISTORICO = '';
    PAINEL_CONF = COALESCE((SELECT FIRST 1 FN_LPAD(A.ID,4,0)||' - '||A.DESCRICAO FROM TBCASO_PAINEL_CONF A WHERE A.ID = OLD.CAMPO_ID),'');

    IF(OLD.ID > 0) THEN
    BEGIN
       HISTORICO = HISTORICO||'DEPEND: '||FN_LPAD(OLD.ID,4,0)||', EXCLUIDA NO CAMPO: '||PAINEL_CONF;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBCASO_PAINEL', OLD.PAINEL_ID,FN_ELIPSES(:HISTORICO,500));
    END
END
^

SET TERM ; ^



