CREATE TRIGGER TTBAPURACAOENC_B02I FOR TBAPURACAOENC
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable CODIGO varchar(10);
begin
CODIGO = '';
    if(new.CODTIPO <> '') then
    begin
        CODIGO = coalesce((SELECT FIRST 1 A.CODTIPO from TBAPURACAOENC a where a.CODTIPO = new.CODTIPO),'');
    end

    if(CODIGO <> '') then
    begin
       exception "..." 'TIPO/SUB-TIPO '||CODIGO||' JÁ CADASTRADO';
    end
end;

CREATE TRIGGER TTBAPURACAOENC_B03I FOR TBAPURACAOENC
ACTIVE BEFORE INSERT POSITION 5
AS
begin
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBAPURACAOENC,1);
end;

CREATE TRIGGER TTBAPURACAOENC_B04I FOR TBAPURACAOENC
ACTIVE BEFORE INSERT POSITION 9
AS
declare variable historico varchar(500);
BEGIN
  historico = '';
  IF(NEW.ID > 0) then
  BEGIN
    historico = historico||' Reg.Incluido';
  END

  IF(HISTORICO <> '') then
  BEGIN
    execute procedure spi_historico('TBAPURACAOENC',NEW.ID,historico);
  END
END;

CREATE TRIGGER TTBAPURACAOENC_B02U FOR TBAPURACAOENC
ACTIVE BEFORE UPDATE POSITION 9
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';
    IF(OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' Desc:'||OLD.DESCRICAO||' -> '||NEW.DESCRICAO;
    END

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

    IF(OLD.CODTIPO <> NEW.CODTIPO)THEN
    BEGIN
        HISTORICO = HISTORICO||' Tipo:'||OLD.CODTIPO||' -> '||NEW.CODTIPO;
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBAPURACAOENC',NEW.ID,FN_ELIPSES(HISTORICO,500));
    END
END;

CREATE TRIGGER TTBAPURACAOENC_B02D FOR TBAPURACAOENC
ACTIVE BEFORE DELETE POSITION 9
AS
declare variable historico varchar(500);
BEGIN
  historico = '';
  IF(OLD.ID > 0) then
  BEGIN
    historico = historico||' Reg.Excluido';
  END

  IF(HISTORICO <> '') then
  BEGIN
    execute procedure spi_historico('TBAPURACAOENC',OLD.ID,historico);
  END
END;



