-- TRIGGERS 
-- INSERTS
CREATE trigger tbconta_receber_posicao_b01i for tbconta_receber_posicao
active before insert position 0
AS
BEGIN
  IF(NEW.CODIGO IS NULL) THEN
    NEW.CODIGO = GEN_ID(GTBCONTA_RECEBER_POSICAO,1);
END;

CREATE OR ALTER trigger ttbconta_receber_pos_b02i for tbconta_receber_posicao
active before insert position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    HISTORICO = HISTORICO||' Reg. Incluido';


    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBCONTA_RECEBER_POSICAO',NEW.CODIGO, HISTORICO);
    END
end;

-- UPDATES

CREATE OR ALTER trigger ttbconta_receber_pos_b01u for tbconta_receber_posicao
active before update position 0
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.status <> NEW.status) THEN
    BEGIN
        HISTORICO = HISTORICO||'Status:'|| OLD.status||'->'||NEW.status;
    END
    
    IF ( OLD.STATUSEXCLUSAO <> NEW.STATUSEXCLUSAO and new.STATUSEXCLUSAO = 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Reg. excluido.';
    END
    
    IF ( OLD.STATUSEXCLUSAO <> NEW.STATUSEXCLUSAO and new.STATUSEXCLUSAO = 1) THEN
    BEGIN
        HISTORICO = HISTORICO||'Exc. desfeita.';
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBCONTA_RECEBER_POSICAO', NEW.CODIGO, HISTORICO);
    END
end;
