Edit a lot's cost, and merge opening lots on remap

Merged
JA
1mo ago
+496-18

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/:id and POST …/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_cost falls back to calculate_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.

BeforeAfter
Desktop (1400px)beforeafter
Phone (390px)before phoneafter phone

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.

BeforeAfter
Desktop (1400px)locked beforelocked after
Phone (390px)locked before phonelocked after phone

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_price in each calculator serves acquisitions and outbound transfers. Only an acquisition takes a manual cost: manual_unit_cost returns nil for a non-positive quantity.
  • HoldingLot.store! upserts only security_id acquired_on qty unit_cost currency (and clamped), so a user's manual_total_cost survives every materialization. A deleted trade deletes its lot, and the cost with it.
  • HoldingsController#show now 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's unit_cost from the book, which then carries the manual figure.
  • Holding#calculate_avg_cost and Holding.preload_avg_costs do 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, forward and …, 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_at and value checked].
  • a lot edit with the lot count unchanged invalidates the statement cache [holdings_version moves].
  • 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_d would read abc as 0, added for the light review at d00ca826f].
  • 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):

#MutationCaught by
P1no merge (1b's behaviour)both merge tests
P2merge keeps the target's cost alwayscost-agreement test
P3forward ignores the manual cost on a buy4 tests
P4reverse treats a costed transfer-in as unknownreverse transfer-in test
P5manual total divided by the lot's current qtysplit-and-sale test
P6forward treats a costed transfer-in as unknownforward transfer-in test
P7no restatement after updateupdate test, statement-cache test
P8negative total acceptedrejection test (the DB check also refuses it)
P9opening lot editableopening-lot test
P10lot not scoped to the holding's positionother-family test
P11no write-permission checkread-only test
P12drawer lists lots out of partitiondrawer test
P13unlock does not clear the costunlock test
P14total 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, the icon helper.
  • 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_cost is 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.