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

Closed
JA
25d ago
+626-17

Part of #4449.

Slice 4 (U4) of the per-lot cost basis series that #4449 proposes. Depends on #4497 (slice 3, the fifo method), which depends on the slices before it. This PR targets up/551-u3 (the branch of #4497, pushed to this repo at the same commit as the fork's), so Files changed shows this slice alone. Merge bottom-up: once #4497 is in main, I retarget this PR to main and merge main down. Merged before #4497, it would land in up/551-u3 rather than main.

In short. Lets a user set a lot's cost (a transfer-in or an opening lot, for example), and merges opening lots when a holding is remapped. Look first: HoldingLotsController, holdings/_lots.html.erb, Holding::TradeCalculatorHelpers#manual_lot_costs. Check: bin/rails test test/models/holding_lot_test.rb test/controllers/holding_lots_controller_test.rb; the lot editor is in Screenshots.

Fork pre-flight: jaysbeekay/sure#602 (https://github.com/jaysbeekay/sure/pull/602), which holds this slice's CI and review history. Same branch, same commit. It ports the merged fork PR jaysbeekay/sure#582, whose review history is there too.

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, which also overrides the units whose cost is known. Separately, when a remap moves an opening lot onto a position that has its own, slice 2 drops the moved lot and lets the next materialization restate it, so 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 lot with a cost set 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).
  • holding_lots.manual_total_cost: decimal(19,4), nullable, checked ≥ 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. 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: a family-scoped holding and write permission.
    • The lot is found among the position's derived lots, so another account's lot and an opening lot both give a 404.
    • It permits only total_cost_basis, parsed strictly and required to be ≥ 0, and bounded so it fits the column.
    • The edit is restated into that security's holdings straight away, as a price sync is.
  • Opening-lot merge on remap, 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 slice:

  • Editing the opening lot. It stays out of the position's figure, so a cost on it would change nothing visible.
  • The provider's own row on a linked account. The materializer never writes it, and where the provider gives no cost, Holding#calculate_avg_cost refuses a position with a transfer-in. A lot cost on a linked account resolves every calculated date but not that row; slice 5 changes that fallback.

Screenshots

The holding drawer for a position with a transfer-in lot (unknown cost) and a buy, with the first lot's editor open. Rendered headless by a throwaway system test with fixture data. Before is slice 3's head, after is this branch.

BeforeAfter
Desktop (1400px)beforeafter
Phone (390px)before phoneafter 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.
  • effective_trade_price in each calculator serves acquisitions and outbound transfers. Only an acquisition takes a manual cost, because manual_unit_cost is nil for a non-positive quantity.
  • HoldingLot.store! upserts only security_id acquired_on qty unit_cost currency 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.

Siblings:

  • The calculators read lot costs through manual_lot_costs, once per run.
  • The whole-position override (Holding#set_manual_cost_basis!) still outranks lots, because the materializer keeps a locked row's figure. This is tested.

Tests

test/models/holding_lot_test.rb:

  • a remap onto a position with its own opening lot merges the two, and the merged cost is kept only when both sides agree;
  • a user-set cost on a transfer-in lot resolves the position, forward and reverse ($15.20, #4449's Example);
  • a user-set cost replaces a buy's price, and unlocking returns it;
  • the cost survives a 2:1 split and a partial sale ($75, where dividing by the lot's remaining 15 would give $100);
  • a whole-position lock outranks a lot cost.

test/controllers/holding_lots_controller_test.rb:

  • an update sets the cost, locks it and restates the position;
  • resubmitting updates in place;
  • unlock;
  • another family's lot and an opening lot give 404;
  • a negative, blank, non-numeric (abc, 12abc) or out-of-range total is rejected and the lot is unchanged;
  • qty and acquired_on are not permitted;
  • a read-only member cannot edit;
  • the drawer lists lots only while they add up to the position.

Mutations (14, all caught): no merge; merge keeping the target's cost; either calculator ignoring the cost; dividing by the current quantity; no restatement; a negative total accepted; the opening lot editable; an unscoped lot lookup; no permission check; the drawer out of partition; unlock not clearing; lenient parsing.

Validation

  • Full suite at bf4cbb42b: 13521 runs, 62230 assertions, 0 failures, 0 errors, 36 skips.
  • bin/rubocop, erb_lint and bin/brakeman (0 warnings) are clean.

Migration notes

  • 20261024120000_add_manual_total_cost_to_holding_lots: one nullable column with a check, so it is metadata-only.
  • It is reversible and schema-only, with no backfill.
  • Verified: up, rollback, up on a scratch test database.

AGENTS.md

  • Code placement: logic in models; the controller is thin.
  • Design system: styled_form_with, money_field, DS::Disclosure and DS::Button, functional tokens only, and the icon helper.
  • Copy: every string goes through t() (holdings.lots.*, holding_lots.*).
  • Other: comments describe intent; screenshots above; commit subjects ≤72 characters, with no fork references.

Summary by CodeRabbit

  • New Features
    • Trade-enabled accounts can use average-cost or FIFO cost-basis methods.
    • Holdings can display acquisition lots with dates, quantities, and unit costs, including unknown-cost lots. Where editing is available, you can update a lot’s total cost basis or unlock a manually set cost.
  • Improvements
    • Realized gains reports can reflect the costs of specific lots sold when FIFO is selected.
    • Changing an account’s cost-basis method triggers a sync; saving the same method does not.
    • Cost-basis calculations account for trades, transfers, and stock splits.