Use Cases
Derived from network/model/model.yaml. This context's service is built; the model carries its as-built contracts, and identifiers (Err... names, routes, CloudEvents types) are the names the service uses.
The proposed application services of internal/application/usecases, one per
command of the model. Step-by-step interactions are on
the sequence diagrams page;
payloads are on the domain events page.
Reads are not use cases: GET /delivery-offers/{offerId},
GET /promises/{promiseId}, GET /promises?orderId= and
GET /promise-books?nodeId=&date= read the repositories directly. Read-model
projection (board 1 of the EventStorming page)
is not a use case either: it changes no aggregate.
Triggers at a glance
| Use case | Command(s) | Trigger | Inbound adapter |
|---|---|---|---|
QuoteDeliveryOffers | QuoteDeliveryOffers | shopper / storefront, customer-ordering | REST POST /delivery-quotes |
MakePromise | MakePromise, HoldCapacity | customer-ordering checkout | REST POST /promises |
ConfirmPromise | ConfirmPromise, ConfirmCapacity | CustomerOrderPlaced | Kafka consumer promise-lifecycle |
CancelPromise | CancelPromise, ReleaseCapacity | CustomerOrderCancelled | Kafka consumer promise-lifecycle |
FlagPromiseAtRisk | FlagPromiseAtRisk | RepromiseOnRisk: FulfillmentUnsourceable, PackageExceptionRaised, DepartureCancelled | Kafka consumer promise-lifecycle |
RevisePromise | RevisePromise (+ book commands) | RepromiseOnRisk, right after FlagPromiseAtRisk | same consumer, second transaction |
JudgePromise | JudgePromise | JudgeOnDelivery: PackageDelivered | Kafka consumer promise-lifecycle |
ReleaseExpiredHolds | ReleaseExpiredHolds, ReleaseCapacity | clock | scheduler (proposed every minute) |
ExpireOffers | ExpireOffers | clock | scheduler (proposed every minute) |
CloseBook | CloseBook | clock, at the pickup cutoffAt | scheduler (policy CloseBooksAtCutoff) |
How a change commits
Every use case that changes an aggregate saves it and writes its events to
outbox_events in one Postgres transaction. A Kafka-driven use case also
inserts the CloudEvents id into processed_events in that same transaction,
so a redelivered message commits nothing. Promise and PromiseBook carry a
version; the repository updates WHERE version = :read and a lost race
surfaces as a stale-write conflict, which the use case retries (up to three
times, proposed) before reporting 409 stale-write.
MakePromise is the one use case that changes three aggregates (consumes the
offer, creates the promise, holds capacity) in one local transaction. This is a
deliberate, proposed exception: a promise without a hold would break the
business decision "a promise reserves capacity", and all three rows live in
this context's own database (open question 13 on
the canvas page).
Error mapping
Err... | HTTP | Problem type slug | Kind |
|---|---|---|---|
ErrOfferNotQuotable | 409 | offer-not-quotable | state |
ErrOfferExpiryTooLate | — (never returned) | offer-expiry-too-late | internal guard: an offer that would break it is not quoted |
ErrInvalidPromiseTerms | 422 | invalid-promise-terms | validation |
ErrNominalBasisNotAllowedForTier | 422 | nominal-basis-not-allowed-for-tier | validation |
ErrPromiseHoldExpired | 409 | promise-hold-expired | state |
ErrRevisionMovesEarlier | 409 | revision-moves-earlier | state |
ErrPromiseClosed | 409 | promise-closed | state |
ErrGroupSpansNodes | 422 | group-spans-nodes | validation |
ErrPromiseCapacityExhausted | 409 | promise-capacity-exhausted | capacity |
ErrBookClosed | 409 | book-closed | closed |
ErrCapacityUnderflow | — (never returned) | capacity-underflow | internal guard |
(no Err in the model) offer, promise not found | 404 | offer-not-found, promise-not-found | not found |
(no Err in the model) malformed request | 422 | invalid-request | validation |
| (infrastructure) optimistic version lost three times | 409 | stale-write | stale |
(infrastructure) same Idempotency-Key, different body | 422 | idempotency-key-reused | validation |
Problem types are https://retailnetwork.example/problems/<slug> in an RFC 9457
body (type, title, status, detail). On a Kafka-driven use case there is
no HTTP reply: the error column says what the consumer does instead.
QuoteDeliveryOffers
-
Actor / trigger: a shopper on a product page or cart (storefront), or
customer-orderingat checkout. -
Inbound adapter: REST
POST /delivery-quotes(internal/adapters/inbound/http). -
Input:
destinationPostalPrefix,lines[](catalogItemId,quantity), optionaltiers[](default: all four). -
Preconditions: none on aggregates. Reads only local read models and
PromiseBookrows. Makes no synchronous call. -
Main flow (
PromisePolicy; worked example in the promise model, the AUS3 / DFW7 cart on Thursday at 14:05):- Resolve the destination postal prefix to its delivery station and region
(
RegionAndServiceAreaView). None: every tier getsDESTINATION_NOT_SERVED. - Group the lines (
ShipmentGrouping): findACTIVEnodes with theOUTBOUNDcapability whose listings are live and hold the quantity of each line (NodeProfileView,AvailabilityView; discontinued items are excluded). Prefer one node for the whole cart; otherwise split into the fewest groups. A line no node can cover:ITEM_QUANTITY_NOT_AVAILABLE. - Apply
TierOrderDeadline: a tier whose policy-versioned local order deadline in the destination region has passed is not searched. - For each candidate node compute
readyAt = now + handling time(counted inside operating hours, skipping holidays, in the node's time zone)+ handicap(ScorecardHandicap: grade A +0, B + handling × 0.25, C next cutoff, D two cutoffs later, no scorecard yet +0). - Take the first pickup departure (
DepartureView, kindPICKUP) at the node withcutoffAt >= readyAtand remaining capacity, whosePromiseBook(nodeId:pickupDepartureId) isOPENand hasprovisional + confirmed < share. - Search the earliest-arrival path from the pickup to the delivery station
over scheduled departures with remaining capacity (a time-expanded graph;
at each intermediate node add its sort dwell before the next departure's
cutoff).
SAME_DAYadmits only aSUB_SAME_DAYorMICROfulfillment centre injecting directly into the destination's delivery station. - Take the first delivery wave at the station with
inductCutoffAt >= arrivaland stop capacity left (DeliveryWaveView). The offer window is the wave'swindowStart..windowEnd. - Keep the path for a tier only if the window ends within the tier's
calendar days (
SAME_DAY0,NEXT_DAY1,TWO_DAY2,STANDARD7). ForSTANDARDonly, if no scheduled path exists, fall back to nominal lane transit (LaneView); the offer's basis is thenNOMINAL. - Pick the best path per tier: earliest
windowEnd; ties go in-region, then fewer legs, then the better grade. - Create one
DeliveryOffer(QUOTED) per tier with an offer, withexpiresAt = min(quotedAt + offerTtl, the latest instant the witness pickup cutoff can still be met). Save the offers and write oneDeliveryOfferQuotedrow for the analytics topic, in one transaction. - Return the offers, and for each requested tier without an offer, the
OfferConstraintthat blocked it:DELIVERY_SLA_UNAVAILABLEwhen no path fits the tier,NODE_CAPACITY_EXHAUSTEDwhen paths exist but every candidate book or departure is full.
- Resolve the destination postal prefix to its delivery station and region
(
-
Errors:
Error HTTP Problem typemalformed body (no prefix, quantity below 1, unknown tier) 422 invalid-requestErrOfferExpiryTooLatenot returned the offer is not created; the tier is reported unavailable "No offer" is a normal
200answer with constraints, not an error. -
Events: none on the integration topic;
DeliveryOfferQuotedon the analytics topic. -
Idempotency: a quote is safe to repeat. With an
Idempotency-Key, a repeat within the offers' TTL returns the same, still-QUOTEDoffers instead of creating new ones.
MakePromise
-
Actor / trigger:
customer-orderingat checkout (CheckoutPromising), once per shipment group, with the offer the shopper saw. -
Inbound adapter: REST
POST /promises(in-org). -
Input:
offerId,lines[](catalogItemId,quantity) of the group; headerIdempotency-Key. -
Preconditions: the offer exists and is
QUOTEDand not pastexpiresAt; the lines are shippable from the offer's witness node; the witness book isOPENand has room. -
Main flow:
- Load the offer; reject if missing (404) or not quotable
(
ErrOfferNotQuotable). - Re-validate the offer's witness path against the current read models
(the departures and the wave still have room), and check the group against
AvailabilityViewfor the witness node (ErrGroupSpansNodesif any line is not shippable from it). A path that is no longer feasible is refused like a full book, so checkout re-quotes. - Build
PromiseTermsfrom the offer: tier,shipBy= the witness pickup cutoff,deliverByEarliest/deliverByLatest= the offer window, basis andpolicyVersionof the quote (ErrInvalidPromiseTerms,ErrNominalBasisNotAllowedForTier). - Create the
PromiseinPROVISIONALwithholdExpiresAt. HoldCapacityon the booknodeId:pickupDepartureId(ErrPromiseCapacityExhausted,ErrBookClosed). If this hold makesprovisional + confirmed = share, raisePromiseBookExhausted.- Mark the offer
CONSUMED. - Commit offer, promise, book and outbox rows in one transaction; reply
201with the promise.
- Load the offer; reject if missing (404) or not quotable
(
-
Errors:
Error HTTP Problem typeoffer not found 404 offer-not-foundErrOfferNotQuotable409 offer-not-quotableErrGroupSpansNodes422 group-spans-nodesErrInvalidPromiseTerms422 invalid-promise-termsErrNominalBasisNotAllowedForTier422 nominal-basis-not-allowed-for-tierErrPromiseCapacityExhausted409 promise-capacity-exhaustedErrBookClosed409 book-closedbook version lost three times 409 stale-writesame key, different body 422 idempotency-key-reused -
Events:
PromiseMade;PromiseBookExhaustedwhen the book fills. -
Idempotency: the
Idempotency-Keyis stored on the promise (unique), and an offer backs at most one promise (offer_idunique). A retry with the same key and body returns the existing promise with200.
ConfirmPromise
-
Actor / trigger:
customer-orderingplaced the order. -
Inbound adapter: Kafka consumer of
com.retailnetwork.commerce.customer-ordering.customerorder.CustomerOrderPlaced. -
Input:
orderId, and for each groupgroupNo,promiseId. -
Preconditions: each promise is
PROVISIONALandnow < holdExpiresAt. This consumer is the reconciling confirm:customer-orderingnormally confirmed the promise synchronously at checkout (POST /promises/{promiseId}/confirmations), and a promise alreadyCONFIRMEDfor the same order and group is a no-op (ADR 0002 A16). -
Main flow (all groups share one transaction with the inbox row; a lapsed group does not fail it):
- For each group, load the promise (an unknown one is logged and skipped);
ConfirmPromise(orderId, groupNo)(PROVISIONAL→CONFIRMED). ConfirmCapacityon its book (provisional - 1,confirmed + 1).- Save both, write
PromiseConfirmed, record the CloudEventsid.
- For each group, load the promise (an unknown one is logged and skipped);
-
Errors:
Error Consumer outcome Problem type(for logs)ErrPromiseHoldExpiredthat group is skipped with a warning log and never retried; the other groups of the order are still confirmed, and the ReleaseExpiredHoldssweeper releases the lapsedPROVISIONALpromise (hotspot H6)promise-hold-expiredErrPromiseClosed(alreadyRELEASED)as above promise-closedErrCapacityUnderflowbug alarm; transaction rolled back, message retried capacity-underflowstale version retried stale-write -
Events:
PromiseConfirmedper group. -
Idempotency: inbox on the CloudEvents
id; a promise alreadyCONFIRMEDfor the sameorderIdandgroupNois a no-op.
CancelPromise
-
Actor / trigger: the customer cancelled, or
customer-orderingcancelled an unfulfillable group (CancelOnUnfulfillable). -
Inbound adapter: Kafka consumer of
com.retailnetwork.commerce.customer-ordering.customerorder.CustomerOrderCancelled. The model names no policy joining this event toCancelPromise; this is the pack's reading. -
Input:
orderId,groupNos,reason. -
Preconditions: each promise is
CONFIRMEDorAT_RISK. -
Main flow (per group):
- Find the promise by
orderIdandgroupNo;CancelPromise(reason). ReleaseCapacity(confirmed) on its book.- Save, write
PromiseCancelled, record theid.
- Find the promise by
-
Errors:
Error Consumer outcome Problem type(for logs)ErrPromiseClosedno-op if CANCELLED; logged ifKEPT/BROKENpromise-closedErrCapacityUnderflowbug alarm, retried capacity-underflow -
Events:
PromiseCancelled. -
Idempotency: inbox; a
CANCELLEDpromise is a no-op.
FlagPromiseAtRisk
-
Actor / trigger:
RepromiseOnRisk, onFulfillmentUnsourceable(bypromiseId),PackageExceptionRaised(by the group's assignment, see open question 4 on the canvas page), orDepartureCancelled(everyCONFIRMEDpromise whose witness path uses the departure). -
Inbound adapter: Kafka consumer
promise-lifecycle. -
Preconditions: the promise is
CONFIRMED. -
Main flow:
FlagPromiseAtRisk(reason, detectedAt)(CONFIRMED→AT_RISK).- Save, write
PromiseAtRisk, record theid. - Hand the promise to
RevisePromise.
-
Errors:
Error Consumer outcome Problem type(for logs)ErrPromiseClosedignored (already judged, released or cancelled) promise-closedalready AT_RISKno second PromiseAtRisk; goes straight toRevisePromise— -
Events:
PromiseAtRisk. -
Idempotency: inbox; an
AT_RISKpromise is not flagged twice.
RevisePromise
-
Actor / trigger:
RepromiseOnRisk, afterFlagPromiseAtRisk. -
Inbound adapter: same consumer, separate transaction.
-
Preconditions: the promise is
AT_RISK(orCONFIRMED, which the model allows). -
Main flow:
- Re-run the search of
QuoteDeliveryOffersfor the promise's group, destination and tier, fromnow. ForFulfillmentUnsourceable, exclude the event'sexcludedNodes(this pack's reading). If the tier has no path, try the slower tiers down toSTANDARD. - Nothing feasible even at
STANDARD: stop. The promise staysAT_RISKand is reportedPromiseBrokenat judgement time. - Otherwise
RevisePromise(newTerms, newWitness, reason): append aRevision{revisionNo, previousTerms, reason, revisedAt}; reject withErrRevisionMovesEarlierif the newdeliverByLatestis earlier. - Book capacity (this pack's reading; open question 11):
HoldCapacityandConfirmCapacityon the new book,ReleaseCapacity(confirmed) on the old one, if the book changed. - Save, write
PromiseRevised.
- Re-run the search of
-
Errors:
Error Consumer outcome Problem type(for logs)ErrRevisionMovesEarlierthe candidate is discarded (a later one is never earlier) revision-moves-earlierErrPromiseCapacityExhausted,ErrBookClosedon the new booknext candidate path promise-capacity-exhausted,book-closedErrPromiseClosedignored promise-closedErrNominalBasisNotAllowedForTiercandidate discarded nominal-basis-not-allowed-for-tier -
Events:
PromiseRevised. -
Idempotency: the trigger's
idis recorded with the revision; a redelivery finds it in the inbox and does nothing.
JudgePromise
-
Actor / trigger:
JudgeOnDelivery, onPackageDelivered; and onPackageLostorPackageReturned, which break the promise (a lost or returned package's promise IS judged, ADR 0025). -
Inbound adapter: Kafka consumer of
com.retailnetwork.logistics.shipping-and-tracking.journey.PackageDelivered,PackageLostandPackageReturned. -
Input:
assignmentId,orderId,deliveredAt(for a loss or a return the tracking number anddeclaredAtorreturnedAt, nodeliveredAt). -
Preconditions: the group's promise is
CONFIRMEDorAT_RISK. Finding it needsassignmentId→ (orderId,groupNo), which onlyFulfillmentLockedcarries (open questions 3 and 4). A tracking number may belong to several assignments: every sharing promise is judged, each on its own window (SharedTrackingJudgement). -
Main flow:
JudgePromise(deliveredAt):KEPTifdeliveredAt <= deliverByLatest, elseBROKENwithlateByMinutesand acause. OnPackageLostorPackageReturnedthe promise isBROKENwith causeLOSTorRETURNEDand nodeliveredAt.- Save, write
PromiseKeptorPromiseBroken, record theid.
-
Errors:
Error Consumer outcome Problem type(for logs)ErrPromiseClosedno-op (a second package of the same group, or a redelivery) promise-closedpromise not found yet (lock not seen) retried with back-off promise-not-found -
Events:
PromiseKeptorPromiseBroken. -
Idempotency: inbox; a judged promise is terminal.
ReleaseExpiredHolds
- Actor / trigger: the clock.
- Inbound adapter: scheduler.
- Preconditions:
PROVISIONALpromises withholdExpiresAt <= now. - Main flow (per promise, one transaction each):
ReleaseExpiredHolds(PROVISIONAL→RELEASED).ReleaseCapacity(provisional) on its book.- Save, write
PromiseReleased.
- Errors:
ErrPromiseClosed(confirmed in the meantime): skipped.ErrCapacityUnderflow: bug alarm. Stale version: next pass. - Events:
PromiseReleased. - Idempotency: the state check; a
RELEASEDpromise is not selected again.
ExpireOffers
- Actor / trigger: the clock.
- Inbound adapter: scheduler.
- Main flow: move
QUOTEDoffers pastexpiresAttoEXPIREDin batches; drop day partitions older than the retention. - Errors: none returned; a concurrently
CONSUMEDoffer is skipped. - Events: none.
- Idempotency: the state check.
CloseBook
- Actor / trigger: the clock, at the witness pickup's
cutoffAt(policyCloseBooksAtCutoff). Holds are refused earlier, from theholdDeadline, the cutoff minus the node's handling time (the instantErrBookClosedprotects). - Inbound adapter: scheduler.
- Main flow:
CloseBook(OPEN→CLOSED); save. - Errors: already
CLOSED: no-op. - Events: none (the model gives
PromiseBookonlyPromiseBookExhausted). - Idempotency: the state check.