SET TERM ^ ;

CREATE OR ALTER TRIGGER TTBCONCILIACAO_CARTAO_B03I FOR TBCONCILIACAO_CARTAO
ACTIVE BEFORE INSERT OR UPDATE POSITION 3
AS
DECLARE VARIABLE BANDEIRA_ID              INTEGER;
DECLARE VARIABLE TAXA_BANDEIRA_IMPORTACAO INTEGER;
DECLARE VARIABLE DUPLICIDADE_ENCONTRADA   INTEGER;
DECLARE VARIABLE PERCENTUAL_TAXA_BANDEIRA NUMERIC(15,4);
DECLARE VARIABLE VALOR_TAXA_BANDEIRA      NUMERIC(15,4);
BEGIN
  IF(COALESCE(NEW.BANDEIRA_DESCRICAO, '') <> '' AND COALESCE(NEW.BANDEIRA, 0) = 0) THEN
  BEGIN
        
        :BANDEIRA_ID = COALESCE((SELECT FIRST 1 T.ID FROM TBCARTAO_BANDEIRA T WHERE UPPER(T.DESCRICAO) LIKE SUBSTRING(UPPER(NEW.BANDEIRA_DESCRICAO) FROM 1 FOR 4)||'%'), 0);

        NEW.BANDEIRA = :BANDEIRA_ID;

  END

  :TAXA_BANDEIRA_IMPORTACAO = COALESCE((SELECT FIRST 1 ADQ.TAXA_BANDEIRA_IMPORTACAO FROM TBPDV_ADQUIRENTE ADQ WHERE ADQ.ADQUIRENTE_ID = NEW.ADQUIRENTE_ID),0);
  IF(:TAXA_BANDEIRA_IMPORTACAO = 1)THEN
  BEGIN
      :PERCENTUAL_TAXA_BANDEIRA = COALESCE((SELECT FIRST 1 PERC.TAXA FROM TBPDV_ADQUIRENTE_TAXA PERC
                                    WHERE PERC.ADQUIRENTE_ID = COALESCE((SELECT FIRST 1 ADQ.ID FROM TBPDV_ADQUIRENTE ADQ WHERE ADQ.STATUS = 1 AND ADQ.ADQUIRENTE_ID = NEW.ADQUIRENTE_ID),0)
                                      AND PERC.BANDEIRA_ID   = NEW.BANDEIRA
                                      AND PERC.PARCELAS      = NEW.PARCELAS
                                      AND NEW.DATA_VENDA BETWEEN PERC.DATA_INICIAL AND PERC.DATA_FINAL),0.00);

      NEW.DESCONTO1 = CAST(CAST(NEW.VALOR AS DOUBLE PRECISION)*(CAST(:PERCENTUAL_TAXA_BANDEIRA AS DOUBLE PRECISION)/100.00) AS DOUBLE PRECISION);
      NEW.DESCONTO1 = CAST(NEW.DESCONTO1 AS NUMERIC(15,2));
      --NEW.TARIFA_ORIGINAL = NEW.DESCONTO1;
      IF(INSERTING)THEN
      BEGIN
        NEW.TARIFA_ORIGINAL = NEW.DESCONTO1;
      END
  END

  IF(POSITION('*' IN TRIM(NEW.CODIGO_AUTORIZACAO)) = 0)THEN
  BEGIN
     :DUPLICIDADE_ENCONTRADA = COALESCE((SELECT FIRST 1 A.ID FROM TBCONCILIACAO_CARTAO A
                                    WHERE A.CODIGO_AUTORIZACAO  = NEW.CODIGO_AUTORIZACAO
                                      AND A.DATA_VENDA          = NEW.DATA_VENDA
                                      AND A.ADQUIRENTE_ID       = NEW.ADQUIRENTE_ID
                                      AND A.ID                 <> NEW.ID),0);
     IF(:DUPLICIDADE_ENCONTRADA > 0)THEN
     BEGIN
         NEW.CODIGO_AUTORIZACAO = '*'||TRIM(NEW.CODIGO_AUTORIZACAO);
     END
  END
END^

SET TERM ; ^ 