Let a FIFO sale name its lot, and read open lots in the fallback
Part of #4449.
Slice 6 (U6) of the per-lot cost basis series that #4449 proposes. Depends on #4499 (slice 5, the clamp), which depends on the slices before it. This PR targets up/551-u5 (the branch of #4499, pushed to this repo at the same commit as the fork's), so Files changed shows this slice alone. Merge bottom-up: once #4499 is in main, I retarget this PR to main and merge main down. Merged before #4499, it would land in up/551-u5 rather than main.
In short. A FIFO sale can name the lot it sold (specific identification), and a FIFO holding's fallback cost is the mean of its open lots, batched for the portfolio page and the holdings list. Look first: Trade#lot_choices, Holding.fifo_avg_costs, Holding.preload_avg_costs. Check: bin/rails test test/models/holding_lot_disposal_test.rb test/models/holding_test.rb test/controllers/holdings_controller_test.rb; the lot picker is in Screenshots.
Fork pre-flight: jaysbeekay/sure#604 (https://github.com/jaysbeekay/sure/pull/604), which holds this slice's CI and review history. Same branch, same commit. It ports the fork PRs jaysbeekay/sure#584 (a named lot on a sale) and jaysbeekay/sure#585 (the FIFO avg-cost fallback), whose review history is there too.
Problem
- 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.
- A linked FIFO account's current row shows the average method's figure. Where the provider gives no cost,
Holding#avg_costfalls 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 toentries, 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_costanswers the mean of the position's open derived lots, asHolding::LotBook#average_costdoes.- 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.
| Before | After | |
|---|---|---|
| Desktop (1400px) | ![]() | ![]() |
| Phone (390px) | ![]() | ![]() |
Blast radius
Who else hits these lines, and what do they pass?
Holding::LotBook#applyand#sellare 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_saleandTrade#calculate_realized_gain_lossalready read the stored disposals, so they are unchanged.Trade::CreateFormandApi::V1::TradesControllerbuild 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<=inlot_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_lintandbin/brakeman(0 warnings) are clean.
Migration notes
20261024140000_add_lot_source_entry_to_trades: a nullable uuid reference with a foreign key toentries,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
- Choose average-cost or FIFO accounting for eligible investment accounts; changing the method recalculates past realized gains and current average cost.
- View acquisition lots, including dates, quantities, and unit costs, on holdings when lot quantities match the position.
- Set or unlock a lot’s total cost to correct its cost basis.
- For FIFO sales, choose a specific acquisition lot or use the oldest available lot first.
- Realized-gain reports reflect the cost of shares matched to each sale.



