SET TERM ^ ;

CREATE trigger ttbperfil_cliente_desconto_b02i for tbperfil_cliente_desconto
active before insert position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500); 
DECLARE VARIABLE PERFIL_DESC VARCHAR(100);
DECLARE VARIABLE PDV_DESC VARCHAR(100);
BEGIN

    HISTORICO = '';

    PERFIL_DESC = COALESCE((SELECT FIRST 1 P.DESCRICAO FROM TBPERFIL P WHERE P.ID = NEW.PERFIL), '');
    PDV_DESC    = COALESCE((SELECT FIRST 1 D.DESCRICAO FROM TBPDV D WHERE D.ID = NEW.PDV_ID), '');

    IF ( NEW.CLIENTE_ID > 0 AND NEW.ID > 0 ) THEN
    BEGIN
        IF(NEW.ORIGEM = 1) THEN
        BEGIN
          HISTORICO = HISTORICO||'DESCONTO INCLUIDO: '||FN_LPAD(NEW.ID,4,0)||' - '||PERFIL_DESC||', ORIGEM:'||IIF(NEW.ORIGEM = 1, 'PERFIL', 'PDV')
                      ||', VIGENCIA:'||FORMATDATE(NEW.DATA_INICIAL)||' A '||FORMATDATE(NEW.DATA_FINAL);
        END

    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBEMPRESA',NEW.CLIENTE_ID, HISTORICO);
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE trigger ttbperfil_cliente_desconto_b02d for tbperfil_cliente_desconto
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500); 
DECLARE VARIABLE PERFIL_DESC VARCHAR(100);
DECLARE VARIABLE PDV_DESC VARCHAR(100);
BEGIN

    HISTORICO = '';

    PERFIL_DESC = COALESCE((SELECT FIRST 1 P.DESCRICAO FROM TBPERFIL P WHERE P.ID = old.PERFIL), '');
    PDV_DESC    = COALESCE((SELECT FIRST 1 D.DESCRICAO FROM TBPDV D WHERE D.ID = old.PDV_ID), '');

    IF ( old.CLIENTE_ID > 0 AND old.ID > 0 ) THEN
    BEGIN
        IF(old.ORIGEM = 1) THEN
        BEGIN
          HISTORICO = HISTORICO||'DESCONTO EXCLUIDO: '||FN_LPAD(old.ID,4,0)||' - '||PERFIL_DESC||', ORIGEM:'||IIF(old.ORIGEM = 1, 'PERFIL', 'PDV')
                      ||', VIGENCIA:'||FORMATDATE(old.DATA_INICIAL)||' A '||FORMATDATE(old.DATA_FINAL);
        END

    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBEMPRESA',old.CLIENTE_ID, HISTORICO);
    END
END
^

SET TERM ; ^


