2017-02-01 50 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 –