-- INSERT tbpdv_conferencia
CREATE trigger tbpdv_conferencia_b02i for tbpdv_conferencia
active before insert position 2
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

  HISTORICO = '';

  IF(NEW.ID > 0) THEN
  BEGIN
    HISTORICO = HISTORICO||'REGISTRO INCLUIDO';
  END

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

-- UPDATE tbpdv_conferencia

CREATE trigger tbpdv_conferencia_b09u for tbpdv_conferencia
active before update position 9
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF(OLD.PDV_ID <> NEW.PDV_ID) THEN
    BEGIN
       HISTORICO = HISTORICO||' PDV:'||OLD.PDV_ID||'->'||NEW.PDV_ID;
    END

    IF(OLD.CLIENTE_ID <> NEW.CLIENTE_ID) THEN
    BEGIN
       HISTORICO = HISTORICO||' CLIENTE:'||OLD.CLIENTE_ID||'->'||NEW.CLIENTE_ID;
    END

    IF(OLD.CLIENTE_CPF <> NEW.CLIENTE_CPF) THEN
    BEGIN
       HISTORICO = HISTORICO||' CLIENTE CPF:'||OLD.CLIENTE_CPF||'->'||NEW.CLIENTE_CPF;
    END

    IF(OLD.TABELA_PRECO_ID <> NEW.TABELA_PRECO_ID) THEN
    BEGIN
       HISTORICO = HISTORICO||' TABELA PRECO:'||OLD.TABELA_PRECO_ID||'->'||NEW.TABELA_PRECO_ID;
    END

    IF(OLD.OBSERVACAO <> NEW.OBSERVACAO) THEN
    BEGIN
       HISTORICO = HISTORICO||' OBS.'||OLD.OBSERVACAO||'->'||NEW.OBSERVACAO;
    END


    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPDV_CONFERENCIA',NEW.ID,FN_ELIPSES(HISTORICO,500));
    END
END;
 
-- DELETE tbpdv_conferencia


CREATE trigger tbpdv_conferencia_b09d for tbpdv_conferencia
active before delete position 9
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

  HISTORICO = '';

  IF(OLD.ID > 0) THEN
  BEGIN
    HISTORICO = HISTORICO||'REGISTRO EXCLUIDO';
  END

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

-- UPDATE tbpdv_conferencia_item

CREATE trigger tbpdv_conferencia_item_b09d for tbpdv_conferencia_item
active before delete position 9
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

  HISTORICO = '';

  IF(OLD.ID > 0) THEN
  BEGIN
    HISTORICO = HISTORICO||'ITEM '||OLD.SEQUENCIA||' EXCLUIDO';
  END

  IF(HISTORICO <> '') THEN
  BEGIN
    EXECUTE PROCEDURE SPI_HISTORICO('TBPDV_CONFERENCIA', OLD.PDV_CONFERENCIA_ID, HISTORICO);
  END
END;

-- DELETE tbpdv_conferencia_item 
CREATE trigger tbpdv_conferencia_item_b01d for 	
active before delete position 1
AS
BEGIN

  IF(OLD.ID > 0) THEN
  BEGIN
    -- VALIDACAO PARA STATUS DA CONFERENCIA
    IF(OLD.SITUACAO = 1) THEN
    BEGIN
         EXCEPTION "..." 'CONFERENCIA JA VINCULADA EM UM CUPOM FISCAL. EXCLUSÃO CANCELADA.';

    END

  END
END;
