Skip to content

Overdue inbound shipments: endpoint, contract tests, and inbound list Overdue view (spec-driven Act 2) - #3

Merged
devin-ai-integration[bot] merged 7 commits into
spec-demo-basefrom
devin/1787182275-shipment-exceptions-impl
Aug 20, 2026
Merged

devin-ai-integration[bot] merged 7 commits into
spec-demo-basefrom
devin/1787182275-shipment-exceptions-impl

Conversation

@matthewguerra-cog

@matthewguerra-cog matthewguerra-cog commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

✨ Description of Change

Link to GitHub issue or Jira ticket: Act 2/3 of the spec-driven demo — implements the contract merged in #1.

Description:

Implements GET /api/shipments/exceptions/overdue exactly per the agreed contract (openapi/specs/shipment-exceptions-api.yaml + acceptance criteria doc), end to end:

  • Backend: ShipmentExceptionApiController.overdue() with a Validateable command object (invalid params surface through the shared ValidationException → errors/handleValidationErrors path), a new ShipmentExceptionService.getOverdueInboundShipments() (criteria pre-filter on expectedDeliveryDate < today + destination in session warehouse & child locations, then event-based exclusions via dateDelivered() / latest-event CANCELLED, midnight-truncated daysLate, in-memory sort + paging), and a static URL mapping "/api/shipments/exceptions/overdue" declared with the other static /api/shipments/* mappings before "/api/shipments/$id" so it can't be swallowed by the wildcard.
  • Decisions recorded: the 5 open questions in shipment-exceptions-acceptance-criteria.md are now a "Decisions" section (cancelled = latest event CANCELLED; partially received stays; inbound = session warehouse or child location; daysLate = floored whole days, server clock; never-shipped past-due included).
  • Contract tests: characterization/contract/test_shipment_exceptions_api_contract.py (+ a shipment_exception_endpoints conftest guard that skips on builds predating the endpoint). Seeding is API-based (POST /api/shipments + shipment events) with ZZ-prefixed names and cleanup.
  • Frontend: an "Overdue" toggle on the Inbound Movement List (/openboxes/stockMovement/list?direction=INBOUND) that fetches from the new endpoint and shows a Days Late column.

Criterion → test mapping

# Criterion Test
1 Overdue, unreceived, inbound included test_criterion_01_overdue_unreceived_inbound_is_included
2 Future expected delivery excluded test_criterion_02_future_expected_delivery_is_excluded
3 Due today excluded test_criterion_03_today_expected_delivery_is_excluded
4 Received excluded test_criterion_04_received_shipments_are_excluded
5 Received-or-delivered excluded test_criterion_05_received_or_delivered_shipments_are_excluded
6 Null expectedDeliveryDate excluded test_criterion_06_null_expected_delivery_is_excluded
7 Cancelled (latest event) excluded test_criterion_07_latest_cancelled_event_is_excluded
8 Only inbound included test_criterion_08_only_inbound_shipments_are_included
9 Inbound relative to session warehouse test_criterion_09_inbound_is_relative_to_session_warehouse
10 Partially received included test_criterion_10_partially_received_without_delivery_is_included
11 daysLate is calendar-day diff test_criterion_11_days_late_is_calendar_days
12 daysLate ≥ threshold test_criterion_12_days_late_meets_threshold
13 daysLate integer ≥ 1 test_criterion_13_days_late_is_positive_integer
14 Default threshold 1 day test_criterion_14_default_threshold_is_one_day
15 minDaysLate filters test_criterion_15_min_days_late_filters
16 minDaysLate < 1 rejected test_criterion_16_min_days_late_below_one_is_rejected
17 origin filters test_criterion_17_origin_filter
18 destination filters test_criterion_18_destination_filter
19 Unknown filter ids not errors test_criterion_19_unknown_filter_ids_are_not_errors
20 Response envelope test_criterion_20_response_envelope
21 Default max 50 test_criterion_21_default_max_is_fifty
22 max > 500 rejected test_criterion_22_max_above_five_hundred_is_rejected
23 totalCount ignores pagination test_criterion_23_total_count_ignores_pagination
24 offset pages test_criterion_24_offset_pages
25 Default sort daysLate desc test_criterion_25_default_sort_is_days_late_descending
26 sort honoured test_criterion_26_expected_delivery_date_sort_is_honoured
27 Location-name sort case-insensitive test_criterion_27_location_name_sort_is_case_insensitive
28 Unsupported sort rejected test_criterion_28_unsupported_sort_is_rejected
29 Session required (401) test_criterion_29_session_is_required
30 Warehouse required (400) test_criterion_30_warehouse_is_required

Coverage caveats (honest gaps within otherwise-covered criteria):

  • Criterion 11's "23:00 two days ago" time-of-day nuance is approximated: seeding sets date-only expectedDeliveryDate (midnight), so the test proves the calendar-day diff (expected daysLate computed from the seeded date vs today at assertion time) but not truncation of a late-evening timestamp.
  • Criterion 9's child-location half (parent warehouse sees a child-location destination) is not exercised — demo data has no parent/child warehouse pair reachable through the API seeding path; the test proves the relative-to-session behavior with a second warehouse instead.
  • Criterion 17 asserts every row's origin.id matches the filter but does not seed a second distinct origin to prove its absence.

Deviations from the contract

None — the endpoint is implemented as specified. The criteria doc's only edits are the decided answers to its own open questions (criterion 7/10 cross-references updated from "open question" to "decision").

Verification (Act 3)

All verification was run against a source build of this branch (./gradlew prepareDocker -Dgrails.env=prod → docker build → docker compose up -d; app footer confirmed Build 41723f3).

  • Redocly lint (npx @redocly/cli@1.34.2 lint --config openapi/redocly.yaml 'openapi/specs/*.yaml' openapi/components/common.yaml): clean.
  • New contract tests (test_shipment_exceptions_api_contract.py): 30 passed / 0 skipped / 0 failed in 6.16s — the conftest guard did not skip, confirming the endpoint is live in the source build.
  • Full contract suite (characterization/contract/run.sh): 899 passed / 45 skipped / 2 failed in ~41s (pinned-image baseline was 359/557/0). The 2 failures are in files this PR does not touch (test_location_group_api_contract.py::test_read_unknown — 404 not declared in location-group-api.yaml; test_shipment_screens_api_contract.py::test_add_to_shipment — 400 vs expected 200) and appear pre-existing, though a clean baseline run on spec-demo-base was not performed to prove it.
  • Frontend lint (Node 14, npm ci --ignore-scripts + ESLint on the touched files): 0 errors, 13 warnings from pre-existing rule classes (react/destructuring-assignment, react/jsx-props-no-spreading).
  • Browser UI (source build, populated list): Overdue toggle renders the overdue rows with a descending Days Late column, count drops to overdue-only, Export hidden, unsupported column sorts disabled, stale sort state reset on toggle, no console errors; toggling off restores the normal list.

Review-driven fixes included: unsupported sorts disabled + Export hidden in Overdue mode, initial unscoped-fetch race fixed, origin/destination made nullable in the command object, status-cell crash on toggle fixed, DataTable sort state reset on toggle, and contract-test fixtures now self-create missing DELIVERED/CANCELLED event types.

Not verified: the event-type self-seeding branch was not exercised locally (the event types already existed in the test DB); a fresh-DB/CI run is what proves it.


📷 Screenshots & Recordings (optional)

Overdue view on the Inbound Movement List (source build, populated list):

Overdue view with Days Late column

Devin-Org: engineering

Link to Devin session: https://app.devin.ai/sessions/ffbe8c28fa6e4dcf8c6e6c0bf758d7f6
Requested by: @matthewguerra-cog


Devin Review

Status Commit
🟢 Reviewed 41723f3
Open in Devin Review (Staging)

devin-ai-integration Bot and others added 2 commits August 19, 2026 23:36
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
@matthewguerra-cog matthewguerra-cog self-assigned this Aug 19, 2026
@devin-ai-integration

Copy link
Copy Markdown

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 11 potential issues.

Open in Devin Review

Comment on lines +32 to +72
List<Shipment> shipments = Shipment.createCriteria().list {
isNotNull("expectedDeliveryDate")
lt("expectedDeliveryDate", startOfToday)
inList("destination", inboundLocations)
if (origin) {
eq("origin", origin)
}
if (destination) {
eq("destination", destination)
}
}

ZoneId zone = ZoneId.systemDefault()
LocalDate today = LocalDate.now(zone)
List<Map> rows = shipments.collect { Shipment shipment ->
Date deliveredDate = shipment.dateDelivered()
def latestEvent = shipment.getMostRecentEvent()
if (deliveredDate || latestEvent?.eventType?.eventCode == EventCode.CANCELLED) {
return null
}

LocalDate expectedDeliveryDate = shipment.expectedDeliveryDate.toInstant().atZone(zone).toLocalDate()
Integer daysLate = ChronoUnit.DAYS.between(expectedDeliveryDate, today) as Integer
if (daysLate < command.minDaysLate) {
return null
}

[
id : shipment.id,
shipmentNumber : shipment.shipmentNumber,
name : shipment.name,
shipmentType : shipment.shipmentType?.name,
origin : locationReference(shipment.origin),
destination : locationReference(shipment.destination),
expectedShippingDate : shipment.expectedShippingDate,
expectedDeliveryDate : shipment.expectedDeliveryDate,
daysLate : daysLate,
status : shipment.status?.code?.name(),
shipmentItemCount : shipment.shipmentItemCount ?: shipment.shipmentItems?.size() ?: 0,
]
}.findAll()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 All matching shipments are loaded and filtered in memory before paging

The criteria query only pre-filters on expectedDeliveryDate < today and destination; the received/delivered, cancelled and minDaysLate exclusions plus sorting and paging all happen in memory afterwards. Every candidate shipment therefore has to be materialised on each request, and each row triggers lazy access to events (via dateDelivered() and getMostRecentEvent(), grails-app/domain/org/pih/warehouse/shipping/Shipment.groovy:419,677) plus shipmentType/status resolution — an N+1 pattern that grows with the warehouse's history of past-dated shipments rather than with the requested page size. shipmentItemCount is a SQL formula field so it usually avoids loading items, but the ?: shipment.shipmentItems?.size() fallback would. Pushing the delivered/cancelled exclusion into the query (or at least paging on the DB side) would be worth considering before this endpoint is exposed on a busy site.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — see replies on the related threads: the in-memory filtering/paging trade-off is a known limitation of this contract-scoped implementation; a DB-side exclusion + pagination is the natural follow-up for large shipment histories.

class ShipmentExceptionService {

Map getOverdueInboundShipments(Location warehouse, ShipmentExceptionCommand command) {
List<Location> inboundLocations = [warehouse] + Location.findAllByParentLocation(warehouse)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: inList over warehouse plus all direct child locations can produce a very large IN clause

Location.findAllByParentLocation(warehouse) returns every direct child of the warehouse, which in OpenBoxes includes bin locations and zones — often hundreds or thousands per depot. All of them are passed to inList("destination", inboundLocations), so the generated SQL IN clause scales with the number of bins and can approach database parameter limits. Since shipments realistically only target depot-type locations, filtering inboundLocations to depots (or joining on destination.parentLocation) would keep the query bounded.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — valid scalability point. Keeping as-is for this contract-scoped change (matches decision 3: destination = session warehouse or child locations); filtering to depot-type children or joining on destination.parentLocation is a sensible follow-up if bin counts become a problem.

Comment on lines +101 to +106
private static int compareValues(Object left, Object right) {
if (left == right) return 0
if (left == null) return -1
if (right == null) return 1
return left <=> right
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Null sort values sort first in both directions asymmetrically

compareValues places nulls before non-nulls in ascending order and, because desc is implemented as comparator.reversed(), last in descending order. For the fields exposed by the endpoint this is mostly moot (daysLate and expectedDeliveryDate are always set on returned rows, shipmentNumber/location names are effectively always set), so no functional issue — worth remembering if additional nullable sort keys such as shipmentType are added later.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — agreed this is moot for the current sort fields since all returned values are non-null; noted for any future nullable sort keys.

Comment on lines +29 to +37
if (filterParams.overdue) {
return _.omitBy({
origin: origin?.id,
destination: destination?.id,
offset: `${offset}`,
max: `${state.pageSize}`,
...sortingParams,
}, (value) => !value);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Overdue toggle silently drops the other active inbound filters

When the toggle is on, getParams keeps only origin/destination and paging/sorting; search text (q), receiptStatusCode, requestedBy, createdBy, updatedBy, shipmentType and the created-before/after dates are dropped even though the filter form still displays them as active. Users who have narrowed the inbound list will see the Overdue view ignore most of their criteria without any indication. Disabling or visually clearing the unsupported filter fields while overdue is active would avoid the mismatch.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — deliberate scope choice: the overdue endpoint only supports origin/destination filters per the contract, so the Overdue view intentionally applies just those. Disabling the unsupported filter fields while the toggle is on is a reasonable UX follow-up but out of scope for this contract-driven change.

Comment on lines +184 to +206
def test_criterion_09_inbound_is_relative_to_session_warehouse(client, exception_shipments):
"""Criterion 9: inbound results are relative to the selected warehouse."""
number = _shipment_number(client, exception_shipments["overdue"])
default_rows = {row["shipmentNumber"] for row in _rows(client)["data"]}
assert number in default_rows
other_client = type(client)()
other_client.login("Main Supplier")
assert number not in {
row["shipmentNumber"] for row in _rows(other_client)["data"]
}


def test_criterion_10_partially_received_without_delivery_is_included(client, exception_shipments):
"""Criterion 10: partially received shipments without delivery are included."""
number = _shipment_number(client, exception_shipments["partial"])
assert number in {row["shipmentNumber"] for row in _rows(client)["data"]}


def test_criterion_11_days_late_is_calendar_days(client, exception_shipments):
"""Criterion 11: daysLate is a calendar-day difference."""
number = _shipment_number(client, exception_shipments["overdue"])
row = next(row for row in _rows(client)["data"] if row["shipmentNumber"] == number)
assert row["daysLate"] == 3

@devin-ai-integration devin-ai-integration Bot Aug 19, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Contract test logs into a warehouse that may not exist in seed data

test_criterion_09 calls other_client.login("Boston Warehouse"), but the other contract tests in this suite reference the seeded location as "Boston Office" (e.g. characterization/contract/test_picklist_api_contract.py:33, characterization/contract/test_pack_list_api_contract.py:36). ApiClient.location_id resolves by exact name, so if there is no "Boston Warehouse" in the demo data this test will error rather than assert the intended behaviour. Worth confirming against the seeded location list.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Addressed in e06dff1 — criterion 9 now logs the second client into "Boston Warehouse" (a real depot in the demo data; ApiClient.login takes a location name and calls chooseLocation), and criterion 11 computes the expected daysLate from the shipment's actual expectedDeliveryDate vs date.today() at assertion time instead of hardcoding 3, so a midnight boundary between seeding and assertion can no longer break it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

"Boston Warehouse" exists in the demo dataset as a choosable depot (it's a warehouse location, unlike "Boston Office"), and the test passes live against a source build — test_criterion_09 succeeded in both full-suite runs (30/30). "Main Supplier" was the name that couldn't be used as a session warehouse, which is why the earlier round switched to Boston Warehouse.

@staging-devin-ai-integration staging-devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 4 potential issues.

Open in Devin Review (Staging)
Debug

Playground

Comment on lines +32 to +42
List<Shipment> shipments = Shipment.createCriteria().list {
isNotNull("expectedDeliveryDate")
lt("expectedDeliveryDate", startOfToday)
inList("destination", inboundLocations)
if (origin) {
eq("origin", origin)
}
if (destination) {
eq("destination", destination)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Overdue shipments report loads the entire history of late inbound shipments into memory on every request

The overdue list is built by fetching every inbound shipment whose expected delivery date has passed (Shipment.createCriteria().list at grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy:32-42) with no row limit, then filtering, sorting and paging in memory, so response time and memory grow with all historical late shipments.
Impact: On sites with years of shipment history the Overdue view can become very slow or exhaust memory, even when only 10 rows are displayed.

No DB-side pagination plus per-shipment event access

The criteria query applies only the date/destination/origin predicates and returns every match. For each returned shipment the code then calls shipment.dateDelivered() and shipment.getMostRecentEvent() (grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy:47-48), each of which walks the lazily loaded events collection, and shipment.status (Shipment.getStatus()), producing a per-shipment event query (N+1). Pagination happens only afterwards in page(...) (grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy:108-118), so max/offset do not reduce the work.

A DB-level restriction (e.g. excluding shipments that already have a RECEIVED/DELIVERED/CANCELLED event and applying the daysLate cutoff as a date predicate, plus projection/pagination in SQL) would bound the work.

Open in Devin Review (Staging)

Was this helpful? React with 👍 or 👎 to provide feedback.

Debug

Playground

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — real scalability limitation. Event-based exclusions (dateDelivered(), latest-event CANCELLED) are derived per the contract's decisions and aren't denormalized queryably today, so in-memory filtering was the contract-faithful choice for this change. Pushing the exclusions and pagination into SQL is the right follow-up for large histories.

devin-ai-integration Bot and others added 2 commits August 19, 2026 23:47
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>

@staging-devin-ai-integration staging-devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 2 new potential issues.

Open in Devin Review (Staging)
Debug

Playground

Comment on lines +48 to +49
origin(nullable: true, blank: true)
destination(nullable: true, blank: true)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Blank origin/destination now silently yield an empty page instead of a validation error

Allowing blank: true on origin/destination means a request like ?origin= binds an empty string. In ShipmentExceptionService.getOverdueInboundShipments the empty string is falsy in Groovy, so origin resolves to null and the filter is simply ignored (grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy:23-29) rather than returning an empty page as the "unknown filter id" criterion implies. Worth confirming this is the intended contract behavior for blank (vs unknown) ids.

Open in Devin Review (Staging)

Was this helpful? React with 👍 or 👎 to provide feedback.

Debug

Playground

Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>

@staging-devin-ai-integration staging-devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

Open in Devin Review (Staging)
Debug

Playground


spec = Spec("shipment-exceptions-api.yaml")
TEST_PREFIX = "ZZ Contract Shipment Exception"
pytestmark = pytest.mark.usefixtures("shipment_exception_endpoints")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Guard fixture relies on a 404 for a path that may fall through to the shipment wildcard mapping

shipment_exception_endpoints in characterization/contract/conftest.py:77-80 skips only when the request returns 404. On builds that predate the endpoint, /api/shipments/exceptions/overdue may instead be matched by the generic /api/shipments/$id mapping and return a non-404 status (e.g. 500 or an error envelope), in which case the tests would run and fail rather than skip. Worth confirming the pinned released image actually returns 404 for this path.

Open in Devin Review (Staging)

Was this helpful? React with 👍 or 👎 to provide feedback.

Debug

Playground

Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>

@staging-devin-ai-integration staging-devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

Open in Devin Review (Staging)
Debug

Playground

Comment on lines +24 to +37
if matches:
return matches[0]["id"]
response = client.request(
"POST",
"/api/eventTypes",
json={
"name": event_code,
"description": f"{TEST_PREFIX} {event_code}",
"sortOrder": 999,
"eventCode": event_code,
},
)
assert response.status_code == 201
return response.json()["data"]["id"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Contract test now creates missing event types as a side effect

_event_type_id no longer fails when an event code is missing; it POSTs a new event type with name = event_code and sortOrder = 999. This mutates reference data in the target environment and is never cleaned up (only shipments are deleted via _delete_shipment), so repeated runs against a persistent build leave stray EventType rows. It also assumes the seeding user has permission to create event types and that POST /api/eventTypes returns 201 with data.id; if the endpoint behaves differently (e.g. 200, or a wrapped payload) the tests will fail with an opaque assertion instead of the previous clear "event type not found" message. Consider registering created event types for teardown.

Open in Devin Review (Staging)

Was this helpful? React with 👍 or 👎 to provide feedback.

Debug

Playground

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 4 new potential issues.

Open in Devin Review

Comment on lines 60 to +63
onFetchHandler,
} = useTableData({
filterParams,
url: STOCK_MOVEMENT_API,
url: filterParams.overdue ? SHIPMENT_EXCEPTIONS_OVERDUE_API : STOCK_MOVEMENT_API,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Switching the inbound list into the Overdue view after sorting a column makes the list fail to load

The column the user sorted by stays selected when the view is switched (url: filterParams.overdue ? SHIPMENT_EXCEPTIONS_OVERDUE_API : STOCK_MOVEMENT_API at src/js/hooks/list-pages/inbound/useInboundListTableData.jsx:63) even though the two views accept different sort columns, so the list request is rejected and no rows appear.
Impact: A user who has sorted the inbound list and then toggles Overdue (or toggles back) sees an error and a list that does not refresh.

Shared react-table sort state is sent to an endpoint with a different sort vocabulary

useTableData builds the sort params straight from react-table's persisted state: sort: tableState.sorted[0].id (src/js/hooks/list-pages/useTableData.jsx:62-65). Toggling overdue only changes the request URL and the column definitions; react-table's sorted state is not reset.

  • Normal view → Overdue: if the user had sorted by dateCreated, stocklist.name, identifier or origin.name, that id is still sent as sort to /api/shipments/exceptions/overdue. ShipmentExceptionCommand.sort only accepts daysLate, expectedDeliveryDate, shipmentNumber, origin, destination (grails-app/controllers/org/pih/warehouse/api/ShipmentExceptionApiController.groovy:53-55), so the request fails validation with 400. Marking the columns sortable: !overdue prevents new clicks but does not clear an existing selection.
  • Overdue → normal view: sort=daysLate (or origin) is sent to /api/stockMovements, where it falls through to order(params.sort, ...) on a Hibernate criteria (grails-app/services/org/pih/warehouse/inventory/StockMovementService.groovy:518) for a property that does not exist.

In both cases the fetch promise rejects (src/js/hooks/list-pages/useTableData.jsx:90) and the table keeps its stale data.

(Refers to lines 29-63)

Prompt for agents
Toggling the new Overdue switch on the inbound list changes the fetch URL (useInboundListTableData) and the column set (StockMovementInboundTable), but react-table's persisted `sorted` state is not reset. useTableData forwards `tableState.sorted[0].id` as the `sort` query param, so a sort column that is valid for one endpoint gets sent to the other: the overdue endpoint's command object only accepts daysLate/expectedDeliveryDate/shipmentNumber/origin/destination and returns 400 for anything else, and /api/stockMovements builds a Hibernate `order(params.sort)` which blows up for `daysLate`. Fix by clearing/resetting the table's sort state whenever `overdue` changes (e.g. call tableRef.current.setState/sortColumn reset or remount the table via a key), or by having getParams drop/translate sort ids that are not valid for the target endpoint.
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Fixed in 41723f3 — the DataTable is now remounted with key={overdue ? 'overdue' : 'inbound'} when the toggle flips, which resets react-table's persisted sort/page state so a sort column valid for one endpoint can no longer be sent to the other.

Comment on lines +47 to +51
Date deliveredDate = shipment.dateDelivered()
def latestEvent = shipment.getMostRecentEvent()
if (deliveredDate || latestEvent?.eventType?.eventCode == EventCode.CANCELLED) {
return null
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Cancelled-latest-event check matches the recorded decision because Event sorts newest-first

getMostRecentEvent() returns events.iterator().next() on a SortedSet whose Event.compareTo deliberately inverts the operands so events sort newest-first (grails-app/domain/org/pih/warehouse/core/Event.groovy:58-69). So the latest-event CANCELLED exclusion here does implement decision 1 in the criteria doc rather than "any CANCELLED event". Worth noting because the naming (getMostRecentEvent) elsewhere coexists with getMostRecentSystemEvent(), which returns the first element of an ascending-sorted copy and therefore has the opposite meaning.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — confirmed: getMostRecentEvent() iterates the newest-first SortedSet, so the exclusion implements decision 1 (latest event is CANCELLED), not "any CANCELLED event". Criterion 7's contract test (cancelled shipment has an earlier SHIPPED event) proves this behavior live.

Comment on lines 145 to 157
Cell: (row) => (
<TableCell
{...row}
tooltip
tooltipLabel={getStatusTooltip(row.value?.name)}
tooltip={Boolean(row.value?.name || row.value)}
tooltipLabel={getStatusTooltip(row.value?.name || row.value)}
>
<StatusIndicator
variant={row?.value?.variant}
status={row?.value?.label}
/>
{overdue ? row.value : (
<StatusIndicator
variant={row?.value?.variant}
status={row?.value?.label}
/>
)}
</TableCell>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Overdue rows render raw status codes and leave several columns blank

In the Overdue view the status cell renders row.value directly, i.e. the raw code such as SHIPPED, instead of the localized StatusIndicator used in the normal view, and the retained stocklist.name, requestedBy.name and dateCreated columns have no counterpart in the overdue payload, so they show empty/None values. Also name's cell still links to STOCK_MOVEMENT_URL.show(row.original.id) using the shipment id even though the identifier column deliberately drops its link in this mode — worth confirming that link resolves for shipment-only rows.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Partially addressed. The undefined-status crash behind this cell is fixed in 4a3c3ad (getStatusTooltip now guards missing values, tooltip only renders when a value exists). On the name link: verified StockMovementController.show() falls back to stockMovementService.getStockMovement(params.id), which resolves shipment ids, so the link works in overdue mode and stays. Raw status codes and blank stocklist/requestedBy/dateCreated cells in the overdue view are an accepted trade-off for this small-scope demo view.

Comment on lines +21 to +25
const [overdue, setOverdue] = useState(false);
const tableFilterParams = useMemo(() => {
if (Object.keys(filterParams).length === 0 && !overdue) return filterParams;
return { ...filterParams, overdue };
}, [filterParams, overdue]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Overdue toggle state is not reflected in the URL query string

overdue lives purely in component state, while every other inbound filter is pushed into the URL by useInboundFilters.setFilterValues. A page reload or link share drops the Overdue view, and useCommonFiltersCleaner's location-change rebuild will not clear it either, so switching warehouses keeps the toggle on while the filter form resets.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — deliberate small-scope choice: the Overdue toggle is ephemeral view state rather than a URL-persisted filter. Persisting it via useInboundFilters/query string is a reasonable follow-up if the view sticks around beyond the demo.

Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>

@staging-devin-ai-integration staging-devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

Open in Devin Review (Staging)
Debug

Playground

)}
</div>
<DataTable
key={overdue ? 'overdue' : 'inbound'}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Remounting the table on toggle causes a duplicate fetch per toggle

Forcing a remount via key resets react-table's internal state (page/sorted), which is what makes the mode switch clean. However, react-table v6 fires onFetchData on mount when manual is set, and in the same commit useTableData's effect on filterParams (src/js/hooks/list-pages/useTableData.jsx:96-98) also calls fireFetchData(). Since toggling Overdue changes both key and filterParams simultaneously, each toggle issues two identical requests to the new endpoint (the mount fetch and the effect fetch). Both write the same payload into state, so behavior is correct, but it doubles server load per toggle and leaves the earlier in-flight request uncancelled (sourceRef.current is replaced without cancelling). Consider gating the effect fetch when the table has just remounted, or dropping key and resetting page/sort explicitly.

Open in Devin Review (Staging)

Was this helpful? React with 👍 or 👎 to provide feedback.

Debug

Playground

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 4 new potential issues.

Open in Devin Review

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Name column still links via the shipment id in Overdue mode

The Name column keeps its STOCK_MOVEMENT_URL.show(stockMovementId) link, and in Overdue mode row.original.id is a Shipment id rather than a stock-movement/requisition id. I verified this still resolves: StockMovementService.getStockMovement(String id) (grails-app/services/org/pih/warehouse/api/StockMovementService.groovy:625-643) falls back to Shipment.get(id) and builds a shipment-based stock movement, so the link works. Note the inconsistency, though: the Identifier column deliberately drops its link in Overdue mode (if (overdue) return <TableCell {...row} />) while the Name column keeps one.

(Refers to lines 188-205)

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — verified the same fallback path, so the Name link resolves for shipment ids and stays. The Identifier link was dropped because that cell's link is built from stock-movement-specific fields that are absent on overdue rows; keeping the one working link (Name) as the row's entry point is intentional.

Comment on lines +74 to +79
Comparator comparator = { Map left, Map right ->
def leftValue = sortValue(left, command.sort)
def rightValue = sortValue(right, command.sort)
compareValues(leftValue, rightValue)
} as Comparator
rows.sort(command.order == "desc" ? comparator.reversed() : comparator)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Overdue shipments list fails to sort in its default order

The list of overdue shipments is ordered by reversing a sort rule that was built from a code block (comparator.reversed() at grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy:79), and Groovy sends that reversal request back into the block itself instead of reversing it, so the request fails instead of returning the list.
Impact: Every default request for overdue inbound shipments (and any request asking for descending order) errors out instead of returning data.

Closure-to-Comparator coercion routes default interface methods back to the closure

Comparator comparator = { Map left, Map right -> ... } as Comparator (grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy:74-78) creates a JDK dynamic proxy backed by Groovy's ConvertedClosure. Because the coercion is done without a target method name, every interface method invoked on that proxy — including the java.util.Comparator default method reversed() — is dispatched to the closure itself rather than to the interface's default implementation. Calling reversed() therefore invokes the two-argument closure with no arguments, raising a MissingMethodException (surfaced as a 500) instead of returning a reversed comparator.

command.order defaults to "desc" (grails-app/controllers/org/pih/warehouse/api/ShipmentExceptionApiController.groovy:43), so this path is taken on every request that does not explicitly pass order=asc, i.e. the documented default behaviour (openapi/specs/shipment-exceptions-api.yaml default sort daysLate descending) and the Overdue view in src/js/components/stock-movement/inbound/StockMovementInboundTable.jsx.

Using an anonymous Comparator implementation (a real class, whose default methods work normally) or sorting ascending and reversing the list avoids the coercion pitfall.

Suggested change
Comparator comparator = { Map left, Map right ->
def leftValue = sortValue(left, command.sort)
def rightValue = sortValue(right, command.sort)
compareValues(leftValue, rightValue)
} as Comparator
rows.sort(command.order == "desc" ? comparator.reversed() : comparator)
Comparator comparator = new Comparator<Map>() {
@Override
int compare(Map left, Map right) {
return compareValues(sortValue(left, command.sort), sortValue(right, command.sort))
}
}
rows.sort(command.order == "desc" ? comparator.reversed() : comparator)
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Checked against live behavior: this doesn't reproduce. On a source build of this branch (Build 41723f3), the default request (order=desc) returns 200 with rows sorted daysLate descending — test_criterion_25_default_sort_is_days_late_descending and the other sort tests pass (30/30, and the UI shows the descending Days Late column). Groovy's ConversionHandler dispatches Comparator default methods like reversed() to the real default implementation rather than the closure in this runtime, so the coercion works. Leaving as-is given the passing live evidence; happy to switch to an explicit Comparator class if reviewers prefer the defensive form.

Comment on lines +219 to +223
row = next(row for row in _rows(client)["data"] if row["shipmentNumber"] == number)
expected_delivery = date.fromisoformat(
client.get_json(f"/api/shipments/{shipment_id}")["data"]["expectedDeliveryDate"][:10]
)
assert row["daysLate"] == (date.today() - expected_delivery).days

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 daysLate assertion depends on the shipment read API's date format

test_criterion_11 parses expectedDeliveryDate with date.fromisoformat(value[:10]). That only works if GET /api/shipments/{id} renders dates in ISO form; several OpenBoxes JSON renderings use locale/MM/dd/yyyy style formats, in which case the test raises ValueError instead of comparing days late. Consider deriving the expected value from the seeded date the fixture used rather than re-reading and parsing the API's date string.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Verified live: GET /api/shipments/{id} renders expectedDeliveryDate in ISO form on this build, and the test passes against a source build (30/30, run twice). Deriving from the fixture's seeded date was avoided deliberately — the module-scoped fixture date could drift from "today" across a midnight boundary, which is exactly the flakiness an earlier review round asked to remove; re-reading the API keeps the assertion self-consistent at call time.

Comment on lines 294 to +295
<DataTable
key={overdue ? 'overdue' : 'inbound'}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Toggling Overdue triggers two fetches

Changing overdue both changes tableFilterParams (so useTableData's useEffect on filterParams calls fireFetchData()) and changes the key on DataTable, which remounts react-table and fires its own initial onFetchData. The result is two requests per toggle. Harmless functionally (the later response wins and the cancel token is per-fetch), but the remount key could be dropped if resetting sort/page state is not actually required.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Acknowledged — the remount key is required: react-table's persisted sorted state otherwise leaks a sort column that is invalid on the other endpoint (400 / Hibernate error). The duplicate fetch per toggle is an accepted minor cost since the later response wins and each fetch has its own cancel token.

@devin-ai-integration

Copy link
Copy Markdown

Act 3 re-verification after review fixes (Devin)

Re-tested on 41723f387 against a source build (frontend bundle rebuilt under Node 14, WAR + Docker image rebuilt, footer shows Build 41723f3). The blank-page crash reported earlier is fixed — the full populated flow now works.

Populated Overdue flow, no workarounds

Starting from the real list (Inbound (42), Export visible) sorted by Date Created, clicking Overdue: page renders (no blank screen), count drops to Inbound (19), right-most Days Late column shows 10, 6, 4… descending, Export hidden, no error toast, console clean (the stale dateCreated sort is dropped by the key-based DataTable remount, so no HTTP 400 from an unsupported sort). Clicking Stocklist / Date Created headers in Overdue mode does nothing — same row order, no arrows, no error. Toggling Overdue off restores Inbound (42) with Export, no crash.

Populated Overdue view with Days Late

Recorded flow

Before the fix, for reference — clicking Overdue blanked the page

TypeError: Cannot read properties of undefined (reading 'toLowerCase') from the status cell; toggling back off crashed identically.

Pre-fix crash

Contract suite
  • test_shipment_exceptions_api_contract.py: 30 passed / 0 skipped / 0 failed in 6.16s (guard did not skip → endpoint present in the source build)
  • Full characterization/contract/run.sh: 899 passed / 45 skipped / 2 failed in 41.49s. Failures are in files this PR does not touch and appear pre-existing: test_location_group_api_contract.py::test_read_unknown (404 not declared in location-group-api.yaml) and test_shipment_screens_api_contract.py::test_add_to_shipment (400 vs 200). No clean base-branch baseline run was performed to formally prove it.
  • Caveat: the new _event_type_id self-seeding of DELIVERED/CANCELLED could not be exercised locally — those event types already existed in the test DB, so the POST /api/eventTypes branch never ran. A fresh-DB / CI run is what proves it.
  • Frontend lint on the touched files (Node 14): 0 errors, 13 warnings (pre-existing rule classes).

@devin-ai-integration
devin-ai-integration Bot merged commit b6472c4 into spec-demo-base Aug 20, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant