Add a fifo cost basis method and its account setting

Closed
JA
25d ago
+824-40

Part of #4449.

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

In short. Adds a per-account cost basis method (average, the default, or fifo). FIFO sales relieve the oldest lots, and each disposal is stored. Look first: Holding::LotBook, HoldingLotDisposal, Account::Syncer (restates on a method change). Check: bin/rails test test/models/holding_lot_disposal_test.rb; the account form's new setting is in Screenshots.

Fork pre-flight: jaysbeekay/sure#601 (https://github.com/jaysbeekay/sure/pull/601), which holds this slice's CI and review history. Same branch, same commit. It ports the merged fork PRs jaysbeekay/sure#580 (the method and disposals) and jaysbeekay/sure#581 (the account setting), whose review history is there too.

Size: about 305 non-test lines, slightly over the usual guide. The method and its setting ship together so that the slice doesn't add a method nobody can select.

Problem

A sale is always measured at the position's blended average. Under any other method that figure is wrong, because the snapshot after a sale holds the mean of what remains, not the cost of what was sold. On #4449's Example (60 bought at $12, 40 at $20, then 40 sold at $25), the FIFO basis is 40 × $12 = $480. The snapshot after the sale says $17.33 a share, which gives $693.33.

What this changes

  • accounts.cost_basis_method {average, fifo}, default average, with a check constraint. Every existing account keeps average, and its figures are unchanged.
  • holding_lot_disposals: one row per lot a sale took from. It holds the sale's entry, the consumed lot's source entry (nil for the opening lot and for units sold beyond what was held), the qty, the unit cost and the currency.
  • Holding::LotBook takes the method.
    • Under fifo a sale consumes the oldest open lot first and records a disposal for each lot it touches.
    • average_cost becomes the mean of the open lots a trade acquired. The opening lot stays out, as it stays out of the pool.
    • A transfer-in stops making the position unknown once its lot has been sold.
    • Under average the book records nothing and behaves exactly as before.
  • Both calculators build their books with the account's method. The materializer stores the disposals, filtered to security_ids on a scoped run.
  • Trade#realized_gain_loss reads the stored disposals when the account sells by fifo and the record covers the whole sale. A consumed lot with no cost makes the gain unknown. Without a covering record it reads the snapshot exactly as before, and the proceeds conversion is unchanged.
  • Partition guard. Before reading disposals, HoldingLotDisposal.readable_by_sale checks that the position's open lots equal the holding's latest quantity (HoldingLot.in_partition). Otherwise the trade falls back to the snapshot. After an unlink, a forward sync keeps opening lots it cannot rebuild, and this is the state the guard keeps out.
  • The reports card preloads each sale's disposals beside its holdings: one disposals query for the whole set, and none when no account sells by fifo.
  • A "Cost basis method" select (Average cost / First in, first out (FIFO)) on the edit form of an account that supports trades, with a hint. All strings go through t().
    • Changing the method starts a sync, which restates the stored figures. Resubmitting the same method starts none.
    • A change made while a sync is already running is restated afterwards: Account::Syncer records the method each run used, and post-sync starts another sync if it has changed since.
    • The shared update path drops the method for an account without trades, judged after the subtype in the same submission is applied. create drops it too: a new account starts on average.
MethodBasis of the 40 soldRealized gainRemaining avg
average$608$392$15.20
fifo$480$520$17.33

Not in this slice: the lot cost editor (U4), named-lot selection (U6), and counting the opening lot in the mean.

Screenshots

Edit investment account, rendered headless by a throwaway system test with fixture data. Before is slice 2'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?

  • LotBook.new is called by the two calculators, which now pass method:.
  • The reverse calculator now records a cost-basis snapshot after a transfer-in. Under average it repeats the previous figure, and slice 1's byte-identity test still passes.
  • Trade#calculate_realized_gain_loss is reached from the reports card (which preloads) and from a single trade.
  • AccountableResource#update serves every account type's controller, and accounts/_form is rendered by every type's form. A non-trade account never shows the select and drops the param (tested on a depository).

Siblings:

  • basis_holding is kept as the fallback.
  • Holding#calculate_avg_cost is unchanged: it serves rows with no stored basis, and answers nil where an open lot's cost is unknown.
  • cost_basis_unknown passes through Gapfillable unchanged.
  • Disposals are keyed by sale entry, so a sale moved to another security is restated with it.
  • Family::DataExporter exports account.as_json, so the new column is exported.

Tests

  • test/models/holding_lot_disposal_test.rb (new):
    • the Example under both methods;
    • a sale crossing two lots;
    • average unchanged;
    • the persisted consumption beating the post-sale snapshot;
    • a foreign-currency lot (basis at the acquisition-date rate, proceeds at the sale-date rate);
    • a missing sale-date rate;
    • a sale consuming the opening lot;
    • a scoped materialization;
    • the partition guard both ways, with a control: an unlink then a forward sync falls back, lots in partition are read, and lots short of the holding fall back;
    • book-level oldest-first, shortfall, average and transfer-in cases.
  • test/controllers/reports_controller_test.rb: the card reads two FIFO sales' disposals in one query and shows the oldest-lot gain ($130).
  • investments_controller_test.rb:
    • changing the method starts one sync, and resubmitting starts none;
    • an unknown method gets a 422;
    • the select appears only on accounts that trade;
    • a depository ignores the method;
    • a new account starts on average.
  • cryptos_controller_test.rb: an exchange↔wallet switch in the same submission.
  • account/syncer_test.rb: a method changed mid-sync starts one more sync, with the unchanged control.
  • Mutations: 18 on the model side and 10 on the setting, all caught. The reports preload was checked both ways at this head: without it, 2 queries; with Trade ignoring it, 3.

Validation

  • Full suite at 08b8c1cd7 (the tree it ran on, before a commit-message-only rewrite): 13504 runs, 62152 assertions, 0 failures, 0 errors, 36 skips.
  • test/system/accounts_test.rb (headless Chromium): 9 runs, 0 failures.
  • bin/rubocop, erb_lint and bin/brakeman (0 warnings) are clean.

Migration notes

  • accounts.cost_basis_method is added with a constant default, which is metadata-only on PG 11+.
  • holding_lot_disposals is a new, empty table.
  • Both migrations are schema-only and reversible, with no backfill. Disposals come from the next materialization, and only for accounts set to fifo.
  • Verified: up, db:rollback STEP=2, up on a scratch test database.

AGENTS.md

  • Code placement: model logic. The controller adds a param guard and a sync call.
  • Design system: the select is the styled form builder's own, and the hint uses text-secondary. No new styles.
  • Copy: strings go through t().
  • Other: screenshots above; current-version migrations with notes; commit subjects ≤72 characters, with no fork references.

Summary by CodeRabbit

  • New Features
    • Investment and crypto accounts can use average-cost or FIFO cost-basis methods, with average cost as the default.
    • Eligible existing accounts include a setting to choose the cost-basis method.
    • FIFO sales can show realized gains based on the purchase lots matched to each sale.
    • Holdings track acquisition lots and sale allocations, including transfers and stock splits.
    • Changing an account’s cost-basis method updates its calculated holdings and gains.
  • Improvements
    • Reports load lot-based sale details more efficiently when showing multiple sales.