fix(accounts): keep the entered current balance when it differs from the opening one
Cleaner resubmit of #3281, as requested — same fix, one commit.
The problem
Create a loan with an opening balance that differs from its current balance —
original principal 250,000, remaining 180,000 — and the 180,000 is gone as soon
as the account syncs. The account shows 250,000.
Account.create_and_sync anchors only the opening balance, so that anchor is
the account's only entry and the initial sync walks forward from it, overwriting
the current balance the user just typed.
The change
Anchor today's balance too, as an explicit same-day reconciliation, whenever the
two differ and the opening anchor sits on an earlier day.
The date guard is load-bearing. opening_balance_date is user-editable and can
be today, and ReconciliationManager matches an existing valuation by date
alone — kind is not part of the lookup. Without the guard it reuses the opening
anchor and reassigns its amount, which discards the opening balance and leaves a
kind: "opening_anchor" row holding the current balance. On its own date the
opening balance wins.
A direct reconciliation rather than CurrentBalanceManager: the manager's
cash-account strategy computes a zero delta at creation, because account.balance
already holds the entered value, so it would only rewrite the opening anchor and
leave today's balance unanchored for the first sync.
initial_balance's presence is read from the raw value, since "".to_d is 0.
A blank field would otherwise record an opening balance of 0 and, because 0
differs from the entered balance, write a reconciliation on top of it. An
explicit 0 is still a real opening balance.
initial_balance is a Loan attribute today, so the loan regression tests cover
the reachable path.
Verification
bin/rails test, bin/rubocop -f github, bin/brakeman --no-pager, all green.
Four regression tests in account_test.rb cover the differing-balance case, the
opening date falling on today, and an explicit zero opening balance; they fail
against main.
Summary by CodeRabbit
- Bug Fixes
- Improved account setup when entering an opening balance.
- Blank opening balances are now treated as unspecified rather than zero.
- Preserves both the opening balance and the entered current balance when they differ and the opening date is earlier than today.
- Correctly handles zero opening balances and opening balances dated today.