Let a FIFO sale name its lot, and read open lots in the fallback (U6)

Draft
JA
16d ago
+795-27

Part of jaysbeekay/sure#551.

Upstream pre-flight for slice U6 of we-promise/sure#4449 (decision 19 on jaysbeekay/sure#551: U6 = PR 4 + PR 4b). The branch up/551-u6 is cut from up/551-u5 (jaysbeekay/sure#603), so the diff shows only this slice. It carries the current heads of jaysbeekay/sure#584 and jaysbeekay/sure#585, cherry-picked without their merge commits. Both have since merged on the fork, unchanged. Upstream PR: we-promise/sure#4903 (https://github.com/we-promise/sure/pull/4903), part of the native GitHub stack we-promise/sure#4905. It replaces we-promise/sure#4500, closed on 2026-11-11 so the stack's branches could all live upstream; that PR keeps the earlier review history. Same commits: the upstream PR's head is this branch's copy in we-promise/sure.

Adaptations from the fork commits, because upstream has no Holding.preload_avg_costs:

  • Code: Holding.fifo_avg_costs is kept for the Ruby fallback, and the preload half is dropped.
  • Tests: they assert the one path. The preload query-count test is removed, and two test names lose "in both paths".
  • Commit messages: fork references are removed, and the fallback commit's message is rewritten to match.

Problem

  1. A FIFO sale can't say which parcel it sold. Under FIFO a sale always takes the oldest lot first. A user who sold a specific parcel (we-promise/sure#4449's question 3) has no way to record that, so the realized gain and the remaining cost are those of the wrong parcel.
  2. A linked FIFO account's current row shows the average method's figure. Where the provider gives no cost, Holding#avg_cost falls back to the trades, and that fallback pools every purchase whatever the account's method. On we-promise/sure#4449's Example a linked FIFO account's current row reads $15.20 where FIFO's is $17.33, and $15.20 again with the $20 lot named, where it is $12.

What this changes

  • trades.lot_source_entry_id: a foreign key to entries, nullified when the acquisition is deleted. A sale in a FIFO account can name one of its earlier acquisitions as the lot it sold from.
  • The book consumes the named lot first, then the rest oldest first, and what is left of the named lot keeps its place in acquisition order. The disposals already stored per sale carry the result, so the gain reads back as for any FIFO sale: on the Example, naming the $20 lot realizes $200 and leaves $12, where oldest first gives $520 and $17.33.
  • Trade#lot_choices: buys and transfers-in of the same security in the same account that the replay applies before the sale (an earlier date, or the same date and entered first), leaving out lots that earlier sales had already emptied.
    • Only a sale (not a transfer out) in a FIFO account has any.
    • The choice a sale already holds always stays among them, so an edit keeps it.
    • The validation accepts only one of these.
    • A stored choice that names no open lot when the sale is replayed is skipped, and an average account ignores it.
  • A "Sold from lot" select in the sale drawer, shown only on a FIFO sale with choices. Saving it restates the account.
  • The FIFO avg-cost fallback: in a FIFO account, Holding#calculate_avg_cost answers the mean of the position's open derived lots, as Holding::LotBook#average_cost does.
    • The opening lot stays out, and an open lot with no cost makes the figure unknown.
    • It answers only for the position's latest row, and only while the stored lots add up to it (HoldingLot.in_partition); any other row is unknown rather than the pooled figure.

Not in this slice: naming a lot on the new-trade form or through the API, export and import (slice 7).

Screenshots

The drawer of a 40-unit sale in a FIFO account that holds a $12 lot and a $20 lot, with the $20 lot named. Rendered headless by a throwaway system test with fixture data. Before is slice 5'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?

  • Holding::LotBook#apply and #sell are called by both calculators, which now pass the named lot. Their transfer-out calls pass no sale id, so they are unchanged.
  • HoldingLotDisposal.readable_by_sale and Trade#calculate_realized_gain_loss already read the stored disposals, so they are unchanged.
  • Trade::CreateForm and Api::V1::TradesController build their own entryable attributes, so they don't accept the field. That is deliberate (slice 7).
  • Holding#avg_cost's fallback is reached for rows with no stored basis. An average account's path is unchanged.

Tests

  • test/models/holding_lot_disposal_test.rb:
    • a named lot is consumed first, and the rest oldest first;
    • the Example's $200 gain and $12 remainder;
    • an average account ignores a choice, and a stale choice falls back;
    • same-day choices follow the replay order: a buy entered after the sale is not offered, and one entered before it is;
    • lots emptied by earlier sales are not offered;
    • an edit keeps a held choice.
  • The FIFO fallback: $15.20 under average, unchanged; $17.33 under FIFO; $12 with the $20 lot named; an earlier row and lots out of partition are unknown; a sold-off transfer-in no longer blanks the figure.
  • test/controllers/trades_controller_test.rb: the drawer offers the choice only on a FIFO sale; naming a lot saves it and restates the account; another account's lot is refused.
  • Mutations: replacing < with <= in lot_choices, or dropping the validation's change guard, each fail a test. So do the fork's checks of the consumption order, the open-lots filter and the fallback's partition and latest-row guards.

Validation

  • Full suite at 8c7b700b4: 13550 runs, 62308 assertions, 0 failures, 0 errors, 36 skips. The head, c34444dc2, renames two tests only, and their file passes there (39 runs).
  • test/system/trades_test.rb: 4 runs, 0 failures.
  • bin/rubocop, erb_lint and bin/brakeman (0 warnings) are clean.

Migration notes

  • 20261024140000_add_lot_source_entry_to_trades: a nullable uuid reference with a foreign key to entries, on_delete: :nullify, and its index.
  • It is reversible, with no backfill.

AGENTS.md

  • Code placement: model logic. The controller permits one attribute.
  • Design system: the select is the styled form builder's own.
  • Copy: strings go through t().
  • Other: screenshots above; a current-version migration with notes; commit subjects ≤72 characters, with no fork references.