Let a loan name the property or vehicle securing it
Part of #4079
Fork pre-flight: jaysbeekay/sure#363 (same branch, same commit; its CI and review history live there). Model layer of jaysbeekay/sure#129, drop 10.3.
Rebased 2026-10-13 onto main ff51e7e2d. The only conflict was the db/schema.rb version line, kept at main's 2026_10_11_151000; none of the migrations added to main since the old base touches loans. The patches are unchanged.
Review fixes, 2026-10-14: a9c452fda (for_loan is nil for a loan that is not itself in use) and e6bdc6ab4 (Loan.viewers_of counts only active members). Both follow main merged in at a3bb5d991.
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: nullableloans.collateral_account_id(uuid), indexed, foreign key toaccountswithon_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_problemsadds "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.accountis nil while a new loan validates (no inverse across the polymorphic accountable) and is the stored, not submitted, account on an update.Accountnow hands itself to its loan inbefore_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(nodependent:; the foreign key nullifies) and thebefore_validationhand-off above, limited to loan accounts whose accountable is loaded.Loan::CollateralPosition(new):for_collateral(account, viewer:)andfor_loan(loan, viewer:)reach the same position;for_loanis 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.debtandequityare 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 noaccountable_type(where.notalone would drop them, asNULL <> 'Loan'is NULL).Family::DataImporter:link_loan_collateralruns afterimport_accountsand 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 aDebugLogEntrywhen 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 intest/models/family/data_exporter_test.rb(3) anddata_importer_test.rb(6), plusloan_test.rbandaccount_test.rb: 224 runs, 0 failures. - Full suite
bin/rails testat e6bdc6ab4 (onmaina3bb5d991): 11869 runs, 54701 assertions, 0 failures, 0 errors, 34 skips. Earlier, at 218a33a32 (onmainff51e7e2d): 11826 runs, 54527 assertions, 0 failures, 0 errors, 34 skips. bin/rubocop -f githubon 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:
| Mutation | Caught by |
|---|---|
| property/vehicle type check removed | rejects any other kind of account, rejects another loan, rejects the loan's own account |
| same-family check removed | rejects an account in another family, a loan being created is judged against the account it is created on |
| same-currency check removed | rejects 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 removed | requires 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 change | saving other fields keeps a link that has since become ineligible, resubmitting the unchanged link on an ineligible asset still saves |
| unknown id accepted | an 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 removed | a new loan the family will share cannot be secured by a private asset |
| Account's hand-off removed | a loan being created is judged against the account it is created on, a new loan the family will share ... |
| debt counts only the first loan | every loan on the asset counts, so equity is not measured against one of them |
| completeness ignores loans the viewer cannot see | equity is withheld when the viewer cannot see every loan secured on the asset |
| mixed currencies summed | equity is withheld rather than summed across currencies |
| switched-off loans count as debt | a 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 asset | the loan side returns nothing when the viewer cannot see the collateral |
| loan side ignores whether its own loan is in use | a 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 draft | a draft loan is in use and shows the asset's position |
| deactivated members counted as loan viewers | an inactive family member does not block a collateral link, the candidate list does not wait on an inactive family member |
| export not ordered loans-last | exporter 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 skipped | 5 importer tests, incl. relinks a loan to the property that secured it, under the new account ids |
| relink reference not strict | a session import raises when a loan's collateral has not been imported yet |
| refusal not logged | a 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 check | the 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 given | the candidate list for a new loan leaves out what its save would refuse |
| export's first pass drops accounts with no type | exporter exports an account with no accountable type, ahead of the loans |
Blast radius
- Who else hits this line, and what do they pass?
Loansaves:LoansController(throughAccountableResource) does not permitcollateral_account_id, so no request can set it yet; provider processors (Plaid liabilities, SimpleFIN and others) andDemo::Generatorcreate loans without it. The validation is skipped for all of them, as the column does not change.Accountvalidation: the newbefore_validationruns for every loan account whose accountable is loaded and only sets a transient attribute on the loan; nothing else readsowning_account.Accountdestroy: the foreign key nullifiesloans.collateral_account_id;secured_loanshas nodependent:so no callback is added to the destroy path.- Export:
FamilyDataExportJobandInactiveFamilyCleanerJobcallFamily::DataExporter#generate_export; the only change they see is account order (loans last). Import:SureImport#import!callsFamily::DataImporter; the new step only acts on loan records that carry acollateral_account_id.
- What else reads what I just changed the reading of?
grep -rln collateral app liblists only the five files in this PR.grep -rn "DataExporter.new\|DataImporter.new" applists the three callers above. Nothing else readsAccountexport order.
Summary by CodeRabbit
- New Features
- Loans can now be linked to eligible property or vehicle accounts as collateral. Collateral must be in the same family, use the same currency, and be visible to everyone who can view the loan.
- Collateral values can be shown alongside secured debt and resulting equity when the required account and balance information is available.
- Loan collateral links are preserved when accounts are exported and imported.
Summary by CodeRabbit
- New Features
- Loans can be linked to eligible property or vehicle accounts as collateral. The collateral must be in the same family, use the same currency, and be visible to everyone who can view the loan.
- Collateral values can be shown alongside secured debt and resulting equity when the required account and balance information is available. Debt and equity may be unavailable when loan details are incomplete or not fully visible.
- Loan collateral links are preserved when accounts are exported and imported.