Use Cases
Derived from model/model.yaml. The customer-payments service is built on develop (IQVO/customer-payments at 054b3de, checked 2026-12-02), released at v0.1.4 and applied to the k3s cluster: the api and the A2A agent are deployed, the MCP server is registered in warehouse-infra and switched off. Every Err... name, REST route and CloudEvents type of this context named on this page exists in the service; where the built service differs from the model's design, the page says so (As built) or the context's Service and operations section lists it.
One section per command of
contexts[customer-payments].aggregates[PaymentAuthorization].commands and
aggregates[Refund].commands, plus the policies that issue them. They are
application services in internal/application/usecases (as built). The
step-by-step diagrams are on
Sequence Diagrams;
the payloads are on Domain Events;
the REST contract is storefront/apis/customer-payments/openapi.yaml.
Reads are not use cases here: GET /payment-authorizations/{authorizationId}
(GetAuthorization, also called by checkout),
GET /payment-authorizations?orderId=|checkoutSessionId=
(ListAuthorizations) and GET /refunds?orderId= (ListRefunds) read the
repository directly. ListAuthorizations takes exactly one of the two
filters (422 validation-failed otherwise).
As built (054b3de), the four reads (GetAuthorization,
ListAuthorizations, GetRefund, ListRefunds) are use cases in
internal/application/usecases, and they are the whole agent surface: the
MCP tools get_payment_authorization, list_payment_authorizations,
get_refund and list_refunds (cmd/mcp), and the A2A skills
get_payment_status (GetAuthorization or ListAuthorizations) and
get_refund_status (GetRefund or ListRefunds) (cmd/a2a), all L1 inform.
No command has an MCP tool or an A2A skill: authorizing, voiding, capturing,
releasing and refunding stay on REST, Kafka and the clock.
Triggers at a glance
| Use case | Trigger | Inbound adapter | Emits |
|---|---|---|---|
AuthorizePayment | checkout | REST POST /payment-authorizations | PaymentAuthorized or PaymentDeclined |
VoidAuthorization | checkout after a definitive rejection; policy VoidUnboundAuthorizations | REST POST /payment-authorizations/{authorizationId}/voids; scheduler | PaymentReleased (reason VOIDED) |
RequestRefund | Storefront ops; policies RefundOnLostPackage, RefundOnReturnToSender | REST POST /refunds; Kafka consumer, retailnetwork.shipping-and-tracking.events | RefundIssued or RefundFailed after the outcome |
RecordRefundOutcome | The provider's answer to Refund | the provider port (inside RequestRefund) | RefundIssued or RefundFailed |
RetryRefund | Storefront ops or an automatic retry of a FAILED refund (max 5 attempts) | internal; the model's rest list has no route | RefundIssued or RefundFailed after the outcome |
CaptureAllocation | order-sourcing FulfillmentShipped, policy CaptureOnShipment | Kafka consumer, retailnetwork.order-sourcing.events | PaymentCaptured |
ReleaseAllocation | order-sourcing FulfillmentCancelled, policy ReleaseOnCancellation; FulfillmentUnsourceable, policy ReleaseOnUnsourceable | Kafka consumer, retailnetwork.order-sourcing.events | PaymentReleased |
BindOrder | checkout CheckoutCompleted, policy BindOrderOnCheckoutCompleted | Kafka consumer, retailnetwork.checkout.events | none |
ReauthorizePayment | Clock, policy ReauthorizeBeforeExpiry (24 h before expiresAt) | scheduler | PaymentReauthorized, or PaymentDeclined (reason REAUTH_DECLINED) on a provider decline |
ExpireAuthorization | a provider decline on re-authorization | internal, inside ReauthorizePayment | PaymentAuthorizationExpired |
How save and publish commit
Every use case that changes an aggregate loads it with its version, calls
the aggregate, then saves it inside one Postgres transaction. The save is
conditional on the version it loaded (UPDATE ... WHERE version = ?); a
conflict is retried once inside the use case, then surfaces as 409
concurrent-update. If an event is raised, the outbox row
(outbox_events) is written in the same transaction. A consumer-driven use
case also inserts the CloudEvents id into processed_events in that
transaction. A relay publishes outbox rows to
retailnetwork.customer-payments.events after the commit.
The provider call sits outside the transaction. A use case that calls
the provider (AuthorizePayment, CaptureAllocation, VoidAuthorization,
RequestRefund, ReauthorizePayment) calls the port first with the
deterministic key per (operation, authorizationId, groupNo), then saves
the outcome and the outbox row in one transaction. A crash between the two
repeats the call with the same key, which the provider answers with the
first result; that is the reason the key is deterministic.
Error responses use application/problem+json (RFC 9457) with type
/problems/<slug> per conventions.integration_rules: not-found 404,
illegal-transition 409, concurrent-update 409, validation-failed 422, plus
one kebab-case slug per Err in the model. Every write route takes an
Idempotency-Key header. Consumer-driven use cases (capture, release,
bind, refund policies) have no caller: an error is logged and the inbox row
is still written, which is a proposed disposition the model does not state.
AuthorizePayment
- Actor / trigger:
checkout, saga step before the place-order pivot. - Inbound adapter: REST
POST /payment-authorizations, headerIdempotency-Keyrequired (checkout sends<sessionId>:auth:<authAttempt>). - Input:
checkoutSessionId,paymentMethodToken(the PSP token, never a card number),currency,totalMinor,allocations(groupNo,amountMinor). - Preconditions: the session holds no live (non-declined) authorization, or the existing one is returned; allocations sum to the total and name the session's groups.
- Main flow:
Idempotency-Keylookup; replay the stored response on a hit.- Look up the session's live (non-declined) authorization. If there is one
(a sequential second authorize, under a different key), return it
unchanged with
200and do not call the provider. Otherwise check that the allocations sum to the total (ErrAllocationMismatch). - Call the provider
Authorizethrough the ACL port with the token, the total and the deterministic key. - Approved: create the
PaymentAuthorizationAUTHORIZEDwith the provider reference andexpiresAt. Declined: create itDECLINED, a terminal record. - In one transaction: save, outbox
PaymentAuthorizedorPaymentDeclined, store the key response. - Answer
201with the authorization (AUTHORIZEDorDECLINED); the checkout session stays open for another token after a decline (aDECLINEDrecord is not live, so the next authorize creates a new authorization).
- Errors:
| Error | HTTP | Problem type slug | Note |
|---|---|---|---|
ErrDuplicateAuthorization | 409 | duplicate-authorization | Only the concurrent race: two first authorizes for the same session under different keys run at once and the unique index rejects the second insert. It is not the answer to a sequential second authorize. |
ErrAllocationMismatch | 422 | allocation-mismatch | Allocations do not sum to the total or do not name the session's groups. |
| provider unreachable or timed out | 503 | payment-provider-unavailable | Retry with the same Idempotency-Key; the provider key is deterministic. |
| version conflict | 409 | concurrent-update | |
| malformed request | 422 | validation-failed | |
sequential second authorize, different Idempotency-Key | 200 | (none) | Not an error: the session's existing live authorization is returned unchanged. |
same Idempotency-Key again | the first status | (none) | The stored response is replayed (header Idempotency-Replayed: true); the same key with a different request is 409 idempotency-key-reused. |
- Events emitted:
PaymentAuthorizedorPaymentDeclined(analytics). - Idempotency:
Idempotency-Keyreplays the stored response; independently, one live authorization per session: a different key while one is live returns it (200), andduplicate-authorization(409) is raised only when two concurrent first calls race on the unique index.
VoidAuthorization
- Actor / trigger:
checkout, only after a definitive rejection of the place-order step (never while the outcome is in doubt); or the clock, policyVoidUnboundAuthorizations(noCheckoutCompletedafter 24 h). - Inbound adapter: REST
POST /payment-authorizations/{authorizationId}/voids, headerIdempotency-Keyrequired (<sessionId>:void); an internal scheduler for the policy. - Preconditions: the authorization is
AUTHORIZED(no capture yet). - Main flow:
Idempotency-Keylookup.- Load
PaymentAuthorization(404not-found). - Call the provider
Voidthrough the ACL port with the deterministic key. PaymentAuthorization.Void(now):AUTHORIZED → VOIDED; raisesPaymentReleased{reason: VOIDED}.- In one transaction: save (version-checked), store the key response.
- Answer
200with the authorization.
- Errors:
| Error | HTTP | Problem type slug | Note |
|---|---|---|---|
| not found | 404 | not-found | |
| authorization already captured, voided or expired | 409 | illegal-transition | The model lists VOIDED only from AUTHORIZED. |
| provider unreachable or timed out | 503 | payment-provider-unavailable | Retry with the same key. |
| version conflict | 409 | concurrent-update |
- Events emitted:
PaymentReleasedwith reasonVOIDED(analytics). - Idempotency:
Idempotency-Key; a second void of aVOIDEDauthorization replays the stored response.
RequestRefund
- Actor / trigger: storefront ops (
MANUAL); or the policiesRefundOnLostPackage(LOST) andRefundOnReturnToSender(RETURNED_TO_SENDER) onPackageLostandPackageReturned. - Inbound adapter: REST
POST /refunds, headerIdempotency-Keyrequired; Kafka consumer onretailnetwork.shipping-and-tracking.events, groupcustomer-payments.shipping-and-tracking. - Input:
orderId,groupNo,authorizationId,amountMinor,reason(REST); for the policies the group is found by the tracking number stored on its allocation at capture, and the amount is that group's captured amount. - Preconditions: the order is bound; refunds of the order do not exceed
its captured total (
REQUESTEDand issued refunds count;FAILEDnever does). - Main flow:
Idempotency-Keylookup, or inbox check on the CloudEventsid.- If the order is not bound yet, park the fact (consumer path only,
ParkedFulfillmentFacts). Refund.Request(...): createREQUESTED, checkingErrOverRefundagainst the order's captured total.- Call the provider
Refundthrough the ACL port with the deterministic key. RecordRefundOutcome(below), then answer201with the refund (REQUESTEDon the REST route when the outcome is still pending).
- Errors:
| Error | HTTP | Problem type slug | Note |
|---|---|---|---|
ErrOverRefund | 409 | over-refund | Refunds of the order would exceed its captured total. |
| provider unreachable or timed out | 503 | payment-provider-unavailable | Retry with the same Idempotency-Key. |
| version conflict | 409 | concurrent-update | |
| malformed request | 422 | validation-failed |
- Events emitted:
RefundIssuedorRefundFailed(analytics), fromRecordRefundOutcome. - Idempotency:
Idempotency-Keyon REST; inbox on the CloudEventsidand the provider key on the policy path.
RecordRefundOutcome
- Actor / trigger: the provider's answer to
Refund. - Inbound adapter: the provider port, inside
RequestRefund; the model names no separate route or callback. - Main flow:
Refund.RecordOutcome(result):REQUESTED → SUCCEEDEDorREQUESTED → FAILED(with the translated failurecode); save (version-checked), outboxRefundIssuedorRefundFailed, one transaction. - Errors: none reach a caller.
- Events emitted:
RefundIssuedorRefundFailed(analytics). - Idempotency: a
SUCCEEDEDrefund is terminal and a repeated answer is a no-op; aFAILEDrefund can be retried byRetryRefund.
RetryRefund
- Actor / trigger: storefront ops or an automatic retry of a
FAILEDrefund. The model'srestlist has noRetryRefundroute, so the REST contract carries none (H8). - Preconditions: the refund is
FAILEDand has fewer than 5 attempts;ErrOverRefundcountsREQUESTEDand issued refunds, neverFAILED. - Main flow:
Refund.Retry():FAILED → REQUESTED; call the providerRefundwith the same deterministic key;RecordRefundOutcome. After the fifth failed attempt the refund staysFAILEDand an operator alert fires. - Errors:
ErrOverRefund(409over-refund); a refund past 5 attempts is refused with 409illegal-transition. - Events emitted:
RefundIssuedorRefundFailed(analytics). - Idempotency: the provider key is deterministic per refund; a
REQUESTEDrefund is not retried.
CaptureAllocation (Kafka)
- Actor / trigger:
order-sourcingshipped a group; policyCaptureOnShipment. - Inbound adapter: Kafka consumer on
retailnetwork.order-sourcing.events, typecom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentShipped, consumer groupcustomer-payments.order-sourcing. - Main flow:
- Inbox check on the CloudEvents
id; a duplicate is acknowledged. - If
orderIdis not bound to an authorization yet, park the fact inParkedFulfillmentFacts(gap S4) and stop. - Load the authorization by
orderId; find the allocation bygroupNo(ErrUnknownGroup). - Call the provider
Capturethrough the ACL port with the key for (Capture,authorizationId,groupNo). PaymentAuthorization.Capture(groupNo, ...): allocationCAPTURED;AUTHORIZED → PARTIALLY_CAPTURED,PARTIALLY_CAPTURED → PARTIALLY_CAPTURED, orPARTIALLY_CAPTURED → CAPTURED. Guards:ErrOverCapture,ErrCaptureAfterExpiry. Set the allocation's nullabletrackingNumberfromtrackingNumbers(H6); the aggregate state is derived from the allocations, so a one-group order goesAUTHORIZED → CAPTURED.- In one transaction: save (version-checked), outbox
PaymentCaptured, inbox row.
- Inbox check on the CloudEvents
- Errors: none reach a caller.
ErrOverCapture,ErrCaptureAfterExpiryandErrUnknownGroupare logged as anomalies (proposed); a late capture after expiry is the case the correctness target counts. - Events emitted:
PaymentCaptured(analytics). - Idempotency: inbox on the CloudEvents
id; the deterministic provider key means a replayed capture cannot move money twice.
ReleaseAllocation (Kafka)
- Actor / trigger:
order-sourcingcancelled a group or found it unsourceable; policiesReleaseOnCancellationandReleaseOnUnsourceable. - Inbound adapter: Kafka consumer on
retailnetwork.order-sourcing.events, typecom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentCancelledor...FulfillmentUnsourceable, consumer groupcustomer-payments.order-sourcing. - Main flow:
- Inbox check; park the fact if the order is not bound.
- Load the authorization by
orderId; find the allocation bygroupNo(ErrUnknownGroup). - For a partial release call the provider
ReduceAuthorization(amount)through the ACL port (H4). PaymentAuthorization.Release(groupNo, reason): allocationRELEASED(reasonCANCELLEDorUNSOURCEABLE); the state follows the allocations:AUTHORIZED → AUTHORIZEDorRELEASED,PARTIALLY_CAPTURED → PARTIALLY_CAPTURED,CAPTUREDorRELEASED(H3).- In one transaction: save (version-checked), outbox
PaymentReleased, inbox row.
- Errors: none reach a caller;
ErrUnknownGroupis logged. - Events emitted:
PaymentReleased(analytics). - Idempotency: inbox on the CloudEvents
id.
BindOrder (Kafka)
- Actor / trigger:
checkoutcompleted the purchase; policyBindOrderOnCheckoutCompleted. - Inbound adapter: Kafka consumer on
retailnetwork.checkout.events, typecom.retailnetwork.storefront.checkout.checkoutsession.CheckoutCompleted, consumer groupcustomer-payments.checkout. - Main flow:
- Inbox check on the CloudEvents
id. - Load the authorization by
authorizationId(the event carries it). PaymentAuthorization.BindOrder(orderId): setorderId.- Apply every parked fact for the
orderId, in arrival order, throughCaptureAllocation,ReleaseAllocationandRequestRefund. Parked facts older than 30 days were purged (H10). - Save (version-checked), inbox row, one transaction; the applied facts raise their own events.
- Inbox check on the CloudEvents
- Errors: none reach a caller.
- Events emitted: none from the bind itself.
- Idempotency: inbox on the CloudEvents
id; binding the sameorderIdtwice is a no-op.
ReauthorizePayment (clock)
- Actor / trigger: the clock; policy
ReauthorizeBeforeExpiry, 24 h beforeexpiresAt, for authorizations with allocations stillPENDING. - Inbound adapter: an internal scheduler scanning
expires_at. - Main flow: per authorization, call the provider
Reauthorizethrough the ACL port for the uncaptured allocations with the deterministic key. On successReauthorize(providerAuthorizationId, newExpiresAt):AUTHORIZED → AUTHORIZEDwith the newexpiresAtand provider reference. On a provider decline the authorization goes toEXPIRED(ExpireAuthorization) andPaymentDeclined{reason: REAUTH_DECLINED}is raised (H1, H2). - Errors: none reach a caller.
- Events emitted:
PaymentReauthorized, orPaymentDeclinedandPaymentAuthorizationExpiredon a decline (analytics). - Idempotency: the deterministic provider key; the scan selects only authorizations close to expiry.
ExpireAuthorization
- Actor / trigger: a provider decline on re-authorization, inside
ReauthorizePayment(H2). - Main flow:
PaymentAuthorization.Expire(now):AUTHORIZED → EXPIREDorPARTIALLY_CAPTURED → EXPIRED; save (version-checked), outboxPaymentAuthorizationExpired, one transaction. - Errors: none reach a caller.
- Events emitted:
PaymentAuthorizationExpired(analytics). - Idempotency: the transition is terminal; a second expiry is a no-op.