The personal finance app for everyone (by everyone)
Ruby
test(goals): pledge-delta integration coverage (follow-up to #2178) (#2206)
Guillem Arias Fauste3b4aa5551606
diff --git a/app/models/account/reconciliation_manager.rb b/app/models/account/reconciliation_manager.rbindex 774e9b3306..8d2a3331ee 100644--- a/app/models/account/reconciliation_manager.rb+++ b/app/models/account/reconciliation_manager.rb@@ -9,10 +9,14 @@ class Account::ReconciliationManagerdef reconcile_balance(balance:, date: Date.current, dry_run: false, existing_valuation_entry: nil)old_balance_components = old_balance_components(reconciliation_date: date, existing_valuation_entry: existing_valuation_entry)prepared_valuation = prepare_reconciliation(balance, date, existing_valuation_entry)+ # Captured before save!: the amount this valuation already had on disk+ # (nil when this reconciliation creates it). See valuation_contribution.+ prior_valuation_amount = prepared_valuation.amount_in_databaseunless dry_runprepared_valuation.save!- GoalPledge::Reconciler.new(prepared_valuation).run+ contribution = valuation_contribution(prepared_valuation, prior_valuation_amount, old_balance_components)+ GoalPledge::Reconciler.new(prepared_valuation, valuation_delta: contribution).runendReconciliationResult.new(@@ -42,6 +46,40 @@ class Account::ReconciliationManagerkeyword_init: true)+ # Contribution recorded by this reconciliation: how much the balance moved+ # vs. the prior balance. This (not the full new balance) is what a+ # manual_save GoalPledge matches against.+ #+ # The prior balance is resolved in freshness order:+ # 1. The valuation's own pre-save amount, when this reconciliation+ # updates an existing valuation. The balances table recomputes+ # asynchronously (sync_later fires after this manager returns), so a+ # same-date re-reconcile racing that sync would otherwise read the+ # pre-first-reconcile row and over- or under-state the delta — an+ # overstated delta could wrongly close a larger pledge, which never+ # self-heals. The valuation's own prior amount is immune to that+ # race, and once the sync lands the two sources are identical (the+ # valuation anchors that date's end_balance).+ # 2. The balances-table row for the date (first reconcile on a date).+ # This can still be stale in one residual window: a reconcile on a+ # NEW date racing the previous date's pending sync reads a+ # carried-forward row. A missed match self-heals on the next re-save+ # — the pledge stays open and retryable until `expires_at`, and the+ # date/amount tolerance in GoalPledge#matches? accepts the retry.+ # 3. 0, for a brand-new account with no balance record yet, so the+ # first reconciliation's full balance is its contribution.+ #+ # The delta is only ever consumed for goal-linked accounts, which Goal+ # validates to be Depository assets (Goal#linked_accounts_must_be_depository).+ # Balances there are positive, so a save (deposit) is a positive delta and+ # the reconciler's positive-delta guard is correct. There is no liability+ # sign concern: a credit-card/loan paydown can't reach pledge matching+ # because no manual_save pledge can be attached to a non-depository account.+ def valuation_contribution(valuation, prior_valuation_amount, old_balance_components)+ prior_balance = prior_valuation_amount || old_balance_components[:balance] || 0+ valuation.amount.to_d - prior_balance.to_d+ end+def prepare_reconciliation(balance, date, existing_valuation)valuation_record = existing_valuation ||account.entries.valuations.find_by(date: date) || # In case of conflict, where existing valuation is not passed as arg, but one existsdiff --git a/app/models/goal_pledge.rb b/app/models/goal_pledge.rbindex a72b2cb5b1..a204933cf2 100644--- a/app/models/goal_pledge.rb+++ b/app/models/goal_pledge.rb@@ -38,19 +38,39 @@ class GoalPledge < ApplicationRecord# Tolerance check: entry date within [created_at − 5d, expires_at] (so# extend! widens the upper bound) and amount within ±$0.50 OR ±1%.- # Transfer pledges only fire on inflows (Sure convention: inflow < 0).- # Without this guard, .abs below lets a $200 outflow satisfy a $200- # transfer pledge as readily as a $200 deposit.- def matches?(entry)+ #+ # The amount being compared is the money that actually moved IN:+ # - transfer pledges resolve against a Transaction inflow (Sure+ # convention: inflow < 0), so the entry amount IS the contribution.+ # - manual_save pledges resolve against a Valuation, whose amount is the+ # account's full new TOTAL balance — not the contribution. The caller+ # (Account::ReconciliationManager) passes the balance delta+ # (new_balance − prior_balance) via `valuation_delta`; that delta is+ # the contribution we match against. Comparing the raw valuation amount+ # would only ever match on an account whose entire balance equals the+ # pledge (i.e. one starting from ~$0).+ #+ # Both kinds only fire on money coming in: transfers require an inflow+ # entry, manual_save requires a positive balance delta. Without these+ # guards, .abs below would let a $200 outflow / a $200 drawdown satisfy a+ # $200 pledge as readily as a $200 deposit.+ def matches?(entry, valuation_delta: nil)return false unless status_open?return false unless entry.account_id == account_id- return false if kind_transfer? && !entry.amount.to_d.negative?++ is_valuation = entry.entryable.is_a?(Valuation)++ if is_valuation+ return false if valuation_delta.nil? || valuation_delta.to_d <= 0+ elsif kind_transfer? && !entry.amount.to_d.negative?+ return false+ endearliest = created_at.to_date - MATCH_DATE_TOLERANCE_DAYS.dayslatest = [ created_at.to_date + MATCH_DATE_TOLERANCE_DAYS.days, expires_at.to_date ].maxreturn false unless entry.date >= earliest && entry.date <= latest- txn_amount = entry.amount.to_d.abs+ txn_amount = (is_valuation ? valuation_delta.to_d : entry.amount.to_d).abspledge_amount = amount.to_ddiff_abs = (txn_amount - pledge_amount).absdiff --git a/app/models/goal_pledge/reconciler.rb b/app/models/goal_pledge/reconciler.rbindex f3309dc9e2..81de43746e 100644--- a/app/models/goal_pledge/reconciler.rb+++ b/app/models/goal_pledge/reconciler.rb@@ -1,8 +1,13 @@class GoalPledge::Reconcilerattr_reader :entry- def initialize(entry)+ # `valuation_delta` is the contribution (new_balance − prior_balance) for+ # Valuation entries, supplied by Account::ReconciliationManager which knows+ # the prior balance. It is ignored for Transaction entries, whose own+ # amount is already the contribution.+ def initialize(entry, valuation_delta: nil)@entry = entry+ @valuation_delta = valuation_deltaenddef run@@ -17,7 +22,7 @@ class GoalPledge::Reconciler.where("expires_at >= ?", Time.current).order(:created_at, :id).each do |pledge|- next unless pledge.matches?(entry)+ next unless pledge.matches?(entry, valuation_delta: @valuation_delta)beginif entry.entryable.is_a?(Transaction)diff --git a/test/models/account/reconciliation_manager_test.rb b/test/models/account/reconciliation_manager_test.rbindex fe5257e9d6..7f982d7e99 100644--- a/test/models/account/reconciliation_manager_test.rb+++ b/test/models/account/reconciliation_manager_test.rb@@ -91,4 +91,80 @@ class Account::ReconciliationManagerTest < ActiveSupport::TestCase@manager.reconcile_balance(balance: 1200, date: Date.current)endend++ test "reconciliation matches an open manual_save pledge by contribution delta" do+ account = accounts(:depository)+ manager = Account::ReconciliationManager.new(account)+ create_balance(account: account, date: Date.current, balance: 2000, cash_balance: 2000)++ pledge = goal_pledges(:open_transfer).goal.goal_pledges.create!(+ account: account,+ amount: 150,+ currency: "USD",+ kind: "manual_save"+ )++ result = manager.reconcile_balance(balance: 2150, date: Date.current)++ assert result.success?+ assert pledge.reload.status_matched?+ end++ test "reconciliation to the same balance leaves manual_save pledges open" do+ account = accounts(:depository)+ manager = Account::ReconciliationManager.new(account)+ create_balance(account: account, date: Date.current, balance: 2000, cash_balance: 2000)++ pledge = goal_pledges(:open_transfer).goal.goal_pledges.create!(+ account: account,+ amount: 150,+ currency: "USD",+ kind: "manual_save"+ )++ result = manager.reconcile_balance(balance: 2000, date: Date.current)++ assert result.success?+ assert_not pledge.reload.status_matched?+ end++ test "second same-day reconcile derives its delta from the valuation it updates, not the stale balance row" do+ account = accounts(:depository)+ manager = Account::ReconciliationManager.new(account)+ create_balance(account: account, date: Date.current, balance: 2000, cash_balance: 2000)++ goal = goal_pledges(:open_transfer).goal+ first_pledge = goal.goal_pledges.create!(+ account: account,+ amount: 150,+ currency: "USD",+ kind: "manual_save"+ )++ assert manager.reconcile_balance(balance: 2150, date: Date.current).success?+ assert first_pledge.reload.status_matched?++ # The post-reconcile balance sync is async and hasn't run, so the+ # balances row still says $2,000. The second save of $150 (2150 → 2300)+ # must not be read as a $300 contribution off that stale row — that+ # would wrongly close the larger pledge, and a wrong match never+ # self-heals.+ oversized_pledge = goal.goal_pledges.create!(+ account: account,+ amount: 300,+ currency: "USD",+ kind: "manual_save"+ )+ second_pledge = goal.goal_pledges.create!(+ account: account,+ amount: 150,+ currency: "USD",+ kind: "manual_save"+ )++ assert manager.reconcile_balance(balance: 2300, date: Date.current).success?++ assert_not oversized_pledge.reload.status_matched?+ assert second_pledge.reload.status_matched?+ endenddiff --git a/test/models/goal_pledge/reconciler_test.rb b/test/models/goal_pledge/reconciler_test.rbindex 52a25c72c7..e84064b79d 100644--- a/test/models/goal_pledge/reconciler_test.rb+++ b/test/models/goal_pledge/reconciler_test.rb@@ -52,7 +52,7 @@ class GoalPledge::ReconcilerTest < ActiveSupport::TestCaseassert_not @pledge.reload.status_matched?end- test "manual_save kind matches on Valuation entries" do+ test "manual_save kind matches a Valuation by its contribution delta, not the full balance" domanual_pledge = @pledge.goal.goal_pledges.create!(account: @account,amount: 150,@@ -60,13 +60,48 @@ class GoalPledge::ReconcilerTest < ActiveSupport::TestCasekind: "manual_save")- entry = create_valuation_entry(amount: 150, date: manual_pledge.created_at.to_date)+ # Realistic reconciliation: the account already held $2,000 and the user+ # bumps it to $2,150. The valuation records the full $2,150 total; the+ # $150 contribution is the delta the manager passes in.+ entry = create_valuation_entry(amount: 2150, date: manual_pledge.created_at.to_date)- GoalPledge::Reconciler.new(entry).run+ GoalPledge::Reconciler.new(entry, valuation_delta: 150).runassert manual_pledge.reload.status_matched?end+ test "manual_save kind does not match when the full balance (not the delta) is unrelated to the pledge" do+ manual_pledge = @pledge.goal.goal_pledges.create!(+ account: @account,+ amount: 150,+ currency: "USD",+ kind: "manual_save"+ )++ entry = create_valuation_entry(amount: 2150, date: manual_pledge.created_at.to_date)++ # The full $2,150 balance must never be mistaken for the $150 contribution.+ GoalPledge::Reconciler.new(entry, valuation_delta: 2150).run++ assert_not manual_pledge.reload.status_matched?+ end++ test "manual_save kind does not match a balance decrease" do+ manual_pledge = @pledge.goal.goal_pledges.create!(+ account: @account,+ amount: 150,+ currency: "USD",+ kind: "manual_save"+ )++ entry = create_valuation_entry(amount: 1850, date: manual_pledge.created_at.to_date)++ # Balance dropped by $150 — a drawdown must not resolve a save pledge.+ GoalPledge::Reconciler.new(entry, valuation_delta: -150).run++ assert_not manual_pledge.reload.status_matched?+ end+privatedef create_transaction_entry(amount:, date:, account: @account, excluded: false)Entry.create!(