CREATE OR ALTER trigger ttbapi_app_perfil_b02i for tbapi_app_perfil
active before insert position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( NEW.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' PERFIL INCLUIDO: '||NEW.PERFIL||' - '||(SELECT FIRST 1 P.DESCRICAO FROM TBPERFIL P WHERE P.ID = NEW.PERFIL AND P.TABELA = 'PED');
    END

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


CREATE OR ALTER trigger ttbapi_app_perfil_b01u for tbapi_app_perfil
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF ( NEW.PERFIL <> OLD.PERFIL) THEN
    BEGIN
        HISTORICO = HISTORICO||' PERFIL: '||OLD.PERFIL||' - '||(SELECT FIRST 1 P.DESCRICAO FROM TBPERFIL P WHERE P.ID = OLD.PERFIL and P.TABELA = 'PED')||' -> '
        ||NEW.PERFIL||' - '||(SELECT FIRST 1 P.DESCRICAO FROM TBPERFIL P WHERE P.ID = NEW.PERFIL and P.TABELA = 'PED');
    END

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

    IF (HISTORICO <> '') THEN
    BEGIN
        HISTORICO = ' PERFIL ALTERADO: '||HISTORICO;
        EXECUTE PROCEDURE SPI_HISTORICO('TBAPI_APP_PERFIL',NEW.ID, HISTORICO);
    END
END


CREATE trigger ttbapi_app_perfil_b01d for tbapi_app_perfil
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' PERFIL EXCLUIDO: '||OLD.PERFIL||' - '||(SELECT FIRST 1 P.DESCRICAO FROM TBPERFIL P WHERE P.ID = OLD.PERFIL AND P.TABELA = 'PED');
    END

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



