Skip to content

Inventory Flow tab: backdate edits so every column adds up (builds on #5313) - #5730

Open
awwaiid wants to merge 31 commits into
mainfrom
inventory-flow-backdated
Open

awwaiid wants to merge 31 commits into
mainfrom
inventory-flow-backdated

Conversation

@awwaiid

@awwaiid awwaiid commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Builds on #5313 (Resolves #5249). This branch contains #5313's commits plus one more. #5313 comes from a fork, so this PR is based on main.

This implements (and re-works previous implementation) a better inventory-flow tab for a storage location and date range. It uses the event log from the "now" perspective -- meaning if there were retroactive edits then those edits show up when we view an earlier window of time.

I did actual benchmarks using prod data to validate that this performs good enough as an in-memory generation (thereby simplifying away some complex SQL from a previous attempt).

Also:

  • The date range now goes through the shared DateRangeHelper#selected_range
  • The query returns rows and totals separately instead of copying the totals into every row.

Verification on a production snapshot

  • 0 of 455 quarterly windows break start + change = end (65 storage locations across the 15 busiest orgs).
  • 0 of 65 locations differ between end quantity (for a window ending today) and the current inventory.
  • Timing on the busiest location of each of the top 6 orgs, last 30 days: 306–680ms (the app itself loading/rendering takes more time than that)

Snapshots

Inventory history starts at the bank's first snapshot, on both tabs:

  • Inventory Flow: a range can't start before the first snapshot (the picker stops there, and an earlier start is treated as the snapshot, with a note under the table). Later snapshots don't change what the report can see: the replay passes through them, and if one disagrees with the replayed quantities the difference shows in Adjustment/Audit (normally zero). Edits are still backdated "as of now"; a later snapshot already blocks edits to records from before it.
  • Inventory tab ("Show Inventory at Date"): the earliest date is the first snapshot's date. The old fallback to InventoryItem PaperTrail history for earlier dates is removed; an earlier date shows the current inventory with a notice. Dates between the first and a later snapshot now show the right inventory (they used to show current inventory).

Notes for reviewers

  • The date range filters by when things were recorded (event time), not by the donation or distribution's own date. This matches the rest of inventory history.
  • The Flow tab loads in a lazy turbo frame, so the show page only runs the second replay when someone opens that tab.

Example from prod-clone data:
image


Update from brocks-claude-code (2026-11-22): merged main; history now starts at the first usable snapshot (InventoryAggregate.inventory_for(..., from_first_snapshot: true), Event.usable_snapshots, Event.history_start); removed the PaperTrail fallback; Event.usable_snapshots now only looks at the organization's own events (another org's edits could disqualify a snapshot); and the "version date" request specs now check the table quantity (they had been passing because "100" appeared in an asset digest).

Olexii Kasianenko and others added 17 commits September 22, 2025 18:14
…e related specs for accurate quantity calculations
Validating against a production snapshot showed the flow tab's numbers
diverging from inventory by millions of units. Three causes:

1. Editing a donation/purchase/distribution/transfer/adjustment
   republishes the full event for the same eventable, and inventory
   replay diffs against the previous version - but the query counted
   every version at full value. Dedupe to the latest version per
   eventable (destroy events publish zeroed items, so destroyed records
   net to nothing and drop out).

2. Kit allocation/deallocation events were not counted at all. On the
   heaviest production location that is 1.6M items consumed into kits
   that the tab silently omitted. They now flow like any other event
   (each row applies in full, matching InventoryAggregate).

3. Audits record the absolute counted quantity, not a delta, so the tab
   showed e.g. 'audited at 5000' as 5000 in. Audit contributions are now
   computed as deltas via a single replay pass through the event log.

Also collapse the per-type to/from conditions (which had and/or
precedence bugs) into generic to/from matching over an explicit list of
flow event types, filter by event_time rather than created_at to match
replay semantics, drop all-zero rows, and move totals to Ruby.

With these fixes, snapshot + in - out reconciles with current inventory
to within a few hundred units over multi-year windows moving 7M+ units
on production data (residuals trace to UpdateExistingEvent group
handling quirks), and the page renders in under a second on the largest
production org.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BNy2e1J81K8xbvXraCeN8e
The flow tab now shows, per item: Quantity at Start, Quantity In,
Quantity Out, Quantity Adjustment/Audit, Quantity Change, and Quantity
at End, so each row self-validates (start + in - out + adjustment =
end) and users can see stock levels bracketing the flows.

- Start/end quantities come from raw InventoryAggregate state at the
  window boundaries (View::Inventory prunes inactive items, so the raw
  aggregate is used instead)
- Adjustments move out of in/out into the combined adjustment/audit
  column, netted with their signed quantities; audit deltas land there
  too. The audit replay pass now doubles as the window-end state
  computation, so the whole page needs only two replays
- The effective window start is clamped to just after the organization's
  most recent usable snapshot: inventory state cannot be derived from
  events before it, and unclamped ranges silently double-counted
  pre-snapshot events against the snapshot baseline
- Rows appear when they have flow activity or a start/end difference

Validated against a production snapshot: row identity holds for all but
1-7 rows per organization (rare event-correction corner cases in
aggregate diff ordering, off by tens of units against multi-million
unit flows), totals reconcile start to end, and the page renders in
under a second on the largest organizations.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BNy2e1J81K8xbvXraCeN8e
ItemsFlowQuery now replays the inventory once, records the change each
event made at the storage location, and attributes it to when the record
was first created. Edits and deletions are therefore reported "as of now"
on the record's original date, and start/end quantities are computed from
the same changes, so start + in - out + adjustment always equals end and a
window ending today matches the Inventory tab.

Previously the in/out columns counted the latest version of a record at
the time of its last edit while start/end came from separate replays, so
any edited or deleted record made the columns disagree (38% of rows on a
production snapshot).

Also: use the shared DateRangeHelper range (handles bad input and matches
what the picker displays), return rows and totals separately, and remove
the unused line_item_row partial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSmvTcnvvTEKz5CmX9kNm8
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSmvTcnvvTEKz5CmX9kNm8
@awwaiid
awwaiid requested a review from dorner September 27, 2026 19:16
Comment thread app/queries/items_flow_query.rb Outdated
ADJUSTMENT_TYPES = %w[AdjustmentEvent AuditEvent].freeze
# These events stand alone rather than being a version of their record, so
# their changes stay at their own event time.
STANDALONE_TYPES = %w[KitAllocateEvent KitDeallocateEvent AuditEvent UpdateExistingEvent].freeze

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wonder if we should have a method on the event indicating editable? or something similar. I think this crops up in at least one more place.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, and then like if it is before a snapshot or depending on the type we'd get false?

Comment thread app/queries/items_flow_query.rb Outdated
end_qty = end_quantities[item_id]
next if flow.values.all?(&:zero?) && start_qty.zero? && end_qty.zero?

{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we make this a Struct / Data class?

Comment thread app/queries/items_flow_query.rb Outdated
# end quantities are then the current quantity minus the changes attributed
# after those times, so start + change always equals end.
class ItemsFlowQuery
Result = Struct.new(:rows, :totals)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Data instead of Struct?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/me refreshes data-vs-struct

sure!

Comment thread app/queries/items_flow_query.rb Outdated

# Replays the inventory, recording the change each event made to each item
# at this location.
# @return [Array(Hash<Integer, Integer>, Array<Change>)] current quantities and changes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like the logic is complex enough to extract some actual data classes here... I'd probably consider almost any data structure that uses bare integers/strings as a code smell for this use case. E.g. lines 93-94 seem like they're just different ways of getting data into / out of a collection, maybe we introduce one that automatically merges the data when you insert it? Not a desperate need, but anything we can do to make the flow simpler / easier to follow would help here.

Comment thread app/queries/items_flow_query.rb Outdated
# Nets each record's changes (so an edited donation counts once, at its
# latest quantity) and sorts them into in, out and adjustment.
# @return [Hash<Integer, Hash>] item_id => {in:, out:, adjustment:}
def window_flows(changes)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually window implies that it's moving or that there are multiple windows... maybe rename this to flows_in_range?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah I like that, window was annoying me a little too. "view" almost comes to mind but that is taken :)

Comment thread app/queries/items_flow_query.rb Outdated
elsif net.positive?
flow[:in] += net
else
flow[:out] -= net

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

more data classes here 😂

Comment thread app/queries/items_flow_query.rb Outdated
# Current quantities with the changes attributed to the selected times undone.
# @yieldparam time [Time] when a change is attributed to
# @return [Hash<Integer, Integer>] item_id => quantity
def quantities_without(current, changes)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the reason this isn't a filter because we don't know how to associate which event to which time yet (it depends on when it was edited)?

Seems like ideally we do that calculation first and then we can filter this out proactively instead of after the fact.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correct -- the idea is to show the post-edited data from a given time-range. I'll see how I can simplify this.

awwaiid and others added 10 commits October 24, 2026 11:41
Addresses review feedback on ItemsFlowQuery:

- Result and Row are now Data classes; Row computes change and
  quantity_end, and the totals row is a Row too.
- Event#versioned? replaces the STANDALONE_TYPES list. KitAllocate,
  KitDeallocate, Audit and UpdateExisting events return false.
  InventoryAggregate uses the same method to decide which events are
  diffed against the previous version of their record.
- The replay collects each record's changes in a RecordChanges object
  that merges the items each version touches, instead of parallel
  first_seen/touched_by hashes.
- Start, in/out/adjustment and end are built by filtering each item's
  changes by when the record was created (before vs. within the range),
  rather than undoing changes from the current quantity. Results are
  unchanged.
- window_flows is gone (its job is now in build_row), which also covers
  the rename suggestion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A1Q6b5q6YnqkjpKs7VcK19
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A1Q6b5q6YnqkjpKs7VcK19
…-selected

- RecordChanges#touch now returns the current and previous version's
  items instead of every item any version touched, so a record with many
  edits doesn't recheck items removed long ago. This matches what
  InventoryAggregate diffs against.
- aria-selected follows whichever tab is active, so it is correct when a
  date range filter opens the Inventory Flow tab.
- Specs for successive item replacements, an edit that moves a donation
  to another storage location, and the selected tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A1Q6b5q6YnqkjpKs7VcK19
…table?

- The replay starts at the organization's most recent usable snapshot, so
  nothing is known before it. A range that starts before the snapshot now
  leaves Quantity at Start and Quantity Change blank and counts in/out/
  adjustment from the snapshot on; a range entirely before it has no rows.
  A note under the table says when the inventory history begins.
- Add a note that edits and deletions are counted on the date the record
  was first entered, so past quantities can differ from the Inventory tab.
- The flow table now loads in a lazy turbo frame from a new
  inventory_flow member action, so the show page no longer runs a second
  inventory replay unless someone opens the Inventory Flow tab.
- A tab=flow param selects the Inventory Flow tab, and each tab's form
  carries the other's filter (version_date / date range) so submitting one
  no longer clears the other. Clear Filters stays on the flow tab.
- Rename Event#is_edit? to editable?: it is true for the first version of a
  record as well as later edits.
- Sort rows by name case-insensitively, replace the numeric row id with
  data-item-id, fix the tabs' aria-controls/aria-labelledby, and document
  that UpdateExistingEvent edits are dated when made.
- Fix the system spec's link assertions, which looked up a missing :name key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014FSHhMV2oCu9RE8hpg29ey
- Date range bucketing: records before the range go into the start
  quantity, records in it into in/out, later records are left out, and the
  totals row and negative-change styling render.
- A range straddling the snapshot renders blank start/change cells and the
  history note with the snapshot's date.
- An invalid date range falls back to the default range.
- The show page doesn't run ItemsFlowQuery (the frame loads it lazily).
- Clear Filters stays on the flow tab and keeps the inventory date.
- Signed-out requests to inventory_flow redirect to sign in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014FSHhMV2oCu9RE8hpg29ey
…ings

- Item links in the flow table navigated the turbo frame instead of the
  page, replacing the table with "Content missing". Target _top on the
  frame, with a system spec that clicks a link.
- A malformed filters param (?filters=x) raised a 500 on the storage
  location page and anywhere else the date range picker is used.
  DateRangeHelper now ignores a non-hash filters param, and the show
  page's tab and date range filters are computed in the controller.
- SnapshotEvent#editable? is false, matching the doc comment.
- Look up item names through the organization's items, and render a
  missing item's name without a broken link.
- Compare event classes with is_a? instead of type strings.
- System spec compares whole rows and totals (the old substring matches
  passed with the wrong numbers), and checks the filter keeps the tab.
- Query specs for a transfer seen from the receiving location, kit
  deallocation, legacy UpdateExistingEvent edits, distribution/transfer/
  purchase destroys, and a multi-month history that must add up per row,
  chain month to month, and end at the current inventory.
- editable? spec covers every event type.
- User guide describes the Inventory Flow tab instead of the old Coming
  In / Going Out tabs; remove their screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014FSHhMV2oCu9RE8hpg29ey
Add an annotated screenshot of the Inventory Flow tab (tab, date range,
Filter), and re-shoot the Inventory tab screenshot, which still showed the
old Inventory Coming In / Going Out tabs. Both taken from seed data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014FSHhMV2oCu9RE8hpg29ey
Match the Inventory tab, which already uses number_with_delimiter; flow
numbers at real banks run into the millions. Re-shoot the guide
screenshot to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014FSHhMV2oCu9RE8hpg29ey
awwaiid and others added 2 commits November 22, 2026 08:50
The flow report started its replay at the organization's most recent usable
snapshot, so publishing a new snapshot hid all the history before it. It now
replays from the first usable snapshot and passes through each later usable
snapshot. A later snapshot that disagrees with the replayed quantities shows
the difference as an adjustment (normally there is none).

- InventoryAggregate.inventory_for takes from_first_snapshot: to do this. The
  resulting inventory is the same either way.
- Event.usable_snapshots lists every usable snapshot; most_recent_snapshot
  uses it.
- Snapshots have no group_id, so the replay now groups them by id instead of
  lumping them together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzWYrym3qZvcn1QqAqAEW
These specs checked that "100" appeared anywhere in the page, which an asset
digest satisfied, so they passed while the table showed the wrong quantity.
They now read the quantity from the table. The legacy case needs PaperTrail
versioning turned on, and the events case needs a snapshot before the date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzWYrym3qZvcn1QqAqAEW
@awwaiid

awwaiid commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

From brocks-claude-code, on behalf of Brock:

dorner, here's where each point from your review ended up. Could you take another look?

  • editable? on the event: Event#editable? is true for records whose events are full versions (donations, distributions, etc.) and false for SnapshotEvent, AuditEvent, KitAllocateEvent, KitDeallocateEvent and UpdateExistingEvent. InventoryAggregate now uses it to decide which events get diffed against the previous version, in place of the UpdateExistingEvent special case.
  • Data instead of Struct / more data classes: Result, Row (which computes change and quantity_end; the totals row is a Row too) and ItemChange are Data classes. Each record's changes go into a RecordChanges object that merges as you add to it, replacing the parallel hashes.
  • window_flows naming: it's gone. Rows are built in build_row.
  • Filter up front instead of after the fact: each change is dated to when its record was first created, then filtered into before range (start quantity) or in range (in/out/adjustment).

Since then:

  • The tab loads lazily in a turbo frame, so the show page doesn't replay twice.
  • The replay now starts at the organization's first usable snapshot and passes through later ones (InventoryAggregate.inventory_for(..., from_first_snapshot: true)). A new snapshot no longer hides the history before it.
  • Two existing "version date" request specs were passing only because "100" appeared in an asset digest. They now check the table's quantity.

awwaiid and others added 2 commits November 22, 2026 09:44
…llback

Inventory before an organization's first snapshot isn't shown anymore,
on either tab of the storage location page:

- Inventory tab: "Show Inventory at Date" no longer falls back to the
  pre-event InventoryItem PaperTrail history. The earliest date is the
  first snapshot's date; an earlier date shows the current inventory with
  a notice. Removes View::Inventory.within_snapshot?,
  legacy_inventory_for_storage_location and InventoryItem::EARLIEST_VERSION.
- Inventory Flow tab: a range that starts before the first snapshot starts
  at the snapshot (the picker won't go earlier), so ItemsFlowQuery no longer
  needs blank "unknown" start quantities.
- InventoryAggregate.inventory_for(event_time:) starts at the latest usable
  snapshot at or before that time and always applies the upper bound. A
  date before the most recent snapshot used to return current inventory.
- Event.usable_snapshots only considers the organization's own events.
  Another organization's edited event could make a snapshot unusable.
- Replaying from the first snapshot forgets earlier record versions at each
  later snapshot, so it always ends where the normal replay does.
- Event.history_start replaces most_recent_snapshot.
- The flow invariant spec checks start + in - out + adjustment = end
  (it compared start + change, which is end - start by definition).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzWYrym3qZvcn1QqAqAEW

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inventory Coming In / Going out -- Rework to Inventory Flow, including date range.

2 participants