Repository navigation
Overdue inbound shipments: endpoint, contract tests, and inbound list Overdue view (spec-driven Act 2) - #3
Conversation
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
| 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() |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
📝 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| 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 | ||
| } |
There was a problem hiding this comment.
📝 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Acknowledged — agreed this is moot for the current sort fields since all returned values are non-null; noted for any future nullable sort keys.
| if (filterParams.overdue) { | ||
| return _.omitBy({ | ||
| origin: origin?.id, | ||
| destination: destination?.id, | ||
| offset: `${offset}`, | ||
| max: `${state.pageSize}`, | ||
| ...sortingParams, | ||
| }, (value) => !value); | ||
| } |
There was a problem hiding this comment.
📝 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
"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.
| List<Shipment> shipments = Shipment.createCriteria().list { | ||
| isNotNull("expectedDeliveryDate") | ||
| lt("expectedDeliveryDate", startOfToday) | ||
| inList("destination", inboundLocations) | ||
| if (origin) { | ||
| eq("origin", origin) | ||
| } | ||
| if (destination) { | ||
| eq("destination", destination) | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
Debug
There was a problem hiding this comment.
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.
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
| origin(nullable: true, blank: true) | ||
| destination(nullable: true, blank: true) |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
Debug
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
|
|
||
| spec = Spec("shipment-exceptions-api.yaml") | ||
| TEST_PREFIX = "ZZ Contract Shipment Exception" | ||
| pytestmark = pytest.mark.usefixtures("shipment_exception_endpoints") |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
Debug
Co-Authored-By: Matthew Guerra <matthew.guerra@cognition.ai>
| 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"] |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
Debug
| onFetchHandler, | ||
| } = useTableData({ | ||
| filterParams, | ||
| url: STOCK_MOVEMENT_API, | ||
| url: filterParams.overdue ? SHIPMENT_EXCEPTIONS_OVERDUE_API : STOCK_MOVEMENT_API, |
There was a problem hiding this comment.
🔴 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,identifierororigin.name, that id is still sent assortto/api/shipments/exceptions/overdue.ShipmentExceptionCommand.sortonly acceptsdaysLate,expectedDeliveryDate,shipmentNumber,origin,destination(grails-app/controllers/org/pih/warehouse/api/ShipmentExceptionApiController.groovy:53-55), so the request fails validation with 400. Marking the columnssortable: !overdueprevents new clicks but does not clear an existing selection. - Overdue → normal view:
sort=daysLate(ororigin) is sent to/api/stockMovements, where it falls through toorder(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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| Date deliveredDate = shipment.dateDelivered() | ||
| def latestEvent = shipment.getMostRecentEvent() | ||
| if (deliveredDate || latestEvent?.eventType?.eventCode == EventCode.CANCELLED) { | ||
| return null | ||
| } |
There was a problem hiding this comment.
📝 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| 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> |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| const [overdue, setOverdue] = useState(false); | ||
| const tableFilterParams = useMemo(() => { | ||
| if (Object.keys(filterParams).length === 0 && !overdue) return filterParams; | ||
| return { ...filterParams, overdue }; | ||
| }, [filterParams, overdue]); |
There was a problem hiding this comment.
📝 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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>
| )} | ||
| </div> | ||
| <DataTable | ||
| key={overdue ? 'overdue' : 'inbound'} |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
Debug
There was a problem hiding this comment.
📝 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)
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
🔴 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.
| 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) |
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
🔍 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
| <DataTable | ||
| key={overdue ? 'overdue' : 'inbound'} |
There was a problem hiding this comment.
📝 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
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.
Act 3 re-verification after review fixes (Devin)Re-tested on Populated Overdue flow, no workaroundsStarting from the real list ( Before the fix, for reference — clicking Overdue blanked the page
Contract suite
|
✨ 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/overdueexactly per the agreed contract (openapi/specs/shipment-exceptions-api.yaml+ acceptance criteria doc), end to end:ShipmentExceptionApiController.overdue()with aValidateablecommand object (invalid params surface through the sharedValidationException→errors/handleValidationErrorspath), a newShipmentExceptionService.getOverdueInboundShipments()(criteria pre-filter onexpectedDeliveryDate < today+ destination in session warehouse & child locations, then event-based exclusions viadateDelivered()/ latest-eventCANCELLED, midnight-truncateddaysLate, 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.shipment-exceptions-acceptance-criteria.mdare now a "Decisions" section (cancelled = latest eventCANCELLED; partially received stays; inbound = session warehouse or child location;daysLate= floored whole days, server clock; never-shipped past-due included).characterization/contract/test_shipment_exceptions_api_contract.py(+ ashipment_exception_endpointsconftest guard that skips on builds predating the endpoint). Seeding is API-based (POST /api/shipments + shipment events) with ZZ-prefixed names and cleanup./openboxes/stockMovement/list?direction=INBOUND) that fetches from the new endpoint and shows aDays Latecolumn.Criterion → test mapping
test_criterion_01_overdue_unreceived_inbound_is_includedtest_criterion_02_future_expected_delivery_is_excludedtest_criterion_03_today_expected_delivery_is_excludedtest_criterion_04_received_shipments_are_excludedtest_criterion_05_received_or_delivered_shipments_are_excludedtest_criterion_06_null_expected_delivery_is_excludedtest_criterion_07_latest_cancelled_event_is_excludedtest_criterion_08_only_inbound_shipments_are_includedtest_criterion_09_inbound_is_relative_to_session_warehousetest_criterion_10_partially_received_without_delivery_is_includedtest_criterion_11_days_late_is_calendar_daystest_criterion_12_days_late_meets_thresholdtest_criterion_13_days_late_is_positive_integertest_criterion_14_default_threshold_is_one_daytest_criterion_15_min_days_late_filterstest_criterion_16_min_days_late_below_one_is_rejectedtest_criterion_17_origin_filtertest_criterion_18_destination_filtertest_criterion_19_unknown_filter_ids_are_not_errorstest_criterion_20_response_envelopetest_criterion_21_default_max_is_fiftytest_criterion_22_max_above_five_hundred_is_rejectedtest_criterion_23_total_count_ignores_paginationtest_criterion_24_offset_pagestest_criterion_25_default_sort_is_days_late_descendingtest_criterion_26_expected_delivery_date_sort_is_honouredtest_criterion_27_location_name_sort_is_case_insensitivetest_criterion_28_unsupported_sort_is_rejectedtest_criterion_29_session_is_requiredtest_criterion_30_warehouse_is_requiredCoverage caveats (honest gaps within otherwise-covered criteria):
daysLatecomputed from the seeded date vs today at assertion time) but not truncation of a late-evening timestamp.origin.idmatches 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 Build41723f3).npx @redocly/cli@1.34.2 lint --config openapi/redocly.yaml 'openapi/specs/*.yaml' openapi/components/common.yaml): clean.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.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 inlocation-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 onspec-demo-basewas not performed to prove it.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).Days Latecolumn, 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/destinationmade nullable in the command object, status-cell crash on toggle fixed, DataTable sort state reset on toggle, and contract-test fixtures now self-create missingDELIVERED/CANCELLEDevent 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):
Devin-Org: engineering
Link to Devin session: https://app.devin.ai/sessions/ffbe8c28fa6e4dcf8c6e6c0bf758d7f6
Requested by: @matthewguerra-cog
Devin Review
41723f3