2017-02-01 52 views
1

我需要从第三方API获取交易数据,并定期(每月一次)保存记录。这里是一个例子:上次创建记录

class BalanceTransaction::Update 
    include Service 

    attr_reader :offset, :transactions 

    def initialize(offset) 
    @offset = offset 
    @transactions = fetch_transactions 
    end 

    def call 
    ActiveRecord::Base.transaction do 
     transactions.auto_paging_each do |txn| 
     type = txn[:type] 
     source = txn[:source] 
     case type 
      when 'charge', 'adjustment' 
      invoice = find_invoice(source) 
      ac_id = invoice.account.id 
      update_attrs(id: invoice.id, account_id: ac_id, type:'invoice', attrs: txn) 
      when 'refund' 
      refund = find_refund(source) 
      ac_id = refund.invoice.account.id 
      update_attrs(id: refund.id, account_id: ac_id, type:'refund', attrs: txn) 
     end 
     end 
    end 
    true 
    end 

    private 

    def find_invoice(source) 
    Invoice.find_by!(stripe_charge_id: source) 
    end 

    def find_refund(source) 
    Refund.find_by!(stripe_refund_id: source) 
    end 

    def update_attrs(id:, account_id:, type:, attrs:) 
    BalanceTransaction.create(
     account_id: account_id, 
     stripe_transaction_id: attrs[:id], 
     gross_amount: attrs[:amount], 
     net_amount: attrs[:net], 
     fee_amount: attrs[:fee], 
     currency: attrs[:currency], 
     transactionable_id: id, 
     transactionable_type: type) 
    end 

    def fetch_transactions 
    external_card_balance.all(limit: offset) 
    rescue *EXTERNAL_CARD_ERRORS => e 
    ExternalCardErrorHandler.new(e).handle 
    end 

    def external_card_balance 
    Stripe::BalanceTransaction 
    end 
end 

我想知道如何从上次批量插入幂。我应该检查created_at并删除它们,如果我发现在偏移量后创建的数据?你能给我一些建议吗?

回答

1

交易是否有唯一的id或可以使其唯一的字段?也许你可以使用validates_uniqueness_of来避免保存已经获取的交易。

+0

您的意思是第三方API?如果是,那就是!感谢您的建议! 'stripe_transaction_id'是唯一的。 – Tosh

+0

这样你就不用担心两次保存相同的事务:D –