Skip to content

Commit

Permalink
Allow transfers based on transactions in different currencies (maybe-…
Browse files Browse the repository at this point in the history
…finance#903)

* Allow transfers between transactions in different currencies

* Review fixes
  • Loading branch information
jakubkottnauer authored Jun 21, 2024
1 parent 12380dc commit 3cae528
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
7 changes: 6 additions & 1 deletion app/models/account/transfer.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
class Account::Transfer < ApplicationRecord
has_many :transactions, dependent: :nullify

validate :transaction_count, :from_different_accounts, :net_zero_flows, :all_transactions_marked
validate :net_zero_flows, if: :single_currency_transfer?
validate :transaction_count, :from_different_accounts, :all_transactions_marked

def inflow_transaction
transactions.find { |t| t.inflow? }
Expand Down Expand Up @@ -32,6 +33,10 @@ def build_from_accounts(from_account, to_account, date:, amount:, currency:, nam

private

def single_currency_transfer?
transactions.map(&:currency).uniq.size == 1
end

def transaction_count
unless transactions.size == 2
errors.add :transactions, "must have exactly 2 transactions"
Expand Down
9 changes: 8 additions & 1 deletion test/models/account/transfer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,18 @@ class Account::TransferTest < ActiveSupport::TestCase
end
end

test "transfer transactions must net to zero" do
test "single-currency transfer transactions must net to zero" do
@outflow.update! amount: 105

assert_raises ActiveRecord::RecordInvalid do
Account::Transfer.create! transactions: [ @inflow, @outflow ]
end
end

test "multi-currency transfer transactions do not have to net to zero" do
@outflow.update! amount: 105, currency: "EUR"
transfer = Account::Transfer.create! transactions: [ @inflow, @outflow ]

assert transfer.valid?
end
end

0 comments on commit 3cae528

Please sign in to comment.