Files
sure/app/models/transfer.rb
T
47c46843e1 fix(transfers): prevent duplicate creation on double-submit (#3342)
* fix(transfers): prevent duplicate creation on double-submit

TransfersController#create -> Transfer::Creator had no protection
against a repeated form submission - a double-click, a browser retry,
or two near-simultaneous requests could each create a separate,
identical transfer (and its 2-4 underlying Entry/Transaction rows).

Adds a per-form idempotency key, the same approach already used for
TransactionsController#create: a UUID hidden field generated fresh on
page load, tagging the outflow/inflow (and fee, with a distinguishing
suffix since a fee leg shares its account with its primary leg) entries
via the existing entries(account_id, source, external_id) partial
unique index. A pre-check handles the sequential double-submit case;
rescue ActiveRecord::RecordNotUnique is the authoritative backstop for
genuine concurrent requests - the whole Transfer.transaction block
rolls back cleanly on conflict, so there's no risk of a half-created
transfer.

A same-day duplicate transfer can be legitimate (unlike a duplicate
valuation, see #3339/PR #3340), so this uses the same per-submission
token approach as #3334/PR #3338 rather than a natural-key DB
constraint.

Fixes #3341.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(transfers): store the idempotency key in its own column, isolate the retry with a savepoint

Same two review findings as PR #3338 (transactions) and #3340
(valuations), applied here since this branch shares the same
mechanism:

- Reusing external_id/source for the web-form idempotency token made
  every leg of a manually-created transfer satisfy Entry#linked?,
  incorrectly making it look provider-synced. Uses the same dedicated
  entries.idempotency_key column added in
  db/migrate/20260902180400_add_idempotency_key_to_entries.rb (cherry-picked
  identically from PR #3338 - this branch depends on that migration;
  please merge #3338 first, or merge this after it lands so the
  duplicate migration file is a no-op).

- Transfer::Creator now wraps the actual save in
  Transfer.transaction(requires_new: true) so a RecordNotUnique only
  rolls back to a savepoint rather than aborting any transaction the
  caller might already be in, keeping the rescue's retry lookup usable
  (mirrors the fix already applied to Account::ReconciliationManager
  in PR #3340).

Added a regression test asserting neither leg of a transfer created
via this path is linked? or has external_id/source set.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(transfers): distinct idempotency key per leg, rebuild invalid index on retry

Two more review findings:

- CodeRabbit: the form doesn't prevent selecting the same account as
  both source and destination. The outflow and inflow legs shared the
  bare idempotency key, so on that same-account path they'd collide
  with each other under the same account-scoped unique index (as
  would both fee legs, which shared a single "-fee" suffix). Every
  leg now gets a distinct, role-specific suffix (outflow stays bare -
  that's what find_existing_transfer looks up by - inflow/source_fee/
  destination_fee each get their own).

- Codex (same finding already fixed once for entries.idempotency_key's
  sibling migration, recurring here since this branch carries an
  identical copy): index_exists? alone doesn't distinguish a valid
  index from an INVALID one left behind by an interrupted CREATE INDEX
  CONCURRENTLY, so a retry after a failed build would short-circuit
  and record the migration as applied while the constraint was still
  missing. Now checks pg_index.indisvalid directly before deciding to
  skip.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(transfers): clear idempotency key on destroy so a retry doesn't 500

Codex flagged that Transfer#destroy! (used by reject!) preserves the
outflow/inflow entries but not the Transfer join row - a retried
create request with the same idempotency_key would find no Transfer
via find_existing_transfer, attempt another insert, hit the stale
entry's unique key, and re-raise RecordNotUnique instead of finding
a match. Clear the key on the surviving entries when a transfer is
destroyed.

Also adds a regression test for the CodeRabbit-flagged per-leg key
collision concern (already fixed by role-specific suffixes in the
prior commit) to lock in that fee legs never share a key with their
primary leg.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(transfers): verify idempotency key matches the request, fix stale doc comment

jjmata review on #3342:
- find_existing_transfer matched on idempotency_key + source_account only,
  so a stale key from a cached form could silently return a different,
  older transfer instead of creating the one actually requested. Now
  verifies destination account, date, and amount before treating a key
  match as the same request; a genuine mismatch surfaces as a new
  StaleIdempotencyKeyError (422 + message) instead of a false success or
  a raw 500.
- Removed a comment claiming parity with a
  TransactionsController#new_transaction_idempotency_key method that
  doesn't exist in the codebase.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(transfers): preserve from_account_id on error, match fees/exchange rate in idempotency check

coderabbitai review on #3342:
- All three create rescue blocks (exchange rate unavailable, invalid date,
  stale idempotency key) failed to set @from_account_id, so the re-rendered
  form lost the user's selected source account.
- matches_request? only compared accounts/date/outflow amount, so a retry
  with the same key but a different exchange_rate or fee would be reported
  as success while silently keeping the old inflow amount and fee entries.
  Now recomputes the request's effective inflow amount and compares derived
  fee totals too; a mismatch raises StaleIdempotencyKeyError like other
  stale-key mismatches instead of silently returning the old transfer.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Gerald <248542187+gfr-free@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-09-04 06:25:34 +02:00

185 lines
5.2 KiB
Ruby

class Transfer < ApplicationRecord
belongs_to :inflow_transaction, class_name: "Transaction"
belongs_to :outflow_transaction, class_name: "Transaction"
has_many :fee_transactions, class_name: "Transaction", dependent: :destroy
attr_accessor :source_fee_amount, :destination_fee_amount, :tag_ids
enum :status, { pending: "pending", confirmed: "confirmed" }
validates :inflow_transaction_id, uniqueness: true
validates :outflow_transaction_id, uniqueness: true
validate :transfer_has_different_accounts
validate :transfer_has_opposite_amounts
validate :transfer_within_date_range
validate :transfer_has_same_family
class << self
def kind_for_account(account)
if account.loan?
"loan_payment"
elsif account.credit_card?
"cc_payment"
elsif account.investment? || account.crypto?
"investment_contribution"
elsif account.liability?
"cc_payment"
else
"funds_movement"
end
end
end
def has_source_fee?
derived_source_fee_amount > 0
end
def has_destination_fee?
derived_destination_fee_amount > 0
end
def has_fees?
has_source_fee? || has_destination_fee?
end
def total_fee
derived_source_fee_amount + derived_destination_fee_amount
end
def derived_source_fee_amount
fee_transactions.joins(:entry).where(entries: { account_id: from_account.id }).sum("entries.amount")
end
def derived_destination_fee_amount
fee_transactions.joins(:entry).where(entries: { account_id: to_account.id }).sum("entries.amount")
end
def amount_abs
inflow_transaction&.entry&.amount_money&.abs || Money.new(0, from_account&.currency || "USD")
end
def name
acc = to_account
if payment?
acc ? "Payment to #{acc.name}" : "Payment"
else
acc ? "Transfer to #{acc.name}" : "Transfer"
end
end
def payment?
to_account&.liability?
end
def loan_payment?
outflow_transaction&.kind == "loan_payment"
end
def liability_payment?
outflow_transaction&.kind == "cc_payment"
end
def regular_transfer?
outflow_transaction&.kind == "funds_movement"
end
def transfer_type
return "loan_payment" if loan_payment?
return "liability_payment" if liability_payment?
"transfer"
end
def categorizable?
to_account&.accountable_type == "Loan"
end
def reject!
Transfer.transaction do
RejectedTransfer.find_or_create_by!(inflow_transaction_id: inflow_transaction_id, outflow_transaction_id: outflow_transaction_id)
destroy!
end
end
def destroy!
Transfer.transaction do
[ inflow_transaction, outflow_transaction ].each do |transaction|
next if transaction.nil?
next unless Transaction.exists?(transaction.id)
begin
transaction.update!(kind: "standard")
# The entry survives this destroy (only the Transfer join row and
# fee transactions go away), but its idempotency_key must not: a
# later retry of the original create request looks up that key,
# finds no Transfer anymore, and would otherwise hit the unique
# index on the stale entry and raise instead of creating a new
# transfer (see Transfer::Creator#find_existing_transfer).
transaction.entry.update!(idempotency_key: nil) if transaction.entry&.idempotency_key.present?
rescue ActiveRecord::RecordNotFound
rescue NoMethodError
next
end
end
super
end
end
def confirm!
update!(status: "confirmed")
end
def date
inflow_transaction&.entry&.date
end
def sync_account_later
inflow_transaction&.entry&.sync_account_later
outflow_transaction&.entry&.sync_account_later
fee_transactions.each { |t| t.entry&.sync_account_later }
end
def to_account
inflow_transaction&.entry&.account
end
def from_account
outflow_transaction&.entry&.account
end
private
def transfer_has_different_accounts
return unless inflow_transaction&.entry && outflow_transaction&.entry
errors.add(:base, :different_accounts) if to_account == from_account
end
def transfer_has_same_family
return unless inflow_transaction&.entry && outflow_transaction&.entry
errors.add(:base, :same_family) unless to_account&.family == from_account&.family
end
def transfer_has_opposite_amounts
return unless inflow_transaction&.entry && outflow_transaction&.entry
inflow_entry = inflow_transaction.entry
outflow_entry = outflow_transaction.entry
inflow_amount_raw = inflow_entry.amount
outflow_amount_raw = outflow_entry.amount
errors.add(:base, :opposite_amounts) unless inflow_amount_raw.negative? && outflow_amount_raw.positive?
if inflow_entry.currency == outflow_entry.currency
errors.add(:base, :opposite_amounts) if inflow_amount_raw + outflow_amount_raw != 0
end
end
def transfer_within_date_range
return unless inflow_transaction&.entry && outflow_transaction&.entry
date_diff = (inflow_transaction.entry.date - outflow_transaction.entry.date).abs
max_days = status == "confirmed" ? 30 : 4
errors.add(:base, :within_days, count: max_days) if date_diff > max_days
end
end