SET TERM ^ ;

CREATE OR ALTER TRIGGER TTBCONCILIACAO_CARTAO_B01U FOR TBCONCILIACAO_CARTAO
ACTIVE BEFORE UPDATE POSITION 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

  HISTORICO = '';

  IF(NEW.CODIGO_AUTORIZACAO = '0' OR NEW.CODIGO_AUTORIZACAO IS NULL) THEN
  BEGIN
     NEW.CODIGO_AUTORIZACAO = NEW.NSU;
  END

  IF(NEW.CONCILIACAO = 1 AND NEW.CONCILIACAO <> OLD.CONCILIACAO)THEN
  BEGIN
     UPDATE TBCONCILIACAO_CARTAO_PARCELAS B
       SET B.CONCILIACAO = 1
     WHERE B.NSU         = NEW.NSU
     AND B.ADQUIRENTE_ID = NEW.ADQUIRENTE_ID
     AND B.MERCHANT_ID   = NEW.MERCHANT_ID
     AND B.DATA_VENDA    = NEW.DATA_VENDA;
  END

  IF(NEW.CONCILIACAO = 0 AND NEW.CONCILIACAO <> OLD.CONCILIACAO)THEN
  BEGIN
     UPDATE TBCONCILIACAO_CARTAO_PARCELAS B
       SET B.CONCILIACAO = 0
     WHERE B.NSU         = NEW.NSU
     AND B.ADQUIRENTE_ID = NEW.ADQUIRENTE_ID
     AND B.MERCHANT_ID   = NEW.MERCHANT_ID
     AND B.DATA_VENDA    = NEW.DATA_VENDA;
  END

  IF(COALESCE(NEW.TIPO,'') <> COALESCE(OLD.TIPO,''))THEN
  BEGIN
     IF(NEW.TIPO = 'CREDIT')THEN
     BEGIN
        :HISTORICO = :HISTORICO||' NATUREZA: DEBITO -> CREDITO';
     END
     IF(NEW.TIPO = 'DEBIT')THEN
     BEGIN
        :HISTORICO = :HISTORICO||' NATUREZA: CREDITO -> DEBITO';
     END

  END

  IF(COALESCE(NEW.PROTOCOLO_CANCELAMENTO,'') <> COALESCE(OLD.PROTOCOLO_CANCELAMENTO,''))THEN
  BEGIN
     :HISTORICO = :HISTORICO||' PROTOCOLO: '||COALESCE(OLD.PROTOCOLO_CANCELAMENTO,'')||'->'||COALESCE(NEW.PROTOCOLO_CANCELAMENTO,'');
  END

  IF(COALESCE(NEW.MOTIVO_ALTERACAO,'') <> COALESCE(OLD.MOTIVO_ALTERACAO,''))THEN
  BEGIN
     :HISTORICO = :HISTORICO||', MOTIVO: '||COALESCE(OLD.MOTIVO_ALTERACAO,'')||'->'||COALESCE(NEW.MOTIVO_ALTERACAO,'');
  END

  
  IF(COALESCE(NEW.VALOR,0.0000) <> COALESCE(OLD.VALOR,0.0000))THEN
  BEGIN
     :HISTORICO = :HISTORICO||', VALOR: '||COALESCE(OLD.VALOR,0.0000)||'->'||COALESCE(NEW.VALOR,0.0000);
  END

  IF(COALESCE(NEW.DESCONTO1,0.0000) <> COALESCE(OLD.DESCONTO1,0.0000))THEN
  BEGIN
     :HISTORICO = :HISTORICO||', TARIFA: '||COALESCE(OLD.DESCONTO1,0.0000)||'->'||COALESCE(NEW.DESCONTO1,0.0000);
  END

  IF(:HISTORICO <> '')THEN
  BEGIN
     HISTORICO = ' VENDA '||FN_LPAD(NEW.ID, 4,0)||',DT:'||FN_DATE(NEW.DATA_VENDA,'DD/MM/YYYY')||' ALTERADA:'||:HISTORICO;
     EXECUTE PROCEDURE SPI_HISTORICO('TBCONCILIACAO_CARTAO',NEW.ID,FN_ELIPSES(:HISTORICO,500));
  END

END
^

SET TERM ; ^

