SET TERM ^ ;

ALTER TABLE TBCONCILIACAO_CARTAO_PARCELAS ADD DATA_EXPIRACAO_ORIGINAL DATE^

CREATE OR ALTER TRIGGER TBCONCILIACAO_CARTAO_PAR_B02IU FOR TBCONCILIACAO_CARTAO_PARCELAS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
  IF(INSERTING)THEN
  BEGIN
     NEW.DATA_EXPIRACAO_ORIGINAL = NEW.DATA_EXPIRACAO;
  END

  IF(UPDATING AND NEW.DATA_EXPIRACAO_ORIGINAL IS NULL AND NEW.DATA_EXPIRACAO IS DISTINCT FROM OLD.DATA_EXPIRACAO)THEN
  BEGIN
     NEW.DATA_EXPIRACAO_ORIGINAL = OLD.DATA_EXPIRACAO;
  END
END^

CREATE OR ALTER TRIGGER TTBCONCIL_CARTAO_PARCELAS_B01U FOR TBCONCILIACAO_CARTAO_PARCELAS
ACTIVE BEFORE UPDATE POSITION 3
AS
DECLARE VARIABLE ID_VENDA INTEGER;
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

  HISTORICO = '';

  ID_VENDA = COALESCE((SELECT FIRST 1 XT.ID FROM TBCONCILIACAO_CARTAO XT
                                WHERE XT.NSU = NEW.NSU AND XT.ADQUIRENTE_ID = NEW.ADQUIRENTE_ID
                                AND XT.DATA_VENDA    = NEW.DATA_VENDA AND XT.MERCHANT_ID   = NEW.MERCHANT_ID),0);

  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(COALESCE(NEW.VALOR_LIQUIDO,0.0000) <> COALESCE(OLD.VALOR_LIQUIDO,0.0000))THEN
  BEGIN
     :HISTORICO = :HISTORICO||', VALOR LIQ: '||COALESCE(OLD.VALOR_LIQUIDO,0.0000)||'->'||COALESCE(NEW.VALOR_LIQUIDO,0.0000);
  END  

  IF(NEW.DATA_EXPIRACAO IS DISTINCT FROM OLD.DATA_EXPIRACAO)THEN
  BEGIN
     :HISTORICO = :HISTORICO||', DT.VENC: '||COALESCE(FN_DATE(OLD.DATA_EXPIRACAO,'DD/MM/YYYY'),'')||'->'||COALESCE(FN_DATE(NEW.DATA_EXPIRACAO,'DD/MM/YYYY'),'');
  END

  --EXCEPTION "..." 'ID DA VENDA'||ID_VENDA;

  IF(:HISTORICO <> '' AND ID_VENDA > 0)THEN
  BEGIN
     HISTORICO = ' PARC.'||FN_LPAD(NEW.NUMERO_PARCELA, 3,0)||', VALOR:'||COALESCE(OLD.VALOR,0.0000)||' ALTERADA:'||:HISTORICO;
     --EXCEPTION "..." 'HISTORICO: '||HISTORICO;
     EXECUTE PROCEDURE SPI_HISTORICO('TBCONCILIACAO_CARTAO',:ID_VENDA,FN_ELIPSES(:HISTORICO,500));
  END
END
^

SET TERM ; ^

