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

Merged
JA
18d ago
+795-27

Part of #4449.

Replaces #4500, closed so the stack can be a native GitHub stack (heads in this repo). Its review history, including jjmata's threads and their answers, stays there.

What: a sale in a FIFO account can name the lot it sold from (specific identification), stored in a new trades.lot_source_entry_id. The lot book consumes the named lot first, then oldest first. A "Sold from lot" select appears in the sale drawer, offering only Trade#lot_choices. In a FIFO account the average-cost fallback becomes the mean of the position's open lots (Holding.fifo_avg_costs), batched for the holdings list.
Why: a user who sold a specific parcel (#4449's question 3) could not record it, so the gain and remaining cost were the wrong parcel's; and a linked FIFO account's current row showed the pooled average ($15.20) where FIFO's is $17.33.
Start reading: Trade#lot_choices (app/models/trade.rb), the named-lot handling in Holding::LotBook, then Holding.fifo_avg_costs and Holding.preload_avg_costs.
Key tests (test/models/holding_lot_disposal_test.rb, test/models/holding_test.rb, test/controllers/trades_controller_test.rb):

  • "naming the $20 lot realizes $200 and leaves $12 avg, forward and reverse"
  • "a sale can name only an earlier acquisition of its own security, in a fifo account"
  • "a named lot that is no longer open falls back to oldest first"
  • "a fifo row the lots cannot describe is unknown, not the pooled average"
  • "the batch answers a fifo holding from its open lots, in a fixed number of queries"

Behaviour change: FIFO sales gain the "Sold from lot" select in their drawer; average accounts ignore a named lot. A linked FIFO account's current row shows its open lots' mean. One migration: a nullable foreign key, nullified when the acquisition is deleted; reversible, no backfill.

Stack: 4 of 5 in the lot stack (slice 6 of #4449), on #4902. GitHub shows only this slice's diff. Next: #4904. Merge order: #4900 → #4901 → #4902 → #4903 → #4904 (slice 2, #4899, is merged).
Size: +181 / −20 outside tests.
Fork pre-flight: jaysbeekay/sure#604 (same commits, on the fork's copy of this branch). It ports the fork PRs jaysbeekay/sure#584 and jaysbeekay/sure#585.

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
Full description and evidence

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 (#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 #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).

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.

Summary by CodeRabbit

  • New Features
    • FIFO sales can be assigned to an eligible purchase lot. The selected lot is used first, followed by other lots in acquisition order; without a selection, sales use oldest-first ordering.
    • Trade details show eligible lot choices with each lot’s date, quantity, and price. Invalid selections, such as lots from another account, are rejected.
  • Bug Fixes
    • FIFO cost-basis figures now use available open-lot costs more consistently, including for pending holdings.
    • Holdings lists fetch cost-basis data more efficiently as the number of holdings grows.