Skip to main content

Use cases

Synced from network-inventory-planning

This page is a copy of docs/docs/ddd/use-cases.md on develop, derived from that repository's code. Edit it there, then re-sync.

Every use case lives in internal/application/usecases. Each takes its clock as a function (Now) and its stores and publishers as ports; the composition roots in cmd/ wire them. "Outbox" means the event is written as an outbox_events row in the same transaction as the state change and reaches Kafka through the relay.

Planning (advisory)​

Use caseTriggerInputsInvariants checkedEvents raised
GenerateTransferProposalsPOST /v1/transfer-proposal-runsasOf, positions[], policies[], lanes[] (request body)asOf required; every position's AsOf equals asOf (no mixed snapshot); the planner then only uses enabled directed lanes, keeps the origin's safety stock (usable − safetyStock), never exceeds the destination deficit (target − (usable + confirmedInbound)), requires origin and destination positions with the same AsOf, and keeps a proposal only if its score (quantity × unitPriority − quantity × unitHandlingCost − leadTimeDays) is positive. Output is sorted by score, then SKU, origin, destination.none
SimulateTransferOptionsGET /v1/transfer-simulations; MCP simulate_transfer_optionsnone (loads the three read models)planning.BuildSnapshot: no empty table, a site participates only with capability + demand + capacity plan, all within PLANNING_MAX_STALENESS (a stale or missing fact excludes that site; the snapshot is refused only when no site survives, ADR-0018), a site disabled for one direction still participates and is gated per direction where used, demand counts only when due_at is in the plan window [start, end)none

The transfer saga​

Use caseTriggerInputsInvariants checkedEvents raised
ApproveTransferPOST /v1/transfer-approvalsIdempotency-Key header; originSiteId, destinationSiteId, sku, quantity, policyVersion, operatorReason, proposalAsOfpick-leg release configured (else 503); key and proposalAsOf present; the current snapshot builds; transfer.ValidateApproval (both sites participate, origin origin-enabled, destination destination-enabled, destination has in-window demand for the SKU, origin capacity ≥ its in-window demand + quantity); ProposeTransfer field checks (ids, sites differ, quantity > 0, policy version); expiry = approval + 24h; idempotency key unique (same body → replay, different body → 409)outbox: TransferPlanApproved, TransferAllocationRequested, and four TransferStateAdvanced (→DRAFT, →PROPOSED, →APPROVED, →ALLOCATING)
ApplyTransferAllocationTransferStockAllocated on warehouse.inventory.eventstransfer id, line id, origin, SKU, reservation id, allocations, reservation expiry, CE timestate is ALLOCATING; reply is for line <id>:1, same origin and SKU, has a reservation id, at least one allocation with stock unit, bin and positive quantity, allocations total the requested quantity, has an expiryoutbox: TransferStateAdvanced (ALLOCATING→ALLOCATED), pick WorkDemandReleased (<id>:pick, TRANSFER_PICK, origin site, CPT = reply time + pick offset, allocated quantity)
ApplyTransferRejectionTransferStockAllocationRejectedtransfer id, line id, reasonstate is ALLOCATING; reason in the closed set; line id matchesnone (state change only)
ApplyTransferPickTransferPicked on warehouse.fulfillment.eventstransfer_ref, picked quantitystate is ALLOCATED; 0 < picked ≤ quantity (a short pick is recorded)outbox: TransferStateAdvanced (ALLOCATED→PICKED), dispatch WorkDemandReleased (<id>:dispatch, TRANSFER_DISPATCH, picked quantity) unless the dispatch leg is not configured
ApplyTransferDispatchedTransferDispatchedtransfer_refstate is PICKEDnone in production (its publisher field is not wired by cmd/network-inventory-planning)
ApplyTransferArrivalTransferArrivedtransfer_refstate is IN_TRANSITnone in production (same reason)
ApplyTransferReceiptStagedTransferReceiptStaged on warehouse.inventory.eventstransfer id, line idstate is IN_TRANSITnone in production (same reason)
ApplyTransferStowTransferStockStowedtransfer id, line id, destination, SKU, quantities, stow allocationsstate is ARRIVED; same line, destination and SKU; stowed quantity > 0; at least one stow allocationnone in production (same reason)

InterWarehouseTransfer.Cancel exists in the domain (legal from DRAFT, PROPOSED, APPROVED, ALLOCATING with a reason) but no use case or route calls it today.

Read side​

Use caseTriggerInputsInvariants checkedEvents raised
GetTransferGET /v1/transfers/{id}; MCP get_transferidid not blank; unknown id → transfer-not-foundnone
ListTransfersGET /v1/transfers; MCP list_transfersstate, originSiteId, destinationSiteId, limit, cursor (REST) or state, site, limit, offset (MCP)state in the 11-state vocabulary (case-insensitive); REST: keyset paging, limit 1–500 (default 100), opaque cursor from nextCursor, an undeclared query parameter is 400; MCP: 0 ≤ limit ≤ 200 (0 → 50), offset ≥ 0none
FindStuckTransfersMCP find_stuck_transfersolder_than_minutes, state, limitthreshold positive; state must be non-terminal; ordered stalest firstnone
ListRebalanceRunsGET /v1/rebalance-runslimit, cursorREST: limit 1–500, default 100 (out-of-range is 400 invalid-limit), keyset cursor (undecodable is 400 invalid-cursor)none
ListRebalancePolicies / ListTransferLanesGET /v1/rebalance-policies, GET /v1/transfer-lanesnoneordered by keynone

Catalogue management (ADR 0015)​

Use caseTriggerInputsInvariants checkedEvents raised
PutRebalancePolicyPUT /v1/rebalance-policiesPolicy body, optional If-Match revisionPolicy.Validate (key present, no negative value, TargetStock ≥ SafetyStock); If-Match equals the stored revision; the key never changes; an identical PUT writes nothing; the write is guarded by the revision readnone (the catalogue is NIP-internal)
PutTransferLanePUT /v1/transfer-lanesLane body, optional If-Match revisionLane.Validate (both sites, origin ≠ destination, no negative lead time or cost); same revision rulesnone

Scheduled (observe-only, ADR 0007)​

Use caseTriggerInputsInvariants checkedEvents raised
CheckStuckTransfersPeriodicRunner every NIP_HEALTH_CHECK_INTERVAL (default 5m)up to 500 non-terminal transfers (id, state, updated_at)age in state > the state's threshold (NIP_STUCK_THRESHOLDS); never mutates a transferoutbox: one TransferStuckDetected per stuck transfer, every tick
RunScheduledRebalancePeriodicRunner every NIP_REBALANCE_SCHEDULE (off by default)the three read models, the policy and lane cataloguessame fail-closed snapshot as the simulation; plans with Planner.PlanFromSnapshot (a lane only when enabled and both ends are capable; need ≤ target; donor keeps safety stock; ADR 0015); a refusal or an unreadable catalogue is recorded as a FAILED run, not an error; never approves or allocatesrebalance_runs row; outbox: RebalanceRunCompleted (run_id = rebal-<id>-<startedAt>) after a completed run

PeriodicRunner (periodic.go) is the ticker loop both run in: it logs a failed tick and keeps going.

Read-model ingestion (adapter level)​

The three planning facts are not use cases: the inbound consumers in internal/adapters/inbound/kafka/consumers.go validate each payload through the planning domain constructors and upsert through the repository ports, inside the same unit of work as the processed_events claim:

ConsumerFactRule
site capabilitySiteCapabilitya strictly greater capability_revision supersedes
site SKU demandSiteSkuDemandlast write wins per (source_order_id, line_no); REMOVED contributes no units
capacity planPublishedCapacityPlana newer published_at supersedes; a plan without site_id is excluded

Analytics projection (nip-projector)​

AnalyticsConsumer folds the three saga.* events into the analytical tables through report.Projection (internal/adapters/outbound/analyticsstore): one row per event, idempotent on the CloudEvents id recorded in analytics_processed_events in the same transaction. The reports binary reads them through report.Reader and the pure rules in internal/analytics/report (half-open ranges, 30-day default, 366-day cap, percentiles, rejection rate, freshness).