Edit a lot's cost, and merge opening lots on remap
Part of jaysbeekay/sure#551. This is PR 3 of the stack (PR 2b #581 ← PR 3 ← 3b #583 ← 4 ← 5; owner decisions 13 and 15). Its base is main, because #581 merged as cce8f97cf.
Problem
A lot's cost can't be changed. A transfer-in lot stays unknown, and so does the position holding it, until it is sold. The only way out is a whole-position override. Separately, when a remap moves an opening lot onto a position that has its own, 1b deletes the moved lot and lets the next materialization restate it, and the moved units' cost is lost on the way.
What this changes
- A lot list in the holding drawer, under Average Cost. Each open lot shows its date (or "Held before the first trade" for the opening lot), its quantity and its unit cost, with a lock where the user set it. A lot a trade acquired opens to an editor for the total paid for the parcel, with a note that deleting its trade removes the lot and the cost. A set lot gets "Use the trade's price" to unlock it. The list appears only while the stored lots add up to the position (
HoldingLot.in_partition, decision 12). holding_lots.manual_total_cost: decimal(19,4), nullable, with a check that it's ≥ 0. A value means the user set it; nil means the lot follows its trade.- Both calculators read it in place of the trade's price, spread over the units the trade brought in (decision 16). A split or a pro-rata sale then scales it like any lot cost. On a transfer-in it replaces the unknown cost, so the position resolves.
HoldingLotsController:PATCH /holdings/:holding_id/lots/:idandPOST …/unlock.- It is gated like the holding's own cost editor (family-scoped holding, write permission).
- The lot is found among the holding's position's derived lots, so another account's lot and an opening lot both give a 404.
- It permits only
total_cost_basis, which must be ≥ 0. - The edit is restated into that security's holdings straight away, as a price sync is.
- Opening-lot merge on remap (decision 14), in
HoldingLot.move!. The quantities add, and the target keeps its row and its origin. The cost stays only where both sides know it and agree; otherwise it is nil.
Not in this PR, and why:
- A clamped position becoming unknown, and its data-quality entry. That is PR 3b (decision 15).
- The current row of a linked account. On a linked account the latest row is the provider's, which the materializer never writes. Where the provider gives no cost,
Holding#avg_costfalls back tocalculate_avg_cost, which refuses any position with a transfer-in. So a lot cost set on a linked account resolves every calculated date but not the provider's own row. That fallback is what PR 3b (#583) changes for the clamp, and it reads lot costs there. The reverse test here asserts the last calculated date, and says so. - Editing the opening lot. It stays out of the position's figure (decision 8), so a cost on it would change nothing visible.
Screenshots
The holding drawer for a position with a transfer-in lot (unknown) and a buy, with the first lot's editor open. The before shots are from main, the after shots from this PR. Both were rendered headless by a throwaway system test on the test containers, with fixture data.
| Before | After | |
|---|---|---|
| Desktop (1400px) | ![]() | ![]() |
| Phone (390px) | ![]() | ![]() |
The lot row and its unlock action use DS::Disclosure and DS::Button. This pair shows a lot with a cost set, so the unlock action is visible: before is d00ca826f (raw details and button_to), after is 837ee1f68. The row's layout is unchanged; "Use the trade's price" now renders as a ghost button.
| Before | After | |
|---|---|---|
| Desktop (1400px) | ![]() | ![]() |
| Phone (390px) | ![]() | ![]() |
Blast radius
Who else hits these lines, and what do they pass?
HoldingLot.move!has two callers:Holding#remap_security!, which now merges, and#reset_security_to_provider!. Reset moves back only opening lots whose origin is the original security. A merged lot keeps the target's origin, so it stays where it is, which is decision 14's accepted limitation.effective_trade_pricein each calculator serves acquisitions and outbound transfers. Only an acquisition takes a manual cost:manual_unit_costreturns nil for a non-positive quantity.HoldingLot.store!upserts onlysecurity_id acquired_on qty unit_cost currency(andclamped), so a user'smanual_total_costsurvives every materialization. A deleted trade deletes its lot, and the cost with it.HoldingsController#shownow loads the lots: 2 queries, the partition check and the list.
What else reads what changed (siblings):
- Lot costs: the calculators, through
manual_lot_costs, loaded once per run. The materializer writes the lot'sunit_costfrom the book, which then carries the manual figure. Holding#calculate_avg_costandHolding.preload_avg_costsdo not read lots. They are left to PR 3b, as above.- The whole-position override (
Holding#set_manual_cost_basis!) still outranks lots: the materializer keeps a locked row's figure. This is tested.
Tests
test/models/holding_lot_test.rb; the bracket says what each assertion catches.
remap onto a position with its own opening lot merges the two[target qty 10, one opening lot, the target's id kept]. This restates 1b's "leaves one opening lot there", as #551 required.merged opening lot keeps its cost only when both sides agree[25/25 → 25; 25/30, nil/30, 25/nil → nil].a user-set cost on a transfer-in lot resolves the position, forwardand…, reverse[nil before; $15.20 after, the Example's figure].a user-set cost replaces a buy's price, and unlocking returns it to the trade[$15.20 → $13.20 → $15.20].a user-set lot cost survives a split and a partial sale[$1,500 over the 10 bought, then a 2:1 split, gives $75, where dividing by the lot's 15 left would give $100].a whole-position lock outranks a user-set lot cost[$99 kept].
test/controllers/holding_lots_controller_test.rb:
update sets one lot's cost, locks it and restates the position[$13.20 without waiting for a sync].resubmitting the same lot id updates it in place and never duplicates[count unchanged; id,created_atand value checked].a lot edit with the lot count unchanged invalidates the statement cache[holdings_versionmoves].unlock returns the lot to its trade's cost.another family's lot id is 404,an opening lot is not editable.a negative, blank or non-numeric total is rejected and the lot is unchanged[-1, blank,abc,12abc;String#to_dwould readabcas 0, added for the light review atd00ca826f].qty and acquired_on are not permitted on a derived lot.a read-only member cannot edit a lot[the not-authorized alert; the lot unchanged].the drawer lists the position's lots, and only while they add up to it.
Evidence
Fail first. On main (cce8f97cf), 17 of the new tests fail or error for the expected reasons:
- the two merge tests fail on their assertions, because 1b deletes the moved lot;
- the rest error on
undefined method 'set_manual_total_cost!'or'holding_lot_path'.
Mutations (14, all caught):
| # | Mutation | Caught by |
|---|---|---|
| P1 | no merge (1b's behaviour) | both merge tests |
| P2 | merge keeps the target's cost always | cost-agreement test |
| P3 | forward ignores the manual cost on a buy | 4 tests |
| P4 | reverse treats a costed transfer-in as unknown | reverse transfer-in test |
| P5 | manual total divided by the lot's current qty | split-and-sale test |
| P6 | forward treats a costed transfer-in as unknown | forward transfer-in test |
| P7 | no restatement after update | update test, statement-cache test |
| P8 | negative total accepted | rejection test (the DB check also refuses it) |
| P9 | opening lot editable | opening-lot test |
| P10 | lot not scoped to the holding's position | other-family test |
| P11 | no write-permission check | read-only test |
| P12 | drawer lists lots out of partition | drawer test |
| P13 | unlock does not clear the cost | unlock test |
| P14 | total parsed with to_d (the code at 5559dd6bf) | rejection test, at abc |
Migration. I ran it on a scratch test database on beastpc: up, db:rollback, then up again, all clean. The regenerated db/schema.rb differs from the committed one only in the PG16 formatting of five unrelated check constraints, which were left out.
== 20261024120000 AddManualTotalCostToHoldingLots: migrated
== 20261024120000 AddManualTotalCostToHoldingLots: reverted
== 20261024120000 AddManualTotalCostToHoldingLots: migrated
Full suite at 5559dd6bf: 14393 runs, 66852 assertions, 0 failures, 0 errors, 38 skips. bin/rubocop, erb_lint and bin/brakeman (0 warnings) are clean.
AGENTS.md
I checked the change against the current we-promise/sure AGENTS.md, including the 23 October rule on comments:
- Code placement: logic in models and POROs; the controller is thin.
- Design system:
styled_form_with,money_field,DS::Button, native<details>, functional tokens only, theiconhelper. - Copy: every string through
t()(holdings.lots.*,holding_lots.*). - Comments: intent only, with no history.
- Migration: reversible and schema-only, with no backfill.
manual_total_costis a nullable column with a check, a metadata-only change. - Screenshots: included above.
- Commit: the subject is ≤72 characters.
Summary by CodeRabbit
-
New Features
- View holding lots with acquisition dates, quantities, and unit costs. Edit a lot’s total cost basis or return it to the trade’s price.
- Manually set cost basis for lots, with updated position calculations reflecting the adjustment.
- Combine matching opening lots when moving them between securities.
-
Bug Fixes
- Preserve lot quantities and apply consistent cost handling when opening lots are combined.







