Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
53eaa68
Add Inventory Flow tab with quantity tracking and date filtering
Aug 7, 2025
bb56879
Refactor inventory flow to use ItemsFlowQuery for improved data handl…
Sep 21, 2025
6e923a6
Add date range filtering to ItemsFlowQuery and update Inventory Flow tab
Sep 22, 2025
2439b14
Remove unused inventory storage methods and related tests for cleaner…
Sep 22, 2025
5233723
Fix date filtering in ItemsFlowQuery to use item creation timestamps
Sep 26, 2025
0eda035
Fix date range filtering in storage location system spec to ensure ac…
Sep 26, 2025
216dc2c
Refactor item creation in flow query specs for improved clarity and a…
Sep 26, 2025
0d50f31
Refactor inventory flow query to utilize event-based data for improve…
Oct 2, 2025
bfd1db6
Enhance inventory flow query to include AuditEvent handling and updat…
Oct 27, 2025
233dd10
Merge branch 'main' into 5249-inventory-flow-tab
awwaiid Nov 23, 2025
2c1a417
Merge branch 'main' into 5249-inventory-flow-tab
awwaiid Nov 30, 2025
146129b
Merge remote-tracking branch 'origin/main' into 5249-inventory-flow-tab
awwaiid Jul 19, 2026
1898ec6
Fix flow accounting: event versions, kit events, and audit deltas
awwaiid Jul 19, 2026
d141971
Add start/end quantity columns and a separate adjustment/audit column
awwaiid Jul 20, 2026
c334702
Backdate edits in Inventory Flow and derive all columns from one replay
awwaiid Sep 27, 2026
f3c8552
Merge remote-tracking branch 'origin/main' into inventory-flow-backdated
awwaiid Sep 27, 2026
a740f90
Drop redundant keyword_init on Structs
awwaiid Sep 27, 2026
70f667b
Merge remote-tracking branch 'origin/main' into inventory-flow-backdated
awwaiid Oct 24, 2026
dcd9751
Inventory Flow: data classes, versioned? events, filter changes up front
awwaiid Oct 24, 2026
1af593e
Rename Event#versioned? to is_edit?
awwaiid Oct 24, 2026
5e04581
Inventory Flow: check only the previous version's items; fix tab aria…
awwaiid Oct 24, 2026
c7b5ac4
Inventory Flow: blank pre-snapshot quantities, lazy-load the tab, edi…
awwaiid Nov 15, 2026
9683659
Inventory Flow: more request spec coverage
awwaiid Nov 15, 2026
dbb1d78
Inventory Flow: fix item links in the lazy frame, address review find…
awwaiid Nov 15, 2026
6d55a61
User guide: screenshot the Inventory Flow tab
awwaiid Nov 15, 2026
8d94a64
Inventory Flow: format quantities with thousands separators
awwaiid Nov 15, 2026
c9d1995
Merge remote-tracking branch 'origin/main' into inventory-flow-backdated
awwaiid Nov 22, 2026
e7a2055
Inventory Flow: replay from the first snapshot, through later ones
awwaiid Nov 22, 2026
63ce770
Check the Inventory tab's quantity in the version date specs
awwaiid Nov 22, 2026
97d15bc
Start inventory history at the first snapshot; drop the PaperTrail fa…
awwaiid Nov 22, 2026
1f5b8ea
Remove a stray Tailwind build file committed by mistake
awwaiid Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,6 @@ Layout/ExtraSpacing:
- 'Guardfile'
- 'app/models/barcode_item.rb'
- 'app/queries/items_by_storage_collection_query.rb'
- 'app/queries/items_in_query.rb'
- 'app/queries/items_in_total_query.rb'
- 'app/queries/items_out_query.rb'
- 'app/queries/items_out_total_query.rb'
- 'config/environments/development.rb'
- 'config/environments/test.rb'
- 'config/puma.rb'
Expand Down Expand Up @@ -169,10 +165,6 @@ Layout/MultilineMethodCallIndentation:
- 'app/models/partner_distribution.rb'
- 'app/models/storage_location.rb'
- 'app/queries/items_by_storage_collection_query.rb'
- 'app/queries/items_in_query.rb'
- 'app/queries/items_in_total_query.rb'
- 'app/queries/items_out_query.rb'
- 'app/queries/items_out_total_query.rb'
- 'app/services/reports/acquisition_report_service.rb'
- 'app/services/reports/adult_incontinence_report_service.rb'
- 'app/services/reports/children_served_report_service.rb'
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Business logic lives in service classes (`app/services/`), not controllers. Patt
- `/reports/*` - Reporting endpoints

### Query Objects
Complex queries are extracted into `app/queries/` (e.g., `ItemsInQuery`, `LowInventoryQuery`).
Complex queries are extracted into `app/queries/` (e.g., `ItemsFlowQuery`, `LowInventoryQuery`).

### Frontend
Bootstrap 5.2, Turbo Rails, Stimulus.js, ImportMap (no Webpack/bundler). JavaScript controllers live in `app/javascript/`.
Expand Down
54 changes: 38 additions & 16 deletions app/controllers/storage_locations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,24 +54,14 @@ def edit
@storage_location = current_organization.storage_locations.find(params[:id])
end

# TODO: Move these queries to Query Object
def show
setup_date_range_picker
@storage_location = current_organization.storage_locations.find(params[:id])
version_date = params[:version_date].presence&.to_date
# TODO: Find a way to do these with less hard SQL. These queries have to be manually updated because they're not in-sync with the Model
@items_out = ItemsOutQuery.new(organization: current_organization, storage_location: @storage_location).call
@items_out_total = ItemsOutTotalQuery.new(organization: current_organization, storage_location: @storage_location).call
@items_in = ItemsInQuery.new(organization: current_organization, storage_location: @storage_location).call
@items_in_total = ItemsInTotalQuery.new(organization: current_organization, storage_location: @storage_location).call
if View::Inventory.within_snapshot?(current_organization.id, version_date)
@inventory = View::Inventory.new(current_organization.id, event_time: version_date)
else
@legacy_inventory = View::Inventory.legacy_inventory_for_storage_location(
current_organization.id,
@storage_location.id,
version_date
)
end
@show_flow_tab = params[:tab] == "flow"
@date_range_filters = date_range_filters
history_start = Event.history_start(current_organization.id)
@history_start_date = history_start&.to_date
@inventory = View::Inventory.new(current_organization.id, event_time: inventory_time(history_start))

respond_to do |format|
format.html
Expand Down Expand Up @@ -135,6 +125,14 @@ def destroy
end
end

# The Inventory Flow tab's table, loaded into a lazy turbo frame on the show
# page so the inventory replay only runs when someone opens that tab.
def inventory_flow
@storage_location = current_organization.storage_locations.find(params[:id])
@flow = ItemsFlowQuery.new(organization: current_organization, storage_location: @storage_location,
date_range: helpers.selected_range).call
end

def inventory
@items = View::Inventory.items_for_location(StorageLocation.find(params[:id]),
include_omitted: params[:include_omitted_items] == "true")
Expand All @@ -155,6 +153,30 @@ def include_omitted_items(existing_item_ids = [])
end
end

# The time to show the Inventory tab's inventory at: the start of the requested
# version_date, but no earlier than when the inventory history begins.
# @param history_start [ActiveSupport::TimeWithZone, nil]
# @return [ActiveSupport::TimeWithZone, nil] nil for the current inventory
def inventory_time(history_start)
version_date = params[:version_date].presence&.to_date
return if version_date.nil?

if history_start && version_date < history_start.to_date
flash.now[:alert] = "Inventory history begins on #{history_start.to_date.to_fs(:long)}. Showing the current inventory."
return
end

[version_date.in_time_zone, history_start].compact.max
end

# @return [Hash] the Inventory Flow tab's date range filters, if any
def date_range_filters
filters = params[:filters]
return {} unless filters.is_a?(ActionController::Parameters)

filters.permit(:date_range, :date_range_label).to_h.compact_blank
end

helper_method \
def filter_params
return {} unless params.key?(:filters)
Expand Down
5 changes: 5 additions & 0 deletions app/events/audit_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,9 @@ def self.publish(audit)
)
)
end

# Sets quantities outright rather than editing an earlier version.
def editable?
false
end
end
46 changes: 26 additions & 20 deletions app/events/inventory_aggregate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,45 @@ def on(*event_types, &block)
end

# @param organization_id [Integer]
# @param event_time [DateTime]
# @param event_time [DateTime] the inventory as of this time. It must not be before the
# organization's first snapshot, since events before that aren't kept.
# @param validate [Boolean]
# @param from_first_snapshot [Boolean] replay from the first usable snapshot, applying each
# later usable snapshot along the way, instead of starting at the most recent one. Only
# useful with a block, to see the whole history; the resulting inventory is the same.
# @return [EventTypes::Inventory]
# This method can take a block so that you can build up the history of a particular item over
# time, for instance
def inventory_for(organization_id, event_time: nil, validate: false)
last_snapshot = Event.most_recent_snapshot(organization_id)
def inventory_for(organization_id, event_time: nil, validate: false, from_first_snapshot: false)
# unusable snapshots are ignored - see Event.usable_snapshots
snapshots = Event.usable_snapshots(organization_id)
snapshots = snapshots.where(event_time: ..event_time) if event_time
snapshots = from_first_snapshot ? snapshots.to_a : [snapshots.last].compact

# ignore all other snapshots as they are considered "unusable" - see most_recent_snapshot method
events = Event.for_organization(organization_id).without_snapshots
if last_snapshot # all previous events can be ignored
events = events.where("event_time > ?", last_snapshot.event_time)
if snapshots.any? # all previous events can be ignored
events = events.where("event_time > ?", snapshots.first.event_time)
end
events = events.where(event_time: ..event_time) if event_time

if event_time && (!last_snapshot || event_time > last_snapshot.event_time)
events = events.where(event_time: ..event_time)
end

events = events.to_a
events.unshift(last_snapshot) if last_snapshot
events = snapshots + events.to_a
events.sort_by! { |event| [event.event_time, event.id] } if snapshots.size > 1

inventory = EventTypes::Inventory.from(organization_id)
event_hash = {}
events.group_by(&:group_id).each do |_, event_batch|
# most snapshots have no group_id, so each one is its own group
events.group_by { |event| event.group_id || event.id }.each do |_, event_batch|
last_grouped_event = event_batch.max_by(&:updated_at)
# don't do grouping for UpdateExistingEvents
if event_batch.any? { |e| e.is_a?(UpdateExistingEvent) }
handle(last_grouped_event, inventory, validate: validate)
yield last_grouped_event, inventory if block_given?
next
# a snapshot already includes every earlier version, so later versions start fresh, as they
# do when replay starts at that snapshot
event_hash.clear if last_grouped_event.is_a?(SnapshotEvent)
previous_event = nil
# only versions of an editable record are diffed against its previous version
if last_grouped_event.editable?
key = [last_grouped_event.eventable_type, last_grouped_event.eventable_id]
previous_event = event_hash[key]
event_hash[key] = last_grouped_event
end
previous_event = event_hash[[last_grouped_event.eventable_type, last_grouped_event.eventable_id]]
event_hash[[last_grouped_event.eventable_type, last_grouped_event.eventable_id]] = last_grouped_event
handle(last_grouped_event, inventory, validate: validate, previous_event: previous_event)
yield last_grouped_event, inventory if block_given?
end
Expand Down
5 changes: 5 additions & 0 deletions app/events/kit_allocate_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,9 @@ def self.publish(kit, storage_location, quantity)
)
)
end

# Each allocation is its own change rather than an edit of the kit.
def editable?
false
end
end
5 changes: 5 additions & 0 deletions app/events/kit_deallocate_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,9 @@ def self.publish(kit, storage_location, quantity)
)
)
end

# Each deallocation is its own change rather than an edit of the kit.
def editable?
false
end
end
5 changes: 5 additions & 0 deletions app/events/snapshot_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,9 @@ def self.publish(organization)
data: inventory
)
end

# A snapshot replaces the whole inventory rather than versioning a record.
def editable?
false
end
end
6 changes: 6 additions & 0 deletions app/events/update_existing_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,10 @@ def publish(itemizable, previous_line_items, original_storage_location)
)
end
end

# Carries the difference from the previous version rather than a full
# version, so it is applied on its own instead of replacing an earlier event.
def editable?
false
end
end
11 changes: 9 additions & 2 deletions app/helpers/date_range_helper.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Encapsulates methods used on the Dashboard that need some business logic
module DateRangeHelper
def date_range_params
params.dig(:filters, :date_range).presence || default_date
date_range_filter(:date_range).presence || default_date
end

def date_range_label
case (params.dig(:filters, :date_range_label).presence || "this year").downcase
case (date_range_filter(:date_range_label).presence || "this year").downcase
when "today"
"today"
when "yesterday"
Expand Down Expand Up @@ -46,6 +46,13 @@ def selected_range
(start_date.beginning_of_day)..(end_date.end_of_day)
end

# @param key [Symbol]
# @return [String, nil] the filter's value, or nil if params[:filters] isn't a hash
def date_range_filter(key)
filters = params[:filters]
filters[key] if filters.respond_to?(:key?)
end

def selected_range_described
start_date, end_date = selected_interval
if start_date == Time.zone.today
Expand Down
4 changes: 4 additions & 0 deletions app/javascript/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,16 @@ $(document).ready(function(){
const today = DateTime.now();
const startDate = new Date(rangeElement.dataset["initialStartDate"]);
const endDate = new Date(rangeElement.dataset["initialEndDate"]);
const minDate = rangeElement.dataset["minDate"]
? new Date(rangeElement.dataset["minDate"])
: null;

const picker = new Litepicker({
element: rangeElement,
plugins: ["ranges"],
startDate: startDate,
endDate: endDate,
minDate: minDate,
format: "MMMM D, YYYY",
ranges: {
customRanges: {
Expand Down
48 changes: 30 additions & 18 deletions app/models/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,38 +54,50 @@ def no_intervening_snapshot
end
end

# Whether events of this type are versions of an editable record: each one,
# the first included, is a full version of the eventable (e.g. a donation,
# then each later edit of it), and replaces the previous event for that
# record. Events that are standalone changes return false.
# @return [Boolean]
def editable?
true
end

# @return [Array<Option>]
def self.types_for_select
descendants.map do |klass|
Option.new(name: klass.name.sub("Event", "").titleize, id: klass.name)
end.sort_by(&:name)
end

# Returns the most recent "usable" snapshot. A snapshot is unusable if there is another event
# that was originally made before the snapshot, but was later updated/edited after the snapshot
# (i.e. there is a correction event whose event_time is before the snapshot, but whose
# The organization's "usable" snapshots, oldest first. A snapshot is unusable if there is another
# event that was originally made before the snapshot, but was later updated/edited after the
# snapshot (i.e. there is a correction event whose event_time is before the snapshot, but whose
# updated_at time is after it).
# In this case, the values in the snapshot can't be used to start the inventory because they
# wouldn't reflect the updates.
# There should always be at least one usable snapshot since the very first event we have in the
# DB for any organization should be a SnapshotEvent.
# @param organization_id [Integer]
# @return [SnapshotEvent]
def self.most_recent_snapshot(organization_id)
query = <<-SQL
select *
FROM events as snapshots
WHERE type='SnapshotEvent' AND organization_id=$1
AND NOT EXISTS (
SELECT id
FROM events
WHERE type != 'SnapshotEvent'
AND event_time < snapshots.event_time AND updated_at > snapshots.event_time
)
ORDER BY event_time DESC
LIMIT 1
# @return [ActiveRecord::Relation<SnapshotEvent>]
def self.usable_snapshots(organization_id)
SnapshotEvent.where(organization_id: organization_id).where(<<~SQL).order(:event_time)
NOT EXISTS (
SELECT 1
FROM events AS edited
WHERE edited.organization_id = events.organization_id
AND edited.type != 'SnapshotEvent'
AND edited.event_time < events.event_time AND edited.updated_at > events.event_time
)
SQL
SnapshotEvent.find_by_sql(query, [organization_id]).first
end

# When the organization's inventory history begins: the time of its first usable snapshot.
# Inventory from before then can't be known.
# @param organization_id [Integer]
# @return [ActiveSupport::TimeWithZone, nil] nil if there is no snapshot
def self.history_start(organization_id)
usable_snapshots(organization_id).pick(:event_time)
end

def validate_inventory
Expand Down
2 changes: 0 additions & 2 deletions app/models/inventory_item.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ class InventoryItem < ApplicationRecord
has_paper_trail
MAX_INT = 2**31

EARLIEST_VERSION = "2021-08-02"

belongs_to :storage_location
belongs_to :item

Expand Down
25 changes: 0 additions & 25 deletions app/models/view/inventory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,31 +17,6 @@ def to_dropdown_option
attr_accessor :inventory, :organization_id
delegate :storage_locations, to: :inventory

# @param event_time [ActiveSupport::TimeWithZone]
# @return [Boolean]
def self.within_snapshot?(organization_id, event_time)
return true if event_time.blank?

event = SnapshotEvent.where(organization_id: organization_id).first
event && event.created_at < event_time
end

# @param organization_id [Integer]
# @param storage_location_id [Integer]
# @param event_time [ActiveSupport::TimeWithZone]
# @return [Array<ViewInventoryItem>]
def self.legacy_inventory_for_storage_location(organization_id, storage_location_id, event_time)
items = Organization.find(organization_id).inventory_items.where(storage_location_id: storage_location_id)
items.map do |item|
ViewInventoryItem.new(
item_id: item.item_id,
quantity: item.paper_trail.version_at(event_time)&.quantity || 0,
storage_location_id: storage_location_id,
db_item: item.item
)
end
end

# @param organization_id [Integer]
# @param event_time [DateTime]
def initialize(organization_id, event_time: nil)
Expand Down
Loading
Loading