diff --git a/characterization/contract/conftest.py b/characterization/contract/conftest.py index 25fb30718b5..21844e6660b 100644 --- a/characterization/contract/conftest.py +++ b/characterization/contract/conftest.py @@ -74,6 +74,12 @@ def batch22_endpoints(client): pytest.skip("Batch 22 shipment screen endpoints not present in target build") +@pytest.fixture(scope="session") +def shipment_exception_endpoints(client): + if client.request("GET", "/api/shipments/exceptions/overdue").status_code == 404: + pytest.skip("shipment exception endpoint not present in target build") + + @pytest.fixture(scope="session") def batch41_endpoints(client): # Same rationale as batch14_endpoints for the Batch 41 admin/auth/batch/ diff --git a/characterization/contract/test_shipment_exceptions_api_contract.py b/characterization/contract/test_shipment_exceptions_api_contract.py new file mode 100644 index 00000000000..e5ae2530398 --- /dev/null +++ b/characterization/contract/test_shipment_exceptions_api_contract.py @@ -0,0 +1,384 @@ +"""Contract tests for GET /api/shipments/exceptions/overdue.""" + +from datetime import date, timedelta + +import pytest +import requests + +from oas import Spec, check + +spec = Spec("shipment-exceptions-api.yaml") +TEST_PREFIX = "ZZ Contract Shipment Exception" +pytestmark = pytest.mark.usefixtures("shipment_exception_endpoints") + + +def _shipment_options(client): + return client.get_json("/api/shipments/wizardOptions")["data"] + + +def _event_type_id(client, event_code): + event_types = client.get_json( + "/api/eventTypes", params={"max": 100} + )["data"] + matches = [event for event in event_types if event.get("eventCode") == event_code] + 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"] + + +def _create_shipment(client, name, destination=None, expected_delivery=None, + origin=None): + options = _shipment_options(client) + destination = destination or client.location_id("Main Warehouse") + origin = origin or client.location_id("Main Supplier") + response = client.request("POST", "/api/shipments", json={ + "name": name, + "shipmentTypeId": options["shipmentTypes"][0]["id"], + "originId": origin, + "destinationId": destination, + "expectedShippingDate": (date.today() - timedelta(days=10)).isoformat(), + }) + assert response.status_code == 201 + shipment_id = response.json()["data"]["id"] + if expected_delivery is not None: + response = client.request( + "POST", f"/api/shipments/{shipment_id}/details", + json={"expectedDeliveryDate": expected_delivery}, + ) + assert response.status_code == 200 + return shipment_id + + +def _add_event(client, shipment_id, event_code, event_date=None): + response = client.request( + "POST", f"/api/shipments/{shipment_id}/events", + json={ + "eventTypeId": _event_type_id(client, event_code), + "eventDate": event_date or "2020-01-01 10:00", + "eventLocationId": client.location_id("Main Warehouse"), + }, + ) + assert response.status_code == 201 + return response.json()["data"]["id"] + + +def _delete_shipment(client, shipment_id): + client.request("DELETE", f"/api/generic/shipment/{shipment_id}") + + +def _rows(client, **params): + response = check( + client, spec, "GET", "/api/shipments/exceptions/overdue", + path="/api/shipments/exceptions/overdue", params=params, + ) + assert response.status_code == 200 + return response.json() + + +def _shipment_number(client, shipment_id): + return client.get_json(f"/api/shipments/{shipment_id}")["data"]["shipmentNumber"] + + +@pytest.fixture(scope="module") +def exception_shipments(client, shipment_exception_endpoints): + yesterday = date.today() - timedelta(days=1) + created = {} + definitions = { + "overdue": yesterday - timedelta(days=2), + "future": date.today() + timedelta(days=3), + "today": date.today(), + "received": yesterday - timedelta(days=2), + "delivered": yesterday - timedelta(days=2), + "cancelled": yesterday - timedelta(days=2), + "partial": yesterday - timedelta(days=2), + "pending": yesterday - timedelta(days=6), + "three_late": yesterday - timedelta(days=2), + "seven_late": yesterday - timedelta(days=6), + } + for key, expected_delivery in definitions.items(): + shipment_id = _create_shipment( + client, f"{TEST_PREFIX} {key}", expected_delivery=expected_delivery.isoformat(), + ) + created[key] = shipment_id + + _add_event(client, created["overdue"], "SHIPPED") + _add_event(client, created["received"], "RECEIVED") + _add_event(client, created["delivered"], "PARTIALLY_RECEIVED") + _add_event(client, created["delivered"], "DELIVERED", "2020-01-02 10:00") + _add_event(client, created["cancelled"], "SHIPPED") + _add_event(client, created["cancelled"], "CANCELLED", "2020-01-02 10:00") + _add_event(client, created["partial"], "PARTIALLY_RECEIVED") + + yield created + for shipment_id in created.values(): + _delete_shipment(client, shipment_id) + + +def test_criterion_01_overdue_unreceived_inbound_is_included(client, exception_shipments): + """Criterion 1: an overdue, unreceived inbound shipment is included.""" + number = _shipment_number(client, exception_shipments["overdue"]) + assert number in {row["shipmentNumber"] for row in _rows(client)["data"]} + + +def test_criterion_02_future_expected_delivery_is_excluded(client, exception_shipments): + """Criterion 2: a future expected delivery date is excluded.""" + number = _shipment_number(client, exception_shipments["future"]) + assert number not in {row["shipmentNumber"] for row in _rows(client)["data"]} + + +def test_criterion_03_today_expected_delivery_is_excluded(client, exception_shipments): + """Criterion 3: an expected delivery date of today is excluded.""" + number = _shipment_number(client, exception_shipments["today"]) + assert number not in {row["shipmentNumber"] for row in _rows(client)["data"]} + + +def test_criterion_04_received_shipments_are_excluded(client, exception_shipments): + """Criterion 4: received shipments are excluded.""" + body = _rows(client) + number = _shipment_number(client, exception_shipments["received"]) + assert number not in {row["shipmentNumber"] for row in body["data"]} + assert all(row["status"] != "RECEIVED" for row in body["data"]) + + +def test_criterion_05_received_or_delivered_shipments_are_excluded(client, exception_shipments): + """Criterion 5: received or delivered shipments are excluded.""" + number = _shipment_number(client, exception_shipments["delivered"]) + assert number not in {row["shipmentNumber"] for row in _rows(client)["data"]} + + +def test_criterion_06_null_expected_delivery_is_excluded(client): + """Criterion 6: a null expected delivery date is excluded.""" + shipment_id = _create_shipment(client, f"{TEST_PREFIX} null") + try: + body = _rows(client) + number = _shipment_number(client, shipment_id) + assert number not in {row["shipmentNumber"] for row in body["data"]} + assert all(row["expectedDeliveryDate"] is not None for row in body["data"]) + finally: + _delete_shipment(client, shipment_id) + + +def test_criterion_07_latest_cancelled_event_is_excluded(client, exception_shipments): + """Criterion 7: a shipment whose latest event is CANCELLED is excluded.""" + number = _shipment_number(client, exception_shipments["cancelled"]) + assert number not in {row["shipmentNumber"] for row in _rows(client)["data"]} + + +def test_criterion_08_only_inbound_shipments_are_included(client, exception_shipments): + """Criterion 8: only inbound shipments are included.""" + warehouse = client.location_id("Main Warehouse") + outbound = _create_shipment( + client, f"{TEST_PREFIX} outbound", + destination=client.location_id("Main Supplier"), + origin=warehouse, + expected_delivery=(date.today() - timedelta(days=3)).isoformat(), + ) + try: + body = _rows(client) + assert all(row["destination"]["id"] == warehouse for row in body["data"]) + assert _shipment_number(client, outbound) not in { + row["shipmentNumber"] for row in body["data"] + } + finally: + _delete_shipment(client, outbound) + + +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("Boston Warehouse") + 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.""" + shipment_id = exception_shipments["overdue"] + number = _shipment_number(client, shipment_id) + 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 + + +def test_criterion_12_days_late_meets_threshold(client): + """Criterion 12: every row meets the effective threshold.""" + body = _rows(client, minDaysLate=3) + assert all(row["daysLate"] >= 3 for row in body["data"]) + + +def test_criterion_13_days_late_is_positive_integer(client): + """Criterion 13: every daysLate value is an integer at least one.""" + assert all(isinstance(row["daysLate"], int) and row["daysLate"] >= 1 + for row in _rows(client)["data"]) + + +def test_criterion_14_default_threshold_is_one_day(client, exception_shipments): + """Criterion 14: the default threshold is one day.""" + body = _rows(client) + numbers = {row["shipmentNumber"] for row in body["data"]} + assert _shipment_number(client, exception_shipments["today"]) not in numbers + assert _shipment_number(client, exception_shipments["overdue"]) in numbers + + +def test_criterion_15_min_days_late_filters(client, exception_shipments): + """Criterion 15: minDaysLate filters returned rows.""" + body = _rows(client, minDaysLate=5) + numbers = {row["shipmentNumber"] for row in body["data"]} + assert _shipment_number(client, exception_shipments["three_late"]) not in numbers + assert _shipment_number(client, exception_shipments["seven_late"]) in numbers + assert all(row["daysLate"] >= 5 for row in body["data"]) + + +def test_criterion_16_min_days_late_below_one_is_rejected(client): + """Criterion 16: minDaysLate below one returns a validation error.""" + response = check( + client, spec, "GET", "/api/shipments/exceptions/overdue", + path="/api/shipments/exceptions/overdue", params={"minDaysLate": 0}, + ) + assert response.status_code == 400 + assert response.json()["errorCode"] == 400 + + +def test_criterion_17_origin_filter(client, exception_shipments): + """Criterion 17: origin filters qualifying shipments.""" + origin = client.location_id("Main Supplier") + body = _rows(client, origin=origin) + assert all(row["origin"]["id"] == origin for row in body["data"]) + + +def test_criterion_18_destination_filter(client, exception_shipments): + """Criterion 18: destination filters qualifying shipments.""" + warehouse = client.location_id("Main Warehouse") + body = _rows(client, destination=warehouse) + assert body["data"] + unrelated = client.location_id("Main Supplier") + body = _rows(client, destination=unrelated) + assert body["data"] == [] and body["totalCount"] == 0 + + +def test_criterion_19_unknown_filter_ids_are_not_errors(client): + """Criterion 19: unknown filter ids return an empty successful page.""" + body = _rows(client, origin="does-not-exist") + assert body["data"] == [] and body["totalCount"] == 0 + + +def test_criterion_20_response_envelope(client): + """Criterion 20: the response includes the complete pagination envelope.""" + body = _rows(client) + assert {"data", "count", "max", "offset", "totalCount"} <= body.keys() + assert body["count"] == len(body["data"]) + + +def test_criterion_21_default_max_is_fifty(client): + """Criterion 21: max defaults to fifty.""" + assert _rows(client)["max"] == 50 + + +def test_criterion_22_max_above_five_hundred_is_rejected(client): + """Criterion 22: max above five hundred returns a validation error.""" + response = check( + client, spec, "GET", "/api/shipments/exceptions/overdue", + path="/api/shipments/exceptions/overdue", params={"max": 501}, + ) + assert response.status_code == 400 + assert response.json()["errorCode"] == 400 + + +def test_criterion_23_total_count_ignores_pagination(client, exception_shipments): + """Criterion 23: totalCount ignores pagination.""" + body = _rows(client, max=1) + assert body["count"] == 1 + assert body["totalCount"] >= 3 + + +def test_criterion_24_offset_pages(client, exception_shipments): + """Criterion 24: offset returns a different page.""" + first = _rows(client, max=1, offset=0) + second = _rows(client, max=1, offset=1) + assert first["offset"] == 0 + assert second["offset"] == 1 + assert first["data"][0]["id"] != second["data"][0]["id"] + + +def test_criterion_25_default_sort_is_days_late_descending(client): + """Criterion 25: default sorting is daysLate descending.""" + values = [row["daysLate"] for row in _rows(client)["data"]] + assert values == sorted(values, reverse=True) + + +def test_criterion_26_expected_delivery_date_sort_is_honoured(client): + """Criterion 26: expectedDeliveryDate sorting is honoured.""" + values = [row["expectedDeliveryDate"] for row in _rows( + client, sort="expectedDeliveryDate", order="asc", + )["data"]] + assert values == sorted(values) + + +def test_criterion_27_location_name_sort_is_case_insensitive(client): + """Criterion 27: location-name sorting is case-insensitive.""" + values = [row["origin"]["name"].lower() for row in _rows( + client, sort="origin", order="asc", + )["data"]] + assert values == sorted(values) + + +def test_criterion_28_unsupported_sort_is_rejected(client): + """Criterion 28: unsupported sort values return a validation error.""" + response = check( + client, spec, "GET", "/api/shipments/exceptions/overdue", + path="/api/shipments/exceptions/overdue", params={"sort": "carrier"}, + ) + assert response.status_code == 400 + assert response.json()["errorCode"] == 400 + + +def test_criterion_29_session_is_required(): + """Criterion 29: an unauthenticated session returns 401.""" + from obx import BASE_URL + + anonymous = requests.Session() + response = anonymous.get( + f"{BASE_URL}/api/shipments/exceptions/overdue", + headers={"Accept": "application/json"}, + timeout=120, + ) + assert response.status_code == 401 + assert response.json()["errorCode"] == 401 + + +def test_criterion_30_warehouse_is_required(client): + """Criterion 30: an authenticated session without a warehouse returns 400.""" + from obx import PASSWORD, USERNAME, ApiClient + + no_location = ApiClient() + no_location.session.headers["Accept"] = "application/json" + no_location.session.post( + f"{no_location.base_url}/api/login", + json={"username": USERNAME, "password": PASSWORD}, + ).raise_for_status() + response = no_location.request("GET", "/api/shipments/exceptions/overdue") + assert response.status_code == 400 + assert response.json()["errorCode"] == 400 diff --git a/grails-app/controllers/org/pih/warehouse/UrlMappings.groovy b/grails-app/controllers/org/pih/warehouse/UrlMappings.groovy index 4487a84e7ef..46c5a666a98 100644 --- a/grails-app/controllers/org/pih/warehouse/UrlMappings.groovy +++ b/grails-app/controllers/org/pih/warehouse/UrlMappings.groovy @@ -1259,6 +1259,11 @@ class UrlMappings { action = [GET: "listOptions"] } + "/api/shipments/exceptions/overdue" { + controller = "shipmentExceptionApi" + action = [GET: "overdue"] + } + "/api/shipments/bulkAction"(parseRequest: true) { controller = "shipmentApi" action = [POST: "bulkAction"] diff --git a/grails-app/controllers/org/pih/warehouse/api/ShipmentExceptionApiController.groovy b/grails-app/controllers/org/pih/warehouse/api/ShipmentExceptionApiController.groovy new file mode 100644 index 00000000000..97f3be77c19 --- /dev/null +++ b/grails-app/controllers/org/pih/warehouse/api/ShipmentExceptionApiController.groovy @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2012 Partners In Health. All rights reserved. + * The use and distribution terms for this software are covered by the + * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) + * which can be found in the file epl-v10.html at the root of this distribution. + * By using this software in any fashion, you are agreeing to be bound by + * the terms of this license. + **/ +package org.pih.warehouse.api + +import grails.converters.JSON +import grails.validation.Validateable +import grails.validation.ValidationException +import org.pih.warehouse.core.Location +import org.pih.warehouse.shipping.ShipmentExceptionService + +class ShipmentExceptionApiController { + + ShipmentExceptionService shipmentExceptionService + + def overdue(ShipmentExceptionCommand command) { + if (!command.validate()) { + throw new ValidationException("Invalid filters", command.errors) + } + + Location warehouse = Location.get(session.warehouse?.id) + if (!warehouse) { + command.errors.reject("warehouse", "A warehouse must be selected") + throw new ValidationException("A warehouse must be selected", command.errors) + } + + Map result = shipmentExceptionService.getOverdueInboundShipments(warehouse, command) + render(result as JSON) + } +} + +class ShipmentExceptionCommand implements Validateable { + + String origin + String destination + Integer minDaysLate = 1 + String sort = "daysLate" + String order = "desc" + Integer max = 50 + Integer offset = 0 + + static constraints = { + origin(nullable: true, blank: true) + destination(nullable: true, blank: true) + minDaysLate(min: 1) + max(min: 0, max: 500) + offset(min: 0) + sort(validator: { value, command -> + value in ["daysLate", "expectedDeliveryDate", "shipmentNumber", "origin", "destination"] ? true : ["invalid"] + }) + order(validator: { value, command -> + value in ["asc", "desc"] ? true : ["invalid"] + }) + } +} diff --git a/grails-app/i18n/messages.properties b/grails-app/i18n/messages.properties index 4a56c6e5d12..eccb253c8c1 100644 --- a/grails-app/i18n/messages.properties +++ b/grails-app/i18n/messages.properties @@ -4304,6 +4304,8 @@ react.stockMovement.column.identifier.label=Identifier react.stockMovement.column.name.label=Name react.stockMovement.column.dateCreated.label=Date Created react.stockMovement.column.expectedReceiptDate=Expected Receipt Date +react.stockMovement.column.daysLate.label=Days Late +react.stockMovement.overdue.label=Overdue react.stockMovement.outbound.filters.requisitionStatus.label=Requisition Status react.stockMovement.outbound.filters.requestType.label=Request type react.stockMovement.outbound.column.dateRequested.label=Date Requested diff --git a/grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy b/grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy new file mode 100644 index 00000000000..a35a0cd18ba --- /dev/null +++ b/grails-app/services/org/pih/warehouse/shipping/ShipmentExceptionService.groovy @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2012 Partners In Health. All rights reserved. + * The use and distribution terms for this software are covered by the + * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) + * which can be found in the file epl-v10.html at the root of this distribution. + **/ +package org.pih.warehouse.shipping + +import grails.gorm.transactions.Transactional +import org.pih.warehouse.api.ShipmentExceptionCommand +import org.pih.warehouse.core.EventCode +import org.pih.warehouse.core.Location + +import java.time.LocalDate +import java.time.ZoneId +import java.time.temporal.ChronoUnit + +@Transactional(readOnly = true) +class ShipmentExceptionService { + + Map getOverdueInboundShipments(Location warehouse, ShipmentExceptionCommand command) { + List inboundLocations = [warehouse] + Location.findAllByParentLocation(warehouse) + Location origin = command.origin ? Location.get(command.origin) : null + Location destination = command.destination ? Location.get(command.destination) : null + + if ((command.origin && !origin) || (command.destination && !destination) || + (destination && !inboundLocations*.id.contains(destination.id))) { + return page([], command) + } + + Date startOfToday = new Date().clearTime() + List 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 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() + + 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) + page(rows, command) + } + + private static Map locationReference(Location location) { + [ + id : location.id, + name : location.name, + locationNumber: location.locationNumber, + ] + } + + private static Object sortValue(Map row, String sort) { + switch (sort) { + case "origin": + case "destination": + return row[sort]?.name?.toLowerCase() + default: + return row[sort] + } + } + + 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 + } + + private static Map page(List rows, ShipmentExceptionCommand command) { + int from = Math.min(command.offset, rows.size()) + int to = Math.min(from + command.max, rows.size()) + List data = rows.subList(from, to) + [ + data : data, + count : data.size(), + max : command.max, + offset : command.offset, + totalCount: rows.size(), + ] + } +} diff --git a/openapi/specs/shipment-exceptions-acceptance-criteria.md b/openapi/specs/shipment-exceptions-acceptance-criteria.md index dccb6e974bb..3672385db4e 100644 --- a/openapi/specs/shipment-exceptions-acceptance-criteria.md +++ b/openapi/specs/shipment-exceptions-acceptance-criteria.md @@ -37,8 +37,9 @@ session bound to a warehouse via `POST /api/chooseLocation/{locationId}`. `expectedDeliveryDate`. 7. **Cancelled shipments are excluded.** A shipment with a past `expectedDeliveryDate` that carries a shipment event with - `EventCode.CANCELLED` does not appear. (There is no `CANCELLED` - `ShipmentStatusCode`; cancellation is event-based — see open question 1.) + `EventCode.CANCELLED` as its latest event does not appear. (There is no + `CANCELLED` `ShipmentStatusCode`; cancellation is event-based — see + decision 1.) 8. **Only inbound shipments are included.** A shipment whose `origin` is the session warehouse and whose `destination` is another location does not appear; every row in `data` has `destination.id` equal to the session @@ -51,7 +52,7 @@ session bound to a warehouse via `POST /api/chooseLocation/{locationId}`. `expectedDeliveryDate`, derived status `PARTIALLY_RECEIVED`, and neither a `RECEIVED` nor a `DELIVERED` event appears, because part of the goods is still outstanding. The received/delivered exclusion takes precedence when - either event exists (see open question 2). + either event exists (see decision 2). ## daysLate @@ -115,25 +116,18 @@ session bound to a warehouse via `POST /api/chooseLocation/{locationId}`. no warehouse selected, the endpoint responds `400` with the shared validation error body (`errorCode` 400). -## Open questions for the human +## Decisions -1. **Cancellation semantics.** `ShipmentStatusCode` has no `CANCELLED` value; - the only cancellation signal is a shipment event with - `EventCode.CANCELLED`. Criterion 7 assumes "cancelled" means "has a - CANCELLED event, and that event is the latest one". Confirm, or name the - signal you actually want. -2. **Partially received shipments.** Criterion 10 reports them as still - overdue only when there is neither a `RECEIVED` nor a `DELIVERED` event; - `dateDelivered()` resolves those events and exclusion takes precedence. - Confirm — the alternative is to exclude anything with any receipt. -3. **Inbound definition.** The contract defines inbound as - `destination` = session warehouse (or a child location of it). Confirm that - is the right notion of "relative to the requesting location", rather than, - say, any location the user has access to. -4. **Time zone / clock.** `daysLate` is a calendar-day difference using the - server time zone. Confirm that time zone is acceptable, or specify whether - a client-supplied `asOfDate` is wanted. -5. **Overdue vs. never shipped.** A shipment still in derived status `PENDING` - (not-yet-shipped) past its expected delivery date is reported (it is late). - Confirm you want those, or restrict to shipments that have actually - shipped. +1. **Cancellation semantics — decided.** `ShipmentStatusCode` has no + `CANCELLED` value. A shipment is cancelled when its **latest** event has + `EventCode.CANCELLED`; those shipments are excluded. +2. **Partially received shipments — decided.** Partially received shipments + stay in the list. They are excluded only when a `RECEIVED` or `DELIVERED` + event exists, meaning `dateDelivered()` is non-null. +3. **Inbound definition — decided.** Inbound means the shipment destination + is the session warehouse or one of its child locations. +4. **Time zone / clock — decided.** `daysLate` is floored whole calendar + days using the server clock and time zone; both dates are truncated to + midnight. There is no client-supplied `asOfDate`. +5. **Overdue vs. never shipped — decided.** Shipments in derived status + `PENDING` that are past due are included. diff --git a/src/js/api/urls.js b/src/js/api/urls.js index ad146de3f4c..946ae4ffc22 100644 --- a/src/js/api/urls.js +++ b/src/js/api/urls.js @@ -13,6 +13,7 @@ export const PURCHASE_ORDER_ROLLBACK_ORDER = (id) => `${PURCHASE_ORDER_API}/${id // STOCK MOVEMENT export const STOCK_MOVEMENT_API = `${API}/stockMovements`; +export const SHIPMENT_EXCEPTIONS_OVERDUE_API = `${API}/shipments/exceptions/overdue`; export const STOCK_MOVEMENT_BY_ID = (id) => `${STOCK_MOVEMENT_API}/${id}`; export const STOCK_MOVEMENT_PENDING_SHIPMENT_ITEMS = `${STOCK_MOVEMENT_API}/pendingRequisitionItems`; export const STOCK_MOVEMENT_INCOMING_ITEMS = `${STOCK_MOVEMENT_API}/shippedItems`; diff --git a/src/js/components/stock-movement/inbound/StockMovementInboundFilters.jsx b/src/js/components/stock-movement/inbound/StockMovementInboundFilters.jsx index 18195559f13..38cde712baf 100644 --- a/src/js/components/stock-movement/inbound/StockMovementInboundFilters.jsx +++ b/src/js/components/stock-movement/inbound/StockMovementInboundFilters.jsx @@ -4,6 +4,7 @@ import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import FilterForm from 'components/Filter/FilterForm'; +import Button from 'components/form-elements/Button'; import { debounceLocationsFetch, debouncePeopleFetch, debounceUsersFetch } from 'utils/option-utils'; const StockMovementInboundFilters = ({ @@ -13,6 +14,8 @@ const StockMovementInboundFilters = ({ formProps, filterFields, defaultValues, + overdue, + setOverdue, }) => { const fetchUsers = useCallback( debounceUsersFetch(debounceTime, minSearchLength), @@ -34,6 +37,14 @@ const StockMovementInboundFilters = ({ return (
+
+
{ setFilterValues, filterParams, } = useInboundFilters(); + const [overdue, setOverdue] = useState(false); + const tableFilterParams = useMemo(() => { + if (Object.keys(filterParams).length === 0 && !overdue) return filterParams; + return { ...filterParams, overdue }; + }, [filterParams, overdue]); useTranslation('stockMovement', 'reactTable'); @@ -32,8 +37,10 @@ const StockMovementInboundList = (props) => { shipmentStatuses: props.shipmentStatuses, shipmentTypes: props.shipmentTypes, }} + overdue={overdue} + setOverdue={setOverdue} /> - +
); }; diff --git a/src/js/components/stock-movement/inbound/StockMovementInboundTable.jsx b/src/js/components/stock-movement/inbound/StockMovementInboundTable.jsx index cde9f507ea8..63b3a1ae052 100644 --- a/src/js/components/stock-movement/inbound/StockMovementInboundTable.jsx +++ b/src/js/components/stock-movement/inbound/StockMovementInboundTable.jsx @@ -31,6 +31,7 @@ const StockMovementInboundTable = ({ shipmentStatuses, currentLocation, isUserAdmin, + overdue, }) => { const { tableData, @@ -42,13 +43,18 @@ const StockMovementInboundTable = ({ deleteConfirmAlert, } = useInboundListTableData(filterParams); - const getStatusTooltip = (status) => translate( - `react.stockMovement.status.${status.toLowerCase()}.description.label`, - status.toLowerCase(), - ); + const getStatusTooltip = (status) => { + if (!status) return null; + const statusKey = status.toLowerCase(); + return translate( + `react.stockMovement.status.${statusKey}.description.label`, + statusKey, + ); + }; // List of all actions for inbound Stock Movement rows const getActions = useCallback((row) => { + if (overdue) return []; const { id, isPending, isReturn, order, origin, isReceived, isPartiallyReceived, } = row.original; @@ -99,7 +105,7 @@ const StockMovementInboundTable = ({ } } return actions; - }, []); + }, [overdue]); // Columns for react-table const columns = useMemo(() => [ @@ -110,17 +116,19 @@ const StockMovementInboundTable = ({ style: { overflow: 'visible', zIndex: 1 }, fixed: 'left', Cell: (row) => ( - + overdue ? null : ( + + ) ), }, { Header: , - accessor: 'lineItemCount', + accessor: overdue ? 'shipmentItemCount' : 'lineItemCount', fixed: 'left', className: 'active-circle d-flex justify-content-center', headerClassName: 'header justify-content-center', @@ -130,30 +138,33 @@ const StockMovementInboundTable = ({ }, { Header: , - accessor: 'displayStatus', + accessor: overdue ? 'status' : 'displayStatus', fixed: 'left', width: 170, sortable: false, Cell: (row) => ( - + {overdue ? row.value : ( + + )} ), }, { Header: , - accessor: 'identifier', + accessor: overdue ? 'shipmentNumber' : 'identifier', headerClassName: 'header justify-content-center', fixed: 'left', minWidth: 130, Cell: (row) => { + if (overdue) return ; const { isReturn, order, id, shipmentType, } = row.original; @@ -196,12 +207,14 @@ const StockMovementInboundTable = ({ { Header: , accessor: 'origin.name', + id: overdue ? 'origin' : undefined, minWidth: 250, Cell: (row) => (), }, { Header: , accessor: 'stocklist.name', + sortable: !overdue, minWidth: 150, Cell: (row) => (), }, @@ -215,6 +228,7 @@ const StockMovementInboundTable = ({ { Header: , accessor: 'dateCreated', + sortable: !overdue, width: 150, Cell: (row) => ( ), }, - ], [shipmentStatuses, translate]); + ...(overdue ? [{ + Header: , + accessor: 'daysLate', + width: 100, + Cell: (row) => (), + }] : []), + ], [overdue, shipmentStatuses, translate]); return (
@@ -245,29 +265,34 @@ const StockMovementInboundTable = ({ {`(${tableData.totalCount})`}
-