2017-02-01 8 views
1

トランザクションデータをサードパーティのAPIから取得し、定期的(月に1回)にレコードを保存する必要があります。ここに例があります:前回から無期限にレコードを作成

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

この方法では、同じトランザクションを2回保存することについて心配する必要はありません。D –

関連する問題