Report lots in the API and assistant, and carry them through export

Merged
JA
1mo ago
+529-10

Part of jaysbeekay/sure#551. This is PR 5, the last slice of the stack (PR 3 #582 ← PR 3b #583 ← PR 4 #584 ← PR 4b #585 ← PR 5). It is stacked on #585, so its base is feat/551-lot-basis-pr4b-fifo-fallback and the diff shows only this slice. It is retargeted down the stack as the lower slices merge.

Problem

The lots exist in the app but reach nothing outside it:

  • The API and the assistant report a holding's average cost but not the lots behind it.
  • The trades API omits the lot a FIFO sale names to sell from.
  • An export carries none of what the user set: a lot's cost, the lot a sale names, or, on import, the account's cost method. A round trip through export and import loses all three.

What this changes

api/v1/holdings gains lots:

  • Where it appears: on a position's latest row, while its stored lots add up to the holding. Any other row gets null, since the lots are the position as it stands.
  • Each lot carries: id, opening, acquired_on, qty, a formatted unit_cost, manual_cost, and the acquiring trade's id.
  • Query cost: Holding.open_lots_for reads a whole page in four queries. Holding.fifo_avg_costs (#585) now builds on it, rather than repeating the latest-row and partition checks.

api/v1/trades gains lot_source_trade_id. It applies only while the account sells by FIFO; an average account keeps the stored choice but ignores it (owner decision 17).

get_holdings (assistant) returns the same lots and describes them in its tool text. It now preloads its average costs in one batch (Holding.preload_avg_costs), so its figure is the drawer's without a query per holding.

Export and import:

DataExportImport
A lot's user-set costlot_total_cost on the acquiring trade's recordSeeds the lot row, which the next sync keeps
A sale's named lotlot_source_trade_id on the sale's recordRestored as stored
The account's cost methodAlready in the account recordNow read back; a file without it leaves the account's own
  • Order: trades are written oldest first, with buys before sales on a day. A named lot is therefore always ahead of its sale, and a later chunk of a session import finds it by the trade's session external id.
  • A named lot that can't be used: it must be an earlier acquisition of the same security in the same account, or a buy on the same day. Anything else is dropped and counted as skipped, and in a session import it raises.
  • A cost that can't be used: a non-numeric or negative total, or a cost on a sale, is handled the same way. The trade still imports, and so does the rest of the file.
  • Re-import: a re-import without a cost or a name clears the earlier one.

Screenshots: none. No view changes.

API response

GET /api/v1/holdings/:id for the #551 Example's current row (60 at $12, then 40 at $20); ids omitted:

   "avg_cost": "$15.20",
+  "lots": [
+    { "opening": false, "acquired_on": "2024-01-10", "qty": "60.0", "unit_cost": "$12.00", "manual_cost": false, "trade_id": "<trade id>" },
+    { "opening": false, "acquired_on": "2024-01-15", "qty": "40.0", "unit_cost": "$20.00", "manual_cost": false, "trade_id": "<trade id>" }
+  ]

Blast radius

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

  • fifo_avg_costs: reached from Holding#calculate_avg_cost and Holding.preload_avg_costs. It now reads through open_lots_for and drops the opening lot itself. #585's tests, all passing, pin it.
  • Family::DataImporter#import_trades: reached from SureImport and session imports. It now seeds lot costs and resolves named lots after the trade loop.

What else reads what changed (siblings):

  • Holding#open_lots (the drawer) keeps its own single-position read. Every link to the drawer opens a position's latest row.
  • SureImport's type list is untouched, because no new record type is added.
  • HoldingLot.store! never writes manual_total_cost, so a seeded cost survives the next sync.

Tests

  • API holdings (test/controllers/api/v1/holdings_controller_test.rb):
    • a position's current row lists its open lots, oldest first
    • units held before the first trade are listed as the opening lot, first
    • an earlier row, or a position its lots do not add up to, has null lots
    • listing holdings reads lots in the same number of queries however many positions
  • API trades: a sale that names its lot reports the acquiring trade, in show and index.
  • Assistant (test/models/assistant/function/get_holdings_test.rb, new):
    • get_holdings average_cost equals the drawer figure (a FIFO position, $17.33)
    • lots oldest first
    • no lots out of partition
  • Import (test/models/family/data_importer_test.rb):
    • the round trip
    • a named lot kept through a switch to average
    • sale and lot in separate chunks of a session
    • seven unusable costs or names, each checked against what a clean import holds
    • a session import raising on one
    • re-import keeping the method and clearing a dropped cost or name

Evidence

Code review before commit. /code-review ran over the whole slice before the export/import part was committed. It found eight issues; none scored 80, and six were real. All six are fixed:

  • a named lot that couldn't be restored failed the whole import;
  • a link was dropped across session chunks;
  • a file without a method reset an existing FIFO account;
  • lot costs weren't parsed strictly;
  • the trades API docs overstated when the field applies;
  • a re-import left stale values.

The two declined:

  • an opening lot's cost isn't exported, but nothing can set one;
  • the drawer and the API differ on an earlier row, by design.

A second review of the strengthened tests led to per-case checks and to the same-day ordering case.

Fail first. Each new test failed before its change:

  • missing lots key or field;
  • undefined method 'map' for nil;
  • the import raising RecordInvalid;
  • Expected "fifo".

Mutations (21, all caught):

AreaMutations
open_lots_forlatest-row check, partition check, opening-first order
FIFO fallbackthe opening lot counted
API viewsper-row refetch in the index; the trade field
Assistantthe lots dropped
Account importmethod ignored; method reset
Lot cost importno clear on blank; no qty guard; lax to_d parse
Named lot importvalidated update!; no eligibility check; no date rule; no security rule
Exportunordered; no buys-first tie-break

Full suite at e0f7332d2: 14432 runs, 66991 assertions, 0 failures, 0 errors, 38 skips. The later commit changes only data_importer_test.rb, and its 6 lot tests pass. bin/rubocop and bin/brakeman (0 warnings) are clean. docs/api/openapi.yaml is regenerated, keeping only this slice's hunks; the generator's unrelated line rewrapping is left out.

AGENTS.md

I checked the change against the current we-promise/sure AGENTS.md:

  • API: Minitest behavioural coverage, with docs-only rswag schemas in spec/swagger_helper.rb and the regenerated openapi.yaml.
  • Code placement: models, jbuilder views and one controller includes.
  • Performance: no N+1, held by a test.
  • Migrations, UI: none.
  • Commits: every subject is ≤72 characters.

Summary by CodeRabbit

  • New Features
    • Holding details now include open investment lots with acquisition dates, remaining quantities, unit costs, and indicators for opening lots and manually entered costs. Lot details are shown when they reconcile with the holding.
    • Trade data now identifies the source trade for a sale when one is assigned.
    • Investment data exports and imports now preserve manual lot costs and sale lot selections. Imports validate lot information and retain existing cost-basis settings when the exported setting is absent.