Skip to content

Commit

Permalink
Fix: PG::UniqueViolation (MAYBE-RAILS-CW)
Browse files Browse the repository at this point in the history
  • Loading branch information
revise-dev[bot] authored Jan 24, 2025
1 parent 7d04ea1 commit c2d174b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion app/models/transfer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def auto_match_for_account(account)
)
").joins("
LEFT JOIN transfers existing_transfers ON (
existing_transfers.inflow_transaction_id = inflow_candidates.entryable_id OR
existing_transfers.inflow_transaction_id = inflow_candidates.entryable_id AND
existing_transfers.outflow_transaction_id = outflow_candidates.entryable_id
)
")
Expand Down
35 changes: 35 additions & 0 deletions test/models/transfer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,41 @@ class TransferTest < ActiveSupport::TestCase
end
end

test "auto_match_for_account does not create duplicate transfers" do
outflow_entry = create_transaction(date: 1.day.ago.to_date, account: accounts(:depository), amount: 500)
inflow_entry = create_transaction(date: Date.current, account: accounts(:credit_card), amount: -500)

# Manually create a transfer between the transactions
Transfer.create!(
inflow_transaction: inflow_entry.account_transaction,
outflow_transaction: outflow_entry.account_transaction,
)

# Assert that no new Transfer record is created
assert_no_difference -> { Transfer.count } do
Transfer.auto_match_for_account(accounts(:depository))
end
end

test "auto_match_for_account handles multiple potential matches" do
# Create multiple transactions that could potentially match
outflow_entry1 = create_transaction(date: 1.day.ago.to_date, account: accounts(:depository), amount: 500)
outflow_entry2 = create_transaction(date: 1.day.ago.to_date, account: accounts(:depository), amount: 500)
inflow_entry1 = create_transaction(date: Date.current, account: accounts(:credit_card), amount: -500)
inflow_entry2 = create_transaction(date: Date.current, account: accounts(:credit_card), amount: -500)

# Create one existing transfer
Transfer.create!(
inflow_transaction: inflow_entry1.account_transaction,
outflow_transaction: outflow_entry1.account_transaction,
)

# Should create only one new transfer, not duplicate existing one
assert_difference -> { Transfer.count } => 1 do
Transfer.auto_match_for_account(accounts(:depository))
end
end

test "transfer has different accounts, opposing amounts, and within 4 days of each other" do
outflow_entry = create_transaction(date: 1.day.ago.to_date, account: accounts(:depository), amount: 500)
inflow_entry = create_transaction(date: Date.current, account: accounts(:credit_card), amount: -500)
Expand Down

0 comments on commit c2d174b

Please sign in to comment.