SET TERM ^ ;

CREATE OR ALTER trigger ttbprevisao_venda_b09i for tbprevisao_venda
active before insert position 0
AS
declare variable HISTORICO VARCHAR(500);
begin
    HISTORICO = '';

    IF(NEW.ID > 0) THEN
    BEGIN
        HISTORICO = ' REGISTRO INCLUÍDO';
    END

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

SET TERM ; ^

SET TERM ^ ;

CREATE trigger ttbprevisao_venda_b09d for tbprevisao_venda
active before delete position 0
AS
declare variable HISTORICO VARCHAR(500);
begin
    HISTORICO = '';

    IF(OLD.ID > 0) THEN
    BEGIN
        HISTORICO = ' REGISTRO EXCLUÍDO';
    END

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


^

SET TERM ; ^

SET TERM ^ ;

CREATE trigger ttbprevisao_venda_b09u for tbprevisao_venda
active before update position 0
AS
declare variable HISTORICO VARCHAR(500);
begin
    HISTORICO = '';

    IF(NEW.DESCRICAO IS DISTINCT FROM OLD.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' DESC.: '||OLD.DESCRICAO||' -> '||NEW.DESCRICAO;
    END

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

    IF(NEW.ESTABELECIMENTO_PRODUCAO IS DISTINCT FROM OLD.ESTABELECIMENTO_PRODUCAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' ESTAB.PROD: '||OLD.ESTABELECIMENTO_PRODUCAO||' -> '||NEW.ESTABELECIMENTO_PRODUCAO;
    END

    IF(NEW.ESTABELECIMENTO_VENDA IS DISTINCT FROM OLD.ESTABELECIMENTO_VENDA) THEN
    BEGIN
        HISTORICO = HISTORICO||' ESTAB.VENDA: '||OLD.ESTABELECIMENTO_VENDA||' -> '||NEW.ESTABELECIMENTO_VENDA;
    END

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

SET TERM ; ^

SET TERM ^ ;

CREATE trigger ttbprevisao_venda_b01d for tbprevisao_venda
active before delete position 0
AS
begin
    IF(OLD.ID > 0) THEN
    BEGIN
        DELETE FROM TBPREVISAO_VENDA_ITEM WHERE PREVISAO_VENDA_ID = OLD.ID;
    END
end
^

SET TERM ; ^

