CREATE TRIGGER TTBSAC_RECLAMACAO_B01I FOR TBSAC_RECLAMACAO
ACTIVE BEFORE INSERT POSITION 0
as
begin
  if (new.CODIGO is null) then
    new.CODIGO = gen_id(GTBSAC_RECLAMACAO,1);
end;

CREATE TRIGGER TTBSAC_RECLAMACAO_B02I FOR TBSAC_RECLAMACAO
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

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

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

CREATE TRIGGER TTBSAC_RECLAMACAO_B01U FOR TBSAC_RECLAMACAO
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Descricao: '|| OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END

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

    IF ( OLD.STATUSEXCLUSAO <> NEW.STATUSEXCLUSAO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Status Exclusao: '|| OLD.STATUSEXCLUSAO||'->'||NEW.STATUSEXCLUSAO;
    END

    IF ( OLD.USUARIO_CODIGO <> NEW.USUARIO_CODIGO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Usuario Codigo: '|| OLD.USUARIO_CODIGO||'->'||NEW.USUARIO_CODIGO;
    END

    IF ( OLD.DATA <> NEW.DATA) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Data: '|| OLD.DATA||'->'||NEW.DATA;
    END

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

CREATE TRIGGER TTBSAC_RECLAMACAO_B01D FOR TBSAC_RECLAMACAO
ACTIVE BEFORE DELETE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.CODIGO > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro Excluido: '||old.CODIGO;
    END

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