Let a loan name the property or vehicle securing it

Closed
JA
2mo ago
+950-2

Part of #129

Upstream pre-flight for the schema and model layer of drop 10.3 (loan secured by a property or vehicle). Upstream issue: we-promise/sure#4079. Upstream PR: we-promise/sure#4088 (draft, opened 2026-10-09). Same branch, same commit. Base is mirror/upstream-main; the merge base is upstream main at ff51e7e2d, so the diff below is what upstream will see.

Rebased 2026-10-13 onto upstream main ff51e7e2d (owner's instruction, force-pushed with a lease from 24dc1bd43; the old head is kept as backup/up/loan-collateral-account-pre-rebase-24dc1bd43). The only conflict was the db/schema.rb version line, resolved to upstream's 2026_10_11_151000; none of upstream's new migrations touches loans, and git diff mirror/upstream-main HEAD -- db/schema.rb is the column, its index and its foreign key. New hashes: 9b0d3632e, 710a4afa0, bb3856c7b (was 28b633a94), 950712362 (was 2085745c4), 08c5fabc1, 218a33a32 (was 24dc1bd43). Full bin/rails test on 218a33a32: 11826 runs, 54527 assertions, 0 failures, 0 errors, 34 skips. rubocop on the changed files and brakeman: clean.

Model and schema only. From #289 the loan form picker (LoansController, loans/_form), UI::Account::CollateralPosition, the overview-tab hooks and the locale strings stay on fork main until the UI drop.

Fork sync hazard: fork main adds the same column in 20261001110000_add_collateral_account_to_loans, and this branch adds it in 20261008110000. That timestamp is now older than upstream's newest migration (20261011151000); Rails runs it anyway, because pending migrations run whatever their order. Dropping the fork's migration alone does not make the sync safe. A fork database has already applied 20261001110000, so 20261008110000 stays pending and its add_reference raises on the existing column, which the test up refuses a column it did not create rather than adopting it pins. Both files also define AddCollateralAccountToLoans, so they cannot coexist. The sync PR on fork main must therefore delete 20261001110000 and carry a fork-only guarded copy of 20261008110000: up skips when the column exists, and down is a no-op, so a rollback never drops a column this migration did not create. The owner confirms the exact form at sync time (nightly review 6134303559). The upstream migration stays the plain reversible change.

Divergences from fork main: migration timestamp; the two private helpers use upstream loan.rb's private def style and sit beside the other new methods; Loan.viewers_of's comment no longer mentions offset links (upstream has none). All other code and every test are byte-identical, except two review fixes made here first and not yet on fork main (back-port pending): bb3856c7b (was 28b633a94) (the candidate list for a new loan is judged as its save will judge it) and 950712362 (was 2085745c4) (an account with no accountable type is no longer dropped from all.ndjson).

Upstream review fixes, 2026-10-14 (made here first; back-port to fork main pending): a9c452fda (for_loan is nil for a loan that is not in use, Codex 4266494388) and e6bdc6ab4 (Loan.viewers_of counts only active members, Codex 4266494396). CodeRabbit 4266493895 declined; see the comment on this PR. Head e6bdc6ab4, merged with mirror/upstream-main a3bb5d991 at 3ba12286a. Full bin/rails test on e6bdc6ab4: 11869 runs, 54701 assertions, 0 failures, 0 errors, 34 skips.


Part of #4079

Fork pre-flight: this PR (same branch, same commit). Model layer of jaysbeekay/sure#129, drop 10.3.

Summary

Lets a loan name the property or vehicle that secures it, and adds Loan::CollateralPosition, the asset's value, debt and equity against every loan secured on it. Schema and model only: no view, controller, form field or locale string.

What calls this? Inside this PR: the validation, and the family export/import, which round-trips the link. Nothing in the app sets the link yet. The loan form's picker (reading Loan.collateral_candidates_for) and the equity row on the loan, property and vehicle pages (reading Loan::CollateralPosition) are a separate UI PR that follows once this lands. Merging this changes no behaviour a user can see; an export gains loans-last ordering, which import already tolerates.

What changed

  • Migration 20261008110000_add_collateral_account_to_loans: nullable loans.collateral_account_id (uuid), indexed, foreign key to accounts with on_delete: :nullify, so deleting the asset unlinks its loans rather than failing or orphaning them.
  • Loan (app/models/loan.rb)
    • belongs_to :collateral_account, optional: true; COLLATERAL_ACCOUNTABLE_TYPES = %w[Property Vehicle].
    • validate :collateral_account_is_eligible, if: :will_save_change_to_collateral_account_id?. Judged only when the link changes, because the loan form resubmits the id it already holds on every edit; a validation on every save would reject any edit of a loan whose asset has since become ineligible.
    • collateral_ineligibilities_for(account): must be a property or vehicle; in the loan's family; in the loan's currency; visible to every active member who can see the loan (Loan.viewers_of; a deactivated member, whose shares wait for the purge, is not a viewer). collateral_problems adds "does not exist" for an id that names no account, so a crafted id is a validation error rather than a foreign-key exception.
    • Loan.collateral_candidates_for(loan, viewer:): the accounts a viewer may pick, filtered by the same rule, so a picker never offers an account the save would refuse. For a loan not yet created it judges against a stand-in built as the save builds the account (the viewer as owner, the given currency or else the family's), so the currency and visibility checks apply to a new loan too.
    • owning_account: loan.account is nil while a new loan validates (no inverse across the polymorphic accountable) and is the stored, not submitted, account on an update. Account now hands itself to its loan in before_validation, so a request that changes the currency and the link together is judged on the submitted currency, and a new loan on its new account.
  • Account: has_many :secured_loans (no dependent:; the foreign key nullifies) and the before_validation hand-off above, limited to loan accounts whose accountable is loaded.
  • Loan::CollateralPosition (new): for_collateral(account, viewer:) and for_loan(loan, viewer:) reach the same position; for_loan is nil for a loan that is not itself in use, even while another loan keeps the asset's position. Debt counts every in-use (Account.visible) loan secured on the asset, so a first and second mortgage give one equity figure. debt and equity are nil when the viewer cannot see every such loan, a loan has no balance, or currencies differ.
  • Family::DataExporter: accounts are written non-loans first, then loans, so a chunked session import never meets a loan before its asset. The first pass also takes accounts with no accountable_type (where.not alone would drop them, as NULL <> 'Loan' is NULL).
  • Family::DataImporter: link_loan_collateral runs after import_accounts and maps the old collateral id to the new one. Strict in a session import (raises on a reference not yet imported, like every other reference); a single-file import leaves the loan unlinked when the asset is not in the file, and records a DebugLogEntry when the model refuses the link.

Demo data

None added. The demo generator's loans are left unlinked; linking the demo mortgage to the demo house can come with the UI PR, where it would be visible.

Migration notes

One additive migration: a nullable column, an index and a foreign key on loans. No backfill, no data change; existing loans stay unlinked. Reversible (add_reference in change).

Verification

  • Targeted: test/models/loan/collateral_account_test.rb (22 tests), test/models/loan/collateral_position_test.rb (14), new export/import tests in test/models/family/data_exporter_test.rb (3) and data_importer_test.rb (6), plus loan_test.rb and account_test.rb: 224 runs, 0 failures.
  • Full suite bin/rails test at e6bdc6ab4 (on main a3bb5d991): 11869 runs, 54701 assertions, 0 failures, 0 errors, 34 skips. Earlier, at 218a33a32 (rebased onto upstream main ff51e7e2d): 11826 runs, 54527 assertions, 0 failures, 0 errors, 34 skips.
  • bin/rubocop -f github on the changed files: no offences. bin/brakeman --no-pager -q: 0 warnings. No ERB or JS changed.
  • Each behaviour was broken on purpose and the named test failed:
MutationCaught by
property/vehicle type check removedrejects any other kind of account, rejects another loan, rejects the loan's own account
same-family check removedrejects an account in another family, a loan being created is judged against the account it is created on
same-currency check removedrejects an account in a different currency, importer a loan whose collateral the model refuses is imported unlinked and the refusal is logged
visible-to-every-viewer check removedrequires every loan viewer to see the collateral, a new loan the family will share cannot be secured by a private asset
validate on every save, not only on changesaving other fields keeps a link that has since become ineligible, resubmitting the unchanged link on an ineligible asset still saves
unknown id acceptedan id that is not an account is a validation error, not a foreign key exception, an unknown id on a loan being created is refused too
share-by-default new-account rule removeda new loan the family will share cannot be secured by a private asset
Account's hand-off removeda loan being created is judged against the account it is created on, a new loan the family will share ...
debt counts only the first loanevery loan on the asset counts, so equity is not measured against one of them
completeness ignores loans the viewer cannot seeequity is withheld when the viewer cannot see every loan secured on the asset
mixed currencies summedequity is withheld rather than summed across currencies
switched-off loans count as debta loan that is switched off no longer counts as debt, a loan that is switched off shows no position of its own
loan side ignores whether the viewer can see the assetthe loan side returns nothing when the viewer cannot see the collateral
loan side ignores whether its own loan is in usea switched-off loan shows no position even when another loan on the asset is in use, a loan pending deletion shows no position ...
loan side counts only active status, not drafta draft loan is in use and shows the asset's position
deactivated members counted as loan viewersan inactive family member does not block a collateral link, the candidate list does not wait on an inactive family member
export not ordered loans-lastexporter exports loans after every other account, whatever the ids, importer an exported loan is relinked when each account arrives in its own chunk
import relink step skipped5 importer tests, incl. relinks a loan to the property that secured it, under the new account ids
relink reference not stricta session import raises when a loan's collateral has not been imported yet
refusal not loggeda loan whose collateral the model refuses is imported unlinked and the refusal is logged
candidate list for a new loan judged with no stand-in account (the old behaviour)the candidate list for a new loan leaves out what its save would refuse
candidate list skips the visibility checkthe candidate list for a new loan leaves out what its save would refuse, the candidate list works out the loan's viewers once, not once per candidate
stand-in ignores the family's currency when none is giventhe candidate list for a new loan leaves out what its save would refuse
export's first pass drops accounts with no typeexporter exports an account with no accountable type, ahead of the loans

Blast radius

  • Who else hits this line, and what do they pass?
    • Loan saves: LoansController (through AccountableResource) does not permit collateral_account_id, so no request can set it yet; provider processors (Plaid liabilities, SimpleFIN and others) and Demo::Generator create loans without it. The validation is skipped for all of them, as the column does not change.
    • Account validation: the new before_validation runs for every loan account whose accountable is loaded and only sets a transient attribute on the loan; nothing else reads owning_account.
    • Account destroy: the foreign key nullifies loans.collateral_account_id; secured_loans has no dependent: so no callback is added to the destroy path.
    • Export: FamilyDataExportJob and InactiveFamilyCleanerJob call Family::DataExporter#generate_export; the only change they see is account order (loans last). Import: SureImport#import! calls Family::DataImporter; the new step only acts on loan records that carry a collateral_account_id.
  • What else reads what I just changed the reading of? grep -rln collateral app lib lists only the five files in this PR. grep -rn "DataExporter.new\|DataImporter.new" app lists the three callers above. Nothing else reads Account export order.