Use Cases
One section per command use case of the Service in internal/application/usecases
(16 commands: eight on DockAppointment, four on DockCalendar, four on Carrier). Source: book.go, change.go,
calendar.go, facts.go, yard.go, carriers.go. The runtime sequence of each is on
Sequence Diagrams. Reads
(GET /appointments, GET /appointments/{appointmentId},
GET /doors/{doorCode}/availability, GET /sites/{siteId}/dock-calendar,
GET /reports/schedule-adherence, GET /reports/freshness) are queries, not commands: the five query methods of the Service (queries.go) serve the first four, and the two report
routes are served by the separate reports binary from the analytical database.
Conventions for every use case
- One transaction. The aggregate change, its outbox rows and (for a Kafka-driven use case) the inbox row commit together.
- Errors are
application/problem+jsonwithtype = https://errors.dock-scheduling.warehouse-systems.dev/<slug>(internal/adapters/inbound/http/errors.go,problemCatalogue). The status follows decision D-10 of ADR 0002: 409 for a conflict with state, 422 for a value or reference rule, 404 for an unknown resource. The slug is the kebab-case of theErrname, except the two 404s of an unknown appointment (appointment-not-found) or door (door-not-found). The use-case sections below name theErr...variables; this table is the complete catalogue.
| Error | HTTP | Problem slug |
|---|---|---|
ports.ErrNotFound (appointment) | 404 | appointment-not-found |
ErrDoorNotFound | 404 | door-not-found |
ErrUnknownClosure | 404 | unknown-closure |
ErrPreconditionFailed (If-Match or expectedVersion stale) | 412 | precondition-failed |
ErrIllegalTransition | 409 | illegal-transition |
ErrConcurrentUpdate | 409 | concurrent-update |
ErrDoorDoubleBooked, ErrDoorUnavailable, ErrOverlappingClosure, ErrClosureConflictsWithAppointments | 409 | door-double-booked, door-unavailable, overlapping-closure, closure-conflicts-with-appointments |
ErrAsnAlreadyScheduled, ErrHoursConflictWithAppointments, ErrNoShowTooEarly, ErrClosureAlreadyLifted | 409 | asn-already-scheduled, hours-conflict-with-appointments, no-show-too-early, closure-already-lifted |
ErrInvalidDoorCode, ErrInvalidSiteID, ErrInvalidCarrier, ErrInvalidDirection | 422 | invalid-door-code, invalid-site-id, invalid-carrier, invalid-direction |
ErrInvalidWindow, ErrWindowInPast, ErrUnknownDoor, ErrDoorFlowMismatch | 422 | invalid-window, window-in-past, unknown-door, door-flow-mismatch |
ErrUnknownAsn, ErrMissingOutboundRef, ErrDuplicateAsn, ErrInvalidRefs | 422 | unknown-asn, missing-outbound-ref, duplicate-asn, invalid-refs |
ErrCarrierSuspended, ErrCarrierAlreadyRegistered, ErrCarrierAlreadySuspended, ErrCarrierNotSuspended (ADR 0012) | 409 | carrier-suspended, carrier-already-registered, carrier-already-suspended, carrier-not-suspended |
ErrCarrierNotFound (ADR 0012) | 404 | carrier-not-found |
ErrInvalidScac, ErrInvalidUSDOT, ErrInvalidMC, ErrInvalidCarrierName, ErrInvalidSuspensionReason (ADR 0012) | 422 | invalid-scac, invalid-usdot, invalid-mc, invalid-carrier-name, invalid-suspension-reason |
ErrInvalidReason, ErrInvalidEta, ErrInvalidOperatingHours, ErrInvalidSettings, ErrInvalidClosure | 422 | invalid-reason, invalid-eta, invalid-operating-hours, invalid-settings, invalid-closure |
| Adapter-level | 400 | idempotency-key-required, idempotency-key-invalid, malformed-request-body, unknown-query-parameter, invalid-limit, invalid-cursor, invalid-availability-query, invalid-query-parameter, invalid-path-parameter, invalid-if-match, invalid-report-range |
| Adapter-level | 409 | idempotency-key-reused |
| Readiness | 503 | dependency-unavailable |
| Anything unmapped | 500 | internal-error (the detail is generic; the cause is only in the log) |
-
Idempotency. Every state-changing
POSTandPUTtakes anIdempotency-Keyheader; a replay with the same key returns the first response. Every Kafka consumer is idempotent on the CloudEventsid(inbox). Mutable aggregates carry aversionexposed as an ETag and checked withIf-Match(ErrConcurrentUpdateon a lost race,412on anIf-Matchmismatch). The ETag is the weakW/"<version>",If-Matchis honoured on reschedule and cancel and is optional (no428), creatingPOSTs require theIdempotency-Keyand a replay answers byte-identically withIdempotency-Replayed: true;PUTis idempotent by method. -
Kafka-driven use cases have no HTTP status. A fact the policies deliberately do not apply is counted (
dock_scheduling_ignored_facts_total) and the event is marked processed; an infrastructure failure rolls back and the message is retried. -
Order of checks in a booking (
book.go): the per-door advisory lock is taken first (so a closure or booking committed by the previous holder is visible), then the door is looked up and its site calendar loaded, then the aggregate factory validates the value objects (carrier, window, start not in the past), thencheckNewruns the door's flow, the calendar (hours and closures), the references (ASNs, cutoff) and ASN uniqueness, and the overlap check last. -
Request and response bodies are in
apis/openapi.yaml(see the API reference); the fields named below come from the event payloads and value objects.
BookAppointment
- Actor / trigger: carrier scheduler (carrier portal).
- Inbound adapter: REST
POST /appointments. - Preconditions: none on the aggregate; the door, ASN and CPT copies must already hold the facts the booking cites.
- Main flow: (all in one unit of work)
- Validate the door code (
ErrInvalidDoorCode), take the per-door advisory lock, look the door up inDoorView: a known, active dock slot (ErrUnknownDoor); the door's zone gives thesite_id. Load the site'sDockCalendar(defaults when none is stored). dockappointment.Bookvalidates the value objects: carrier (ErrInvalidCarrier), window on the site's slot grid and at mostmax_window_minutes(ErrInvalidWindow), start not before now (ErrWindowInPast), distinct ASNs (ErrDuplicateAsn), references that fit the direction (ErrInvalidRefs).checkNew: the direction against the door'sdockFlow(ErrDoorFlowMismatch); the window inside the door's operating hours and outside its closures (ErrDoorUnavailable);INBOUND: every ASN is inAsnViewand not cancelled (ErrUnknownAsn) and sits on no other active appointment (ErrAsnAlreadyScheduled, the detail lists the ids);OUTBOUND: thecpt_idis inCutoffView, or at least oneshipment_refis given (ErrMissingOutboundRef).DoorSchedule.CheckNoOverlapagainst the door'sBOOKEDandCHECKED_INappointments (ErrDoorDoubleBooked). 4a. When the booking names acarrier_scac(ADR 0012, beforecheckNew): a registeredSUSPENDEDcarrier is refused (ErrCarrierSuspended); anACTIVEcarrier and a SCAC that is not in the registry are accepted as before; a booking with no SCAC never reads the registry.- Save the appointment in
BOOKEDand enqueueDockAppointmentBookedin the same transaction; return the appointment with its ETag.
- Validate the door code (
- Errors:
ErrInvalidDoorCode,ErrUnknownDoor,ErrInvalidCarrier,ErrInvalidWindow,ErrWindowInPast,ErrDuplicateAsn,ErrInvalidRefs,ErrDoorFlowMismatch,ErrDoorUnavailable,ErrUnknownAsn,ErrAsnAlreadyScheduled,ErrMissingOutboundRef,ErrDoorDoubleBooked,ErrCarrierSuspended. - Events emitted:
DockAppointmentBooked. - Idempotency:
Idempotency-Key; the overlap check and the insert run under the same per-door lock.
RescheduleAppointment
- Actor / trigger: carrier scheduler.
- Inbound adapter: REST
POST /appointments/{appointmentId}/reschedules,If-Matchwith the appointmentversion. - Preconditions: the appointment is
BOOKED. - Main flow:
- Load the appointment under a row lock; refuse a stale
If-Match/expectedVersion(ErrPreconditionFailed, 412). - Take the per-door lock of the target door (the current door when none is given), which must belong to the appointment's site
(
ErrUnknownDoor); refuse if the appointment is notBOOKED(ErrIllegalTransition). A reschedule may change the door and the window (decision D-4). 2a. The carrier registry rule ofBookAppointmentapplies (ADR 0012): a registeredSUSPENDEDcarrier cannot move an appointment (ErrCarrierSuspended). - Run the same door-flow, hours and closures checks as
BookAppointment, thenDoorSchedule.CheckNoOverlapfor the new window, ignoring this appointment (ErrDoorDoubleBooked). The ASN checks are not repeated. - Keep the state
BOOKED; store the new window and the previous one; save with the version check and writeDockAppointmentRescheduled(previous_window_start,previous_window_end,previous_door_code,arrival_tolerance_minutes), one transaction.
- Load the appointment under a row lock; refuse a stale
- Errors:
ErrNotFound,ErrPreconditionFailed,ErrIllegalTransition,ErrConcurrentUpdate,ErrUnknownDoor,ErrInvalidWindow,ErrWindowInPast,ErrDoorFlowMismatch,ErrDoorUnavailable,ErrDoorDoubleBooked,ErrCarrierSuspended. - Events emitted:
DockAppointmentRescheduled. - Idempotency:
Idempotency-KeyandIf-Match.
CancelAppointment
- Actor / trigger: carrier scheduler; policy
CancelWhenAllAsnsCancelledonASNCancelled(reasonASN_CANCELLED); policyCancelOnVisitRejectedonVisitRejected(reasonTURNED_AWAY). The REST route acceptsCARRIER_REQUESTandSITE_REQUEST, the latter for the dock planner (decisions D-5, X2). - Inbound adapter: REST
POST /appointments/{appointmentId}/cancellationswith aCancellationReason; Kafka consumer ofwarehouse.inbound-receiving.eventsfor the policy. - Preconditions: the appointment is
BOOKEDorCHECKED_IN. - Main flow:
- Load the appointment; refuse if not
BOOKEDorCHECKED_IN(ErrIllegalTransition). - Transition to
CANCELLEDwith the reason. - Save with the version check and write
DockAppointmentCancelled(reason), one transaction. - Policy path: for each
INBOUNDBOOKEDappointment of the cancelled ASN whose ASNs are now all cancelled, run steps 2 and 3.
- Load the appointment; refuse if not
- Errors:
ErrNotFound,ErrIllegalTransition,ErrConcurrentUpdate,ErrInvalidReason(a reason outside the list). - Events emitted:
DockAppointmentCancelled. - Idempotency:
Idempotency-KeyandIf-Match; inbox on the Kafka path.
ReportEta
- Actor / trigger: carrier scheduler (later, possibly a
transport-visibilityfeed). - Inbound adapter: REST
POST /appointments/{appointmentId}/eta-reports. - Preconditions: the appointment is
BOOKED(any other state isErrIllegalTransition). - Main flow:
- Load the appointment with its
version. - Store
Eta(eta_at,reported_at,source, defaultapi, at most 64 characters). - If
eta_atis later thanwindow_startplus the arrival tolerance, flag the appointmentLATE_ETAand writeDockAppointmentAtRisk(policyEtaRisk), once per ETA report. An ETA inside the tolerance writes no event and clears an earlierLATE_ETAflag. - Save with the version check, one transaction. Nothing is rescheduled.
- Load the appointment with its
- Errors:
ErrNotFound(404appointment-not-found),ErrIllegalTransition,ErrConcurrentUpdate,ErrInvalidEta. - Events emitted:
DockAppointmentAtRiskwhen the ETA is late; none otherwise. - Idempotency:
Idempotency-Key; oneAtRiskper ETA report.
RecordArrival
- Actor / trigger: policy
ArrivalFromGateonVisitCheckedInnaming anappointment_id. There is no REST route: arrival is a physical fact owned byyard-management. - Inbound adapter: Kafka consumer of
warehouse.yard-management.events(typecom.warehouse.wms.yard-management.yardvisit.VisitCheckedIn). - Preconditions: the appointment is
BOOKED. - Main flow:
- Insert the CloudEvents
idinto the inbox; if present, stop. - Load the appointment. Unknown or terminal (
COMPLETED,CANCELLED,NO_SHOW): ignore and count. A lateVisitCheckedInfor aCOMPLETEDappointment is also ignored. - Compute
ArrivalStatusfromarrived_at, the window and the site's arrival tolerance (EARLY beforewindow_startminus the tolerance, LATE afterwindow_startplus the tolerance, else ON_TIME; decision X6). - Transition
BOOKEDtoCHECKED_IN; save with the version check and writeDockAppointmentCheckedIn(checked_in_at,arrival_status,visit_id) to the analytics topic, one transaction.
- Insert the CloudEvents
- Errors: none returned; refusals are counted. An appointment already
CHECKED_INis left unchanged and counted. - Events emitted:
DockAppointmentCheckedIn(analytics only). - Idempotency: inbox on the CloudEvents
id.
ReassignDoor
- Actor / trigger: policy
ActualDoorWinsonTrailerDockedwhosedoor_codediffers from the booked door. No REST route. - Inbound adapter: Kafka consumer of
warehouse.yard-management.events(typecom.warehouse.wms.yard-management.trailer.TrailerDocked). - Preconditions: the appointment is active:
BOOKEDandCHECKED_INaccept the command. - Main flow:
- Inbox check on the CloudEvents
id. - Load the appointment by
appointment_id; if the door equals the booked door, stop. - Change the door without the overlap refusal: the physical fact wins.
- Find later appointments that now overlap on the new door; each gets
DockAppointmentAtRiskwith causeDOOR_REASSIGNED_OVERLAP. - Save with the version check and write
DockAppointmentDoorReassigned(from_door_code,to_door_code), one transaction.
- Inbox check on the CloudEvents
- Errors: none returned; a
CANCELLEDorNO_SHOWappointment is ignored and counted. - Events emitted:
DockAppointmentDoorReassigned(integration and analytics, service ADR 0010:inbound-receivingreads it) and, per overlapped appointment,DockAppointmentAtRisk(analytics only). - Idempotency: inbox; a second
TrailerDockedfor the same door changes nothing.
RecordDoorRelease
- Actor / trigger: policy
CompleteOnDoorReleaseonTrailerUndockednaming anappointment_id. No REST route. - Inbound adapter: Kafka consumer of
warehouse.yard-management.events(typecom.warehouse.wms.yard-management.trailer.TrailerUndocked). - Preconditions: the appointment is
CHECKED_IN, orBOOKED(policyOutOfOrderYardFacts). - Main flow:
- Inbox check on the CloudEvents
id. - Load the appointment.
CANCELLEDorNO_SHOW: ignore and count. - From
BOOKED, record the arrival as implicit and complete it (BOOKEDtoCOMPLETED); fromCHECKED_IN, complete it. - Save with the version check and write
DockAppointmentCompleted(completed_at), one transaction.
- Inbox check on the CloudEvents
- Errors: none returned.
- Events emitted:
DockAppointmentCompleted(analytics only). NoDockAppointmentCheckedInis raised for an implicit arrival; the adherence report counts it asON_TIMEand the metricdock_scheduling_implicit_arrivals_totalcounts it. - Idempotency: inbox; an appointment already
COMPLETEDis not completed twice. One appointment covers exactly one trailer (decision X3).
MarkNoShow
- Actor / trigger: scheduler (cron), policy
NoShowSweep. - Inbound adapter: REST
POST /no-show-sweeps. - Preconditions: none; the sweep selects what qualifies.
- Main flow:
- Select
BOOKEDappointments withwindow_endplus the site's no-show grace before now. At most 500 candidates are loaded per pass (sweepBatch). - For each, under a row lock, transition
BOOKEDtoNO_SHOW, save with the version check and writeDockAppointmentNoShow, one transaction per appointment. An appointment whose grace is not over (ErrNoShowTooEarly) or that moved on since the listing (ErrIllegalTransition) is skipped silently. - Return
{count, appointmentIds, ranAt}. Any other failure on one appointment does not stop the pass; the first such error is returned after the pass (a 5xx the CronJob retries).
- Select
- Errors: none for a normal pass; a store failure is the first error of the pass.
- Events emitted:
DockAppointmentNoShow, one per appointment. - Idempotency:
Idempotency-Key; a rerun marks only what still qualifies, so it is idempotent by construction.
DeclareOperatingHours
- Actor / trigger: dock planner.
- Inbound adapter: REST
PUT /sites/{siteId}/dock-calendar/operating-hours. - Preconditions: none.
- Main flow:
- Validate every row:
opens_at < closes_at(ErrInvalidOperatingHours). - Store the hours for the door, or as the site default, with weekday and
time zone;
PUTreplaces the whole set of rows of the site (assumption A7: a door with rows of its own uses only those, a door with none uses the site default rows, no rows at all means open 24x7; at most one row per door and weekday;closes_atmay be24:00). - Save with the version check and write
DoorOperatingHoursDeclared(site_id,door_code,operating_hours,version), one transaction.
- Validate every row:
- Errors:
ErrInvalidOperatingHours,ErrConcurrentUpdate,ErrHoursConflictWithAppointments(409, lists the ids) when an active appointment would fall outside the new hours (decision D-8). - Events emitted:
DoorOperatingHoursDeclared(analytics only). - Idempotency:
Idempotency-Key;PUTwith the same body is a no-op.
DeclareCalendarSettings
- Actor / trigger: dock planner.
- Inbound adapter: REST
PUT /sites/{siteId}/dock-calendar/settings. - Preconditions: none.
- Main flow:
- Validate
max_window_minutes,slot_granularity_minutes,arrival_tolerance_minutesandno_show_grace_minutes(ErrInvalidSettings; the defaults are 240, 15, 15 and 60;max_window_minutescan only lower the 4 h hard cap; the window grid is whole minutes since the Unix epoch). - Store the settings and save with the version check.
- Validate
- Errors:
ErrInvalidSettings,ErrConcurrentUpdate. - Events emitted: none; the new tolerance reaches
yard-managementon the nextBookedorRescheduledevent (arrival_tolerance_minutes, decision X1). - Idempotency:
Idempotency-Key;PUTwith the same body is a no-op.
ScheduleDoorClosure
- Actor / trigger: dock planner.
- Inbound adapter: REST
POST /sites/{siteId}/dock-calendar/closures. - Preconditions: none on the calendar.
- Main flow:
- Validate the closure (
door_code,from,to,reason). - Refuse if it overlaps another closure of the same door
(
ErrOverlappingClosure). - Refuse if it covers an active appointment of the door; the refusal lists
the appointment ids (
ErrClosureConflictsWithAppointments). - Add the closure with a new
closure_id; save with the version check and writeDoorClosureScheduled, one transaction.
- Validate the closure (
- Errors:
ErrOverlappingClosure,ErrClosureConflictsWithAppointments,ErrInvalidClosure,ErrUnknownDoor,ErrConcurrentUpdate. - Events emitted:
DoorClosureScheduled(consumed byyard-management). - Idempotency:
Idempotency-Key. The site's calendar row is locked (GetForUpdate) and the door's advisory lock is taken before the active appointments are read, so a booking on that door cannot slip in between the check and the commit.
LiftDoorClosure
- Actor / trigger: dock planner.
- Inbound adapter: REST
POST /sites/{siteId}/dock-calendar/closures/{closureId}/lifts. - Preconditions: the closure exists on the site's calendar.
- Main flow:
- Lock the site's calendar and find the closure by
closure_id(ErrUnknownClosure, 404, if absent). - Mark it lifted (
ErrClosureAlreadyLifted, 409, if it already is); save with the version check and writeDoorClosureLifted, one transaction.
- Lock the site's calendar and find the closure by
- Errors:
ErrUnknownClosure,ErrClosureAlreadyLifted,ErrConcurrentUpdate. - Events emitted:
DoorClosureLifted(consumed byyard-management). - Idempotency:
Idempotency-Key; a replay returns the first response.
RegisterCarrier
- Actor / trigger: dock planner or compliance process (an agent through MCP
register_carrier). - Inbound adapter: REST
PUT /carriers/{scac}; MCPregister_carrier. - Preconditions: none. The carrier registry is opt-in (ADR 0012).
- Main flow: (one unit of work)
- Validate the SCAC (
ErrInvalidScac, 2..4 upper-case letters) and the identity: name (ErrInvalidCarrierName), optional USDOT (ErrInvalidUSDOT), optional MC or MX (ErrInvalidMC, normalised toMC<digits>orMX<digits>). - Lock the carrier row (
GetForUpdate). Absent:carrier.Registercreates itACTIVEat version 1, save and enqueueCarrierRegistered(REST201). Present with exactly the same data: a no-op (200, nothing written). Present with other data:ErrCarrierAlreadyRegistered.
- Validate the SCAC (
- Errors:
ErrInvalidScac,ErrInvalidCarrierName,ErrInvalidUSDOT,ErrInvalidMC,ErrCarrierAlreadyRegistered. - Events emitted:
CarrierRegistered(first registration only). - Idempotency: idempotent by SCAC and by method; MCP takes an
idempotencyKey.
UpdateCarrier
- Actor / trigger: dock planner or compliance process.
- Inbound adapter: REST
PATCH /carriers/{scac}(a JSON merge patch;Idempotency-Keyrequired,If-Matchhonoured). Not an MCP tool. - Main flow: lock and load the carrier (
ErrCarrierNotFound), compare the version withIf-Match(ErrPreconditionFailed), apply the named fields (nullor""clears USDOT or MC); a change that leaves the data as it is writes nothing. - Errors:
ErrCarrierNotFound,ErrPreconditionFailed,ErrInvalidCarrierName,ErrInvalidUSDOT,ErrInvalidMC. - Events emitted:
CarrierRegisteredwith the new full snapshot and version.
SuspendCarrier
- Actor / trigger: dock planner or compliance process (MCP
suspend_carrier). - Inbound adapter: REST
POST /carriers/{scac}/suspensions; MCPsuspend_carrier. - Main flow: lock and load the carrier, check
If-Match,carrier.Suspend(reason)(ErrInvalidSuspensionReasonfor a blank or over 200 character reason,ErrCarrierAlreadySuspended), save and enqueueCarrierSuspended. From now onBookAppointmentandRescheduleAppointmentrefuse the SCAC withErrCarrierSuspended. Appointments the carrier already holds are not touched. - Events emitted:
CarrierSuspended. - Idempotency:
Idempotency-Key.
ReinstateCarrier
- Actor / trigger: dock planner or compliance process (MCP
reinstate_carrier). - Inbound adapter: REST
POST /carriers/{scac}/reinstatements; MCPreinstate_carrier. - Main flow: lock and load the carrier, check
If-Match,carrier.Reinstate(ErrCarrierNotSuspended), save and enqueueCarrierReinstated. - Events emitted:
CarrierReinstated. - Idempotency:
Idempotency-Key.