Let a FIFO sale name the lot it sold from

Merged
JA
1mo ago
+436-16

Part of jaysbeekay/sure#551. This is PR 4 of the stack (PR 3 #582 ← PR 3b #583 ← PR 4 ← 5; owner decisions 3(a) and 17). #583 has merged, so its base is now main; #585 is stacked on it.

Problem

A sale can only be measured against the lots the account's method picks. Under FIFO that is the oldest first, so a user who sold a particular parcel cannot say so. On the #551 Example (60 bought at $12, 40 at $20, then 40 sold at $25), FIFO realizes $520 and leaves $17.33. If the sale was the $20 parcel, the answer should be $200 realized and $12 left, and today nothing can express that.

What this changes

  • Where the choice is made: a FIFO account's sale gets a "Sold from lot" select in its drawer (decision 17).
    • Choices offered: the account's buys and transfers-in of the same security, dated on or before the sale. "Oldest first" is the blank option.
    • Linked sales: the select stays editable on a provider-linked sale, because it is the user's choice, not provider data.
    • Restate: saving it restates the account through the existing sync_account_later.
  • Storage: trades.lot_source_entry_id, a foreign key to entries that is nullified when the acquisition is deleted. Trade#lot_choices defines what a sale may name. A validation refuses anything else: another account's lot, another security's, a later acquisition, another sale, a choice on a buy or a transfer out, or one in an average account.
  • Holding::LotBook#sell under FIFO:
    • Named first: the named lot is consumed first and the rest oldest first.
    • Remainder: what is left of the named lot keeps its place in acquisition order, so the next unnamed sale still takes the oldest.
    • No open lot: a name that matches no open lot (consumed earlier, or the sale's date moved) is skipped.
    • Average: an average book ignores the name.
  • Both calculators pass the sale's choice to the book. The disposals PR 2 stores carry the result, so the realized gain reads back with no change to Trade or HoldingLotDisposal.

Not in this PR, and why:

  • The new-trade form (decision 17). A choice there would need a lot list that reloads whenever the ticker changes, and the form only creates manual trades.
  • The API, export and import. They join PR 5's surfaces. Api::V1::TradesController and Trade::CreateForm build their own attributes, so neither accepts the field.
  • A gap found while testing, fixed in its own slice, #585 (owner decision 18; it predates this PR). On a linked FIFO account, when the provider's current row carries no cost, Holding#avg_cost falls back to the trades' pooled average.
    • Effect: on the Example the current row reads $15.20 where FIFO's figure is $17.33, with or without a named lot.
    • Unaffected: the dated rows the calculators write are right ($12 with the $20 lot named).
    • Cause: the fallback ignores the method, as it has since PR 2.

Only lots still open are offered (owner, 2026-10-25; amends decision 17). An acquisition whose stored lot earlier sales had already emptied is left out of the "Sold from lot" list, and the validation rejects naming it. A lot this sale, or a later one, emptied was still open on the sale's date, so it stays offered. The choice a sale already holds always stays offered, so an edit keeps it. Opening lots have no acquisition and are not read: an empty one, which a clamp records, no longer clears the list.

Screenshots

The sale's drawer in a FIFO account after selling 40 of 100 units. The before shots are from #583's head and the after shots from this PR, both rendered headless by a throwaway system test on the test containers, with fixture data.

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

Blast radius

Who else hits these lines, and what do they pass?

  • LotBook#apply / #sell: called only from the two calculators. Both pass the trade's choice. Their transfer-out calls pass no sale id, so they are unchanged.
  • TradesController#update: every drawer form posts here. The new form posts only entryable_attributes[id, lot_source_entry_id], so the qty/price branch of update_entry_params is not reached. The validation runs only when the choice changes, so an edit to a sale's date or quantity is never refused because of a choice it already holds.

What else reads what changed (siblings):

  • Realized gain: HoldingLotDisposal.readable_by_sale and Trade#calculate_realized_gain_loss read the stored disposals, so they pick up the named lot unchanged.
  • Remap and reset re-key lots by source entry. The choice is an entry id, which survives a remap. A sale that moves to another security names a lot of the old one, which is no longer open, so the book skips it.

Tests

The bracket says what each assertion catches.

test/models/holding_lot_disposal_test.rb:

  • under fifo a sale naming a lot consumes it first, then the oldest [disposal order and quantities].
  • what is left of a named lot keeps its place, so the next sale still takes the oldest.
  • under average a named lot is ignored [pro-rata lots, $15.20].
  • naming the $20 lot realizes $200 and leaves $12 avg, forward and reverse [$520 before naming, $200 after; $12 left].
  • naming a lot larger than its open qty consumes the rest by the account method [$590: 40 x $20, then 30 x $12].
  • a named lot that is no longer open falls back to oldest first [$260].
  • an average account ignores a named lot [$392 and $15.20; no disposals].
  • naming another account's lot is rejected.
  • a sale can name only an earlier acquisition of its own security, in a fifo account [a later lot, another security's, another sale, a buy, a transfer out, an average account].
  • deleting the named acquisition clears the choice [the FK nullifies].

test/controllers/trades_controller_test.rb:

  • the drawer offers the lot choice only on a fifo sale [none on an average sale or a buy].
  • naming a lot on a sale saves it and restates the account [stored, SyncJob enqueued].
  • naming another account's lot on a sale is refused [422, unchanged].

Open lots only (ac1c1adde, test/models/holding_lot_disposal_test.rb):

  • a sale is offered only the lots still open on its date: an earlier sale's emptied lot is left out, and a crafted submit naming it is rejected.
  • a sale's held choice stays offered once its lot is sold out.
  • an empty opening lot leaves the sale's choices alone.

Pre-commit review: one reviewer found that an opening lot's NULL source id in the exclusion emptied the whole list, and that the validation accepted a newly named sold-out lot. Both are fixed and tested. Mutations (5, all caught): no filter; opening lots read; the new value kept as "held"; the held choice dropped; same-day disposals ignored. Full suite at ac1c1adde's parent run: 14417 runs, 66946 assertions, 0 failures, 0 errors, 38 skips. The amend changed only the test.

Evidence

Fail first. On #583's head (1e3d515b1), all 12 first-written tests fail for the expected reasons: an unknown lot_source_id keyword, an unknown lot_source_entry attribute, no select, and a redirect where 422 is expected. The two tests added afterwards are proven by M2 and M11.

Migration: run, rolled back and run again on the test containers. The dumped schema matches the committed schema.rb; the only differences are the PG16 check-constraint spellings already seen on #582.

Mutations (15, all caught):

#MutationCaught by
M1the book ignores the namebook, Example and larger-than-lot tests
M2the named lot's remainder moves to the frontkeeps-its-place test
M3the forward calculator drops the nameExample, larger-than-lot tests
M4the reverse calculator drops the nameExample test (reverse)
M5no validationboth rejection tests, controller refusal
M6no date filterearlier-acquisition test
M7no security filterearlier-acquisition test
M8no buy filterearlier-acquisition test
M9no FIFO gateearlier-acquisition test, drawer test
M10no sale gateearlier-acquisition test, drawer test
M11no transfer-out gateearlier-acquisition test
M12not scoped to the accountboth other-account tests
M13the param not permittedsave test, refusal test
M14the select shown without choicesdrawer test
M15the FK without on_delete: :nullifydelete test

Full suite at the committed code: 14409 runs, 66913 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:

  • Code placement: business logic in models (Trade#lot_choices, the validation, LotBook), with the controller change limited to one permitted param.
  • UI: the select is the form builder's styled select, with a scale token only. Every string goes through t() (trades.show.lot_label, lot_oldest_first, lot_option).
  • Migration: one reversible migration at the current version (8.1). It adds a nullable column with an index and FK, so no backfill is needed.
  • Comments: intent only.
  • API: none.
  • Commit: the subject is ≤72 characters.

Summary by CodeRabbit

  • New Features
    • FIFO sales can now be assigned to a specific eligible acquisition from the trade details. If no lot is selected—or the selected lot is unavailable or insufficient—remaining shares follow the existing oldest-first order.
    • Trade details show eligible lots by date, quantity, and price; lot selection saves automatically.
    • Average-cost calculations remain unchanged by lot selection.