Use cases
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.
There is one struct per use case in internal/application/usecases. Each
depends only on the domain and on internal/application/ports. Writes
run inside a UnitOfWork when Postgres is configured
(ADR 0010). Without Postgres
(UnitOfWork == nil) the same steps run one after another.
| Use case | Trigger | Writes? | Events raised |
|---|---|---|---|
| DefineStandard | REST POST /standards | yes | LaborStandardDefined or LaborStandardRevised |
| RecordTaskPerformance | Kafka TaskCompleted on warehouse.fulfillment.events | yes | TaskPerformanceRecorded |
| GetStandard | REST GET /standards/{taskType}, MCP get_labor_standard | no | — |
| GetAssociateScorecard | REST GET /associates/{associateId}/scorecard, MCP get_associate_scorecard, MCP resource scorecard://labor/{associateId} | no | — |
| GetTaskTypePerformance | REST GET /task-types/{taskType}/performance, MCP get_task_type_performance | no | — |
| GetUtilization | REST GET /task-types/{taskType}/utilization, GET /associates/{associateId}/utilization, MCP get_task_type_utilization | no | — |
No use case is triggered by a scheduler. The housekeeping sweeper and
the outbox relay are adapter-level jobs, not use cases
(Runbook). The analytics projection
(cmd/labor-projector) is an adapter over internal/analytics/report,
also not an application use case.
DefineStandard
internal/application/usecases/define_standard.go
- Trigger:
POST /standardsoncmd/labor. Never exposed over MCP. - Inputs:
taskType(PICK,PACKorSLAM, validated byshared.NewTaskTypein the HTTP adapter, 400 otherwise),expectedSeconds, an optionaltravelComponentSeconds, an optionalhandlingUnit(EACH,CASE,PALLET) and, forCASEonly, an optionalteamLift{thresholdG, expectedSeconds}(ADR 0035), and an optionalsiteCode(1-32 characters, no whitespace, validated byshared.NewSiteCode, 400invalid-site-codeotherwise; absent = every site, ADR 0038). With a database, theIdempotency-Keyheader is required (ADR 0016). - Steps:
- Load the currently active standard for the scope: task type, handling unit and site (the task-type-only, site-less standard when neither is given).
- Mint a new
StandardId. standard.NewForScopechecks the invariants:expectedSeconds > 0,travelComponentSeconds >= 0, travel ≤ expected, and ateamLiftonly onCASEwith a positive threshold and positive seconds. A violation returns 422 and recordslabor_performance.standards.defined{outcome="rejected"}.- Atomically, close the prior standard of the same scope at
now(Supersede; it is never overwritten), save the new one, and publish the event. - Record
outcome="accepted".
- Concurrency invariants: the
versioncolumn gives optimistic locking onSave(409concurrent-modification), and the unique partial index allows one open standard pertask_type,handling_unitandsite_code(409standard-conflict) (ADR 0022). - Events:
LaborStandardDefinedwhen no standard of the scope was active, otherwiseLaborStandardRevised(carryingprevious_expected_seconds). Both go towarehouse.labor-performance.analyticsand, since ADR 0038,warehouse.labor-performance.events(key TaskType, the samedata), withsite_codeonly for a site-scoped standard.
RecordTaskPerformance
internal/application/usecases/record_task_performance.go
- Trigger: the Kafka consumer in
cmd/labor, forcom.warehouse.wes.fulfillment-execution.task.TaskCompletedonly. There is deliberately no REST endpoint (ADR 0003). - Inputs:
KafkaEventId(CloudEventsid),TaskId,AssociateId(may be empty),TaskType(ParseTaskTypeLenient: an unknown or absent value becomes""),ActualSeconds(duration_seconds), andCompletedAt(CloudEventstime). - Steps, all in one unit of work:
MarkProcessed(KafkaEventId). An id that was already processed returns(nil, nil), a silent no-op.- Resolve the standard active as of
CompletedAt(FindActiveAsOf), not the current one. If there is none, or the task type is unclassified, the standard is 0 (ADR 0004). When the request carries a handling unit, the standard for exactly (task type, unit) is tried first and the task-type-only standard is the fallback (most specific wins); aCASEstandard with a team lift whose threshold is strictly below the declaredWeightGscores the completion against the team-lift seconds (ADR 0035). Only site-less standards are ever resolved: a site-scoped standard never changes a score (ADR 0038). performance.NewWithHandlingrequires a non-empty event id and task id.EfficiencyPct = 100 × standard / actual, ornilwhen either is ≤ 0. The value is frozen for good.- Look up the associate's previous completion (skipped for an empty
associate), then save the
TaskPerformance. - Derive the idle gap:
claimedAt = CompletedAt − ActualSeconds. The gap runs from the previous completion toclaimedAt, capped atIDLE_GAP_CAP_SECONDS(default 3600,capped=truewhen hit), and is saved as anIdlePeriod. A gap ≤ 0 (out-of-order delivery) is logged and skipped, never an error (ADR 0014). - Publish
TaskPerformanceRecorded.
- Failure: any error rolls everything back, including the
processed_eventsclaim, so the consumer's retry or the DLQ re-drive can process the event again. - Events:
TaskPerformanceRecorded, towarehouse.labor-performance.analytics(key TaskType) andwarehouse.labor-performance.events(key AssociateId) (ADR 0013).
GetStandard
internal/application/usecases/get_standard.go
- Inputs:
taskType, and over REST an optionalhandlingUnitand an optionalsiteCodequery. - Returns: the currently open
LaborStandard, orErrStandardNotFound(404standard-not-found, or an MCP tool error). With a handling unit,ExecuteResolvedreturns the unit's own standard, else the task-type-only one (the MCP tool never passes a unit). Without a site the answer is always site-less; with one,ExecuteForSitereturns exactly that site's standard and never falls back to the site-less one (ADR 0038).
GetAssociateScorecard
internal/application/usecases/get_associate_scorecard.go
- Inputs:
associateId. - Rules: an empty id, or an associate with zero rows, returns
ErrAssociateNotFound(404). An associate whose rows are all unscored gets a scorecard withmeanEfficiencyPct: null, not a 404. - Computes: task count, mean efficiency over scored rows, a
per-TaskType breakdown, and, from the 10 most recent rows,
trend(ClassifyTrend: the recent mean against the all-time mean, ±5 percentage points, needs at least 3 scored tasks, otherwiseINSUFFICIENT_DATA) andcoachingFlag(DetectCoachingFlag: the last 3 scored tasks are all below 85%) (ADR 0005).
GetTaskTypePerformance
internal/application/usecases/get_task_type_performance.go
- Inputs:
taskType(must be a known type). - Returns: always succeeds.
taskCount,meanEfficiencyPct(scored rows only) andmeanActualSeconds(measured rows, independent of any standard, ADR 0006). A type that has never been seen returns count 0 andnullmeans.
GetUtilization
internal/application/usecases/get_utilization.go
- Inputs: a task type or an associate id, and a window. REST
?window=takes a Go duration and MCPwindowSecondstakes seconds. Absent, unparsable or ≤ 0 means 1h. ForTaskType: sumsActualSecondsand recorded (closed) idle gaps for the task type sincenow − window, and counts distinct associates.openGapSecondsis always 0.ForAssociate: the same sums for one associate, plus the open gap: the time from the associate's last activity (last completion or last idle-gap end) to now, clamped to the window. It is computed at read time and never persisted.- Returns:
utilizationPct = 100 × task / (task + idle + openGap), ornullwhen there is nothing to divide.
Sequence: define, then score
Source: internal/application/usecases/define_standard.go,
internal/application/usecases/record_task_performance.go.