class Twobook::Corrections::SimulatedDifferenceAdjustment

Public Class Methods

simulate_correction(events, accounts) click to toggle source
# File lib/twobook/corrections.rb, line 102
def self.simulate_correction(events, accounts)
  deserialized_events = events.map { |e| Serialization.deserialize_event(e) }
  deserialized_accounts = accounts.map { |a| Serialization.deserialize_account(a) }
  Twobook.simulate(deserialized_events, deserialized_accounts)
end

Public Instance Methods

accounts(corrected_events:, account_snapshots:) click to toggle source
# File lib/twobook/corrections.rb, line 81
def accounts(corrected_events:, account_snapshots:)
  corrected_accounts = self.class.simulate_correction(corrected_events, account_snapshots)

  requirements = corrected_accounts.map do |account|
    query = AccountQuery.where(
      category: account.class.category,
      **account.data.slice(*account.class.name_includes),
    )
    existing(query)
  end

  labelled_requirements = (0...requirements.count).map do |n|
    "requirement_#{n}_account".to_sym
  end.zip(requirements).to_h

  {
    buffer_account: one(where(category: 'twobook/corrections/correction_buffer')),
    **labelled_requirements,
  }
end
adjust_original_account_balance(original, correct) click to toggle source
# File lib/twobook/corrections.rb, line 60
def adjust_original_account_balance(original, correct)
  correct_balance = correct.balance || Twobook.wrap_number(0)
  original_balance = original.balance || Twobook.wrap_number(0)
  diff = correct_balance - original_balance
  return if diff.zero?

  if original.class.account_type == :records
    record original, amount: diff
  else
    diff *= -1 if %i(revenue liabilities).include?(original.class.account_type)
    book diff, cr: buffer_account, dr: original if diff.positive?
    book (-1 * diff), cr: original, dr: buffer_account if diff.negative?
  end
end
adjust_original_account_data(original, correct) click to toggle source
# File lib/twobook/corrections.rb, line 75
def adjust_original_account_data(original, correct)
  diff = correct.data.to_a - original.data.to_a
  return if diff.empty?
  original << entry(0, data: diff.to_h)
end
handle(account_snapshots:, corrected_events:) click to toggle source
# File lib/twobook/corrections.rb, line 50
def handle(account_snapshots:, corrected_events:)
  correct_accounts = self.class.simulate_correction(corrected_events, account_snapshots)

  correct_accounts.each do |correct|
    original = where(name: correct.name).on(@accounts_in_process).first
    adjust_original_account_balance(original, correct)
    adjust_original_account_data(original, correct)
  end
end