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 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
      NEW.BANDEIRA           = COALESCE((SELECT FIRST 1 T.ID FROM TBCARTAO_BANDEIRA T WHERE UPPER(T.DESCRICAO) LIKE '%OUTROS%'), 0);
      NEW.BANDEIRA_DESCRICAO = COALESCE((SELECT FIRST 1 T.DESCRICAO FROM TBCARTAO_BANDEIRA T WHERE UPPER(T.DESCRICAO) LIKE '%OUTROS%'), 0);
  END

  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 3)||'%'), 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
END
^

SET TERM ; ^

