-- GENERATOR
ALTER SEQUENCE GTBCONTA_RECEBER_COBRANCA RESTART WITH 122 INCREMENT BY 1;

-- TRIGGERS 
-- INSERTS
CREATE OR ALTER trigger ttbconta_receber_cobranca_b01i for tbconta_receber_cobranca
active before insert position 0
AS
BEGIN
  IF(NEW.CODIGO IS NULL) THEN
    NEW.CODIGO = GEN_ID(GTBCONTA_RECEBER_COBRANCA,1);
END;

CREATE trigger tbconta_receber_cobranca_b02i for tbconta_receber_cobranca
active before insert position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

  HISTORICO = '';

  IF(NEW.CODIGO > 0) THEN
  BEGIN
    HISTORICO = HISTORICO||'Reg.incluido';
  END

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

-- UPDATES
CREATE OR ALTER trigger ttbconta_receber_cobranca_b01u for tbconta_receber_cobranca
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.descricao <> NEW.descricao) THEN
    BEGIN
        HISTORICO = HISTORICO||'Descricao:'|| OLD.descricao||'->'||NEW.descricao;
    END
    
    IF ( OLD.STATUSEXCLUSAO <> NEW.STATUSEXCLUSAO and new.STATUSEXCLUSAO = 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro excluido.';
    END
    
    IF ( OLD.STATUSEXCLUSAO <> NEW.STATUSEXCLUSAO and new.STATUSEXCLUSAO = 1) THEN
    BEGIN
        HISTORICO = HISTORICO||'Exclusao desfeita.';
    END

    IF ( OLD.STATUS <> NEW.STATUS) THEN
    BEGIN
         HISTORICO = HISTORICO||'Sts.'|| OLD.STATUS||'->'||NEW.STATUS;
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBCONTA_RECEBER_COBRANCA',NEW.codigo, HISTORICO);
    END
end