Class: F2ynab::YNAB::BulkTransactionCreator

Inherits:
Object
  • Object
show all
Defined in:
lib/f2ynab/ynab/bulk_transaction_creator.rb

Constant Summary collapse

BATCH_SIZE =
100

Instance Method Summary collapse

Constructor Details

#initialize(client, transactions) ⇒ BulkTransactionCreator

Returns a new instance of BulkTransactionCreator.



6
7
8
9
# File 'lib/f2ynab/ynab/bulk_transaction_creator.rb', line 6

def initialize(client, transactions)
  @transactions = transactions
  @client = client
end

Instance Method Details

#createObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/f2ynab/ynab/bulk_transaction_creator.rb', line 11

def create
  if @transactions.size.zero?
    Rails.logger.info(:no_transactions_to_create)
    return false
  end

  created_transactions_ids = []
  batches = (@transactions.size.to_f / BATCH_SIZE).ceil

  Rails.logger.info("Splitting #{@transactions.size} transactions into #{batches} batches")

  @transactions.each_slice(BATCH_SIZE).with_index do |transactions, index|
    Rails.logger.info("Processing batch #{index + 1} of #{batches}")

    transactions_to_create = []
    transactions.each do |transaction|
      transactions_to_create << {
        import_id: transaction[:id].to_s.truncate(36),
        account_id: @client.,
        payee_name: transaction[:payee_name].to_s.truncate(50),
        amount: transaction[:amount],
        memo: transaction[:description],
        date: transaction[:date].to_date,
        cleared: transaction[:cleared] ? 'Cleared' : 'Uncleared',
        flag: transaction[:flag],
      }
    end

    if transactions_to_create.any?
      create_transactions = @client.create_transactions(transactions_to_create)
      Rails.logger.info(create_transactions)
      created_transactions_ids += create_transactions.transaction_ids if create_transactions
    else
      Rails.logger.info(:no_transactions_to_create)
    end
  end
  
  created_transactions_ids
end