Link a loan to the property or vehicle that secures it (#129, 10.3)

Merged
JA
2mo ago
+1213-5

Summary

Part of #129 (10.3). loans has no link to the asset that secures it, so equity (value minus debt) is shown nowhere. This adds loans.collateral_account_id (a property or vehicle), a picker on the loan form, and an equity section on the loan's page and on the asset's page. The link is validated to the loan's family and carried through the family export and import.

Plan and decisions are in the #129 body (triage plan, 10.3).

Scope and dependencies

  • Issue: #129 (10.3). Does not close it; 10.1 is #287, 10.2 is #288.
  • Parent PR/branch, if stacked: none. Off main at c783118. Independent of 10.1 and 10.2 (each adds one migration; their schema.rb version lines will conflict trivially on merge).
  • Intentionally out of scope: the /api/v1 accounts API, assistant tools, bulk linking, and any interplay with Loan::PayoffProjection.

What changed

  • Migration loans.collateral_account_id (uuid, nullable, indexed, FK to accounts ON DELETE SET NULL).
  • Loan#collateral_ineligibilities_for is the one definition of eligibility: a Property or Vehicle, in the loan account's family and currency, visible to every user who can see the loan account (the rule LoanOffsetAccount uses). The validation and the form's candidate list (Loan.collateral_candidates_for) both read it, so the list never offers what the save would refuse. "Cannot link to another loan" falls out of the type check. An id that names no account is a validation error (does not exist), not a foreign key exception; a blank id is simply no link.
  • The loan is judged against the account it is being saved through, as submitted (Loan#owning_account, below), so creating a loan, and changing its currency and its collateral in one request, are both judged on the new currency. A new loan in a family that shares by default is judged against everyone who will see it, not only its owner, because its shares are written after validation.
  • The link is judged only when it changes. The loan form resubmits the id it already holds on every edit; validating every save would make a loan uneditable once its asset changed currency. For the same reason the controller keeps the current link selectable even if it would no longer be accepted fresh.
  • Loan::CollateralPosition: equity is the asset's value less every loan linked to it, so a property with two mortgages is not measured against one. Switched-off loans are not debt. Equity is withheld rather than under-counted when the viewer cannot see every linked loan, the currencies differ, or a linked loan has no balance. An asset with no balance has no position, and neither does a loan that is switched off (it is not debt, so its page would show the whole value as equity).
  • UI::Account::CollateralPosition on the loan, property and vehicle overview tabs: value, debt and equity, with links to the counterparts, and a note when equity is withheld.
  • LoansController: permits the param, sets the candidates (narrowed to the submitted currency when a failed create re-renders), and leaves the link alone when the viewer cannot see the asset (their form has no option for it, so a submitted blank would silently unlink it).
  • Family::DataExporter writes every non-loan account before the loans, so a loan's collateral is always ahead of it in the file. Family::DataImporter links each loan to its imported asset once all accounts exist. A session (chunked) import raises MissingReferenceError for a collateral id that has not been imported yet, as every other reference does, instead of dropping the link; a single-file import leaves such a loan unlinked. A link the model refuses is logged to DebugLogEntry.
  • Locale: en for the loan form and the component (other locales fall back to en).

Blast radius

Who else hits these lines: Loan writes. LoansController#update resubmits every form field (covered by the unchanged-link tests). Account deletion nullifies via the FK (tested by deleting the asset). Account gained one has_many :secured_loans and one before_validation that hands a loan its account. The exporter change affects only the order of the Account lines in all.ndjson.

Siblings found by grep, and what was done:

  • loan.account is nil while a new loan validates (Rails cannot infer the inverse across the polymorphic association), and on an update it is the account as stored, not as submitted. A forged other-family id passed creation, and a currency change submitted with a collateral change was judged on the old currency. Account now hands itself to the loan before validating (Loan#owning_account, a transient writer that falls back to account, so a loan saved on its own is unchanged), and the loan's own validation judges the link once. An earlier version used an Account-level validation that covered creation only; it was replaced. inverse_of on delegated_type was tried first and rejected: it makes loan.account non-nil on unsaved accounts and broke Loan::AmortizationScheduleTest.
  • Accounts were exported in primary-key order, and the collateral link is the first reference between two accounts, so no type ordering guaranteed the asset came first; a chunked import could fail on a valid export depending on ids. The exporter now orders loans last. The accounts.csv export is a flat list with no cross-reference and is left alone.
  • LoansController#create re-rendered the form without @offset_accounts, which raises. Creation can now fail on the form's own fields, so create sets it as new and update do.
  • LoanOffsetAccount has the same nil-account gap on create. Probed on main: for a new variable-rate loan an offset in another currency is accepted, and so is one private to the owner in a family that shares by default; a foreign-family offset is refused, by the lookup of the submitted ids. Left alone here as separate behaviour, and raised as #290, which reuses this PR's owning_account.
  • No sharing-change hook, unlike offsets: the position is checked against the viewer's access when it renders, so a later change in sharing cannot leak a figure.

Evidence checklist

  • Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
  • Contract rows touched by this change name existing tests (see Validation).
  • Any gate test has an observed failing mutation transcript attached. Mutations below.
  • Fixtures used as evidence assert internal consistency: balances are set explicitly in each test (550,000 value, 500,000 debt) so equity is derivable from the test's own data.
  • Financial calculations use BigDecimal and documented rounding points. Money arithmetic over BigDecimal balances; no rounding beyond Money#format.
  • De-identification: no personal data in the diff.
  • Files changed, decisions, tests/runtime, risks and next unblocked issue documented below.

Validation

Fail-first: the 20 model tests errored before the association and Loan::CollateralPosition existed. The create-path test caught the nil-account gap above (a forged other-family id created a loan, 302 instead of 422). For the review fixes, the exporter ordering test, the one-chunk-per-account importer test and the two currency-and-collateral controller tests were run red before any production change (one failure each; the importer test first errored on a bug in the test itself, fixed before the run that counted). Then each behaviour broken deliberately, one at a time, and the named tests went red:

MutationTest that failed
importer pass not calledrelinks under the new ids; refused link is logged
importer lenient in a sessiona session import raises when the collateral has not been imported yet
loans exported before other accountsexports loans after every other account, whatever the ids; an exported loan is relinked when each account arrives in its own chunk
validate on every savesaving other fields keeps an ineligible link; resubmitting the unchanged link; the form keeps it selectable; a viewer who cannot see the asset
account does not hand itself to the loana loan being created is judged against its account; a new loan the family will share; failed create re-renders; both currency-and-collateral controller tests
type / family / currency / viewer check offone named test each, plus the controller's refuse tests
viewers not prospective for a new accounta new loan the family will share cannot be secured by a private asset
viewers worked out per candidatethe candidate list works out the loan's viewers once
unknown id ignoredvalidation error not foreign key exception (model, create and controller)
debt from the first loan onlyevery loan on the asset counts
always complete / ignore currency / ignore nil loan balancewithheld when the viewer cannot see every loan; across currencies; while a loan has no balance
count switched-off loans / for_loan without the in-use checka loan that is switched off no longer counts; shows no position of its own (model and page)
nil asset balancean asset with no valuation yet has no position
loan side ignores viewer access / viewer sees all loansloan side returns nothing; component withholds equity
drop protect_inaccessible_collaterala viewer who cannot see the asset leaves the link alone
drop current-link retention / unfiltered candidates / currency narrowingthe form tests
param not permittedsix controller tests
FK without SET NULL (changed in the scratch DB)deleting the asset unlinks the loan

The first exporter test passed the original exporter by design for the column itself (it rides as_json); the ordering test is the one that pins the order.

Exit criteria: a loan cannot link to an account outside its family (rejects an account in another family, and through create_and_sync) or to another loan (rejects another loan).

Commands (Ruby 3.3.6 with the Gemfile's ruby line removed, local Postgres and Redis; see Risks):

  • bin/rails test, full suite on the export-order and owning_account fixes: 11414 runs, 49365 assertions, 4 failures, 1 error, 33 skips. The five are the same tests that fail on an untouched main in this environment (re-run by name here): 3 in Settings::HostingsControllerTest and 1 in Provider::RegistryTest read ANTHROPIC_BASE_URL (set in this sandbox), and Provider::OpenaiTest expects Ruby 3.4's Hash#inspect. After the last change (viewers computed once per candidate list), the loan, Account, loans, properties and vehicles controller, family exporter and importer, and account component tests were rerun: 634 runs, 0 failures.
  • CI passed on b16ccad on Ruby 3.4.9. The latest push (6079fde) is re-running and is checked before this is marked ready.
  • bin/rubocop on the changed files: no offenses. bin/brakeman --no-pager: no warnings.
  • erb_lint on the changed ERB files (earlier commits): one finding, app/views/loans/_form.html.erb:108 (missing autocomplete on the rate-change <input>), which is identical on an untouched main and not touched here.
  • Migration: run forward on a scratch database; schema.rb takes only the version, column, index and foreign key from its dump (the dump also reformatted three unrelated retirement-plan check constraints under this Postgres version, which were left out). Not rolled back, and not run against any shared database.

Not run: DISABLE_PARALLELIZATION=true bin/rails test:system locally (no Selenium here; CI runs it), npm run lint (no JavaScript changed). No screenshots: the loan form and the three overview tabs were rendered through controller and component tests only.

Risks, blockers, and follow-up

  • Verified locally under Ruby 3.3.6, not the 3.4.9 in .ruby-version (3.4.9's source host is blocked in this environment). CI runs 3.4.9.
  • The owner waived the issue gate for #129 on 2026-10-01. The Gatekeeper account has since reviewed this draft twice (a daily sweep and a review, both "production ready: no" on two findings, the export order and the stale currency, both now fixed). Neither is the owner's approval, and a full Gatekeeper review is still due when the PR is marked ready. Checked against the fork's own AGENTS.md; upstream we-promise/sure's was not read (outside this session's repository scope), per rule 3 it must be before this is marked ready.
  • For a loan being created, the first render of the collateral picker lists every family property and vehicle the user can see, in any currency, because the loan's currency and eventual viewers are not known until it is submitted; a mismatch is refused on save with a message, and a failed create re-renders the picker narrowed to the submitted currency.
  • Not covered, and a decision for the owner: a viewer who can see the loan but not the asset sees no equity (by design) and is not told why; and an asset viewer who cannot see one of its loans is told that equity is withheld, which reveals that a hidden loan exists (not its balance). Both are the equity-withheld rule; changing the wording or hiding the note is a small change if wanted.
  • Next unblocked: #290 (the same gap for offset accounts), which reuses this PR's owning_account and should follow it.