---
id: CompleteOrder
name: Complete order
version: 1.0.0
badges:
  - content: Order Lifecycle
    backgroundColor: blue
    textColor: blue
summary: Marks an existing Order as Completed when its current status is New.
owners:
  - commerce-fulfillment-team
schemaPath: schema.json
operation:
  method: PATCH
  path: /api/v1/orders/{orderId}/complete
  statusCodes: ["200", "404"]
sidebar:
  badge: "PATCH"
---

`CompleteOrder` transitions an existing order from `New` to `Completed` in [[service|order-api]] (`PATCH /ordering/api/v1/orders/{orderId}/complete`) and publishes an integration event so [[service|order-orchestration]] can dispatch completion notifications.

## Overview

| Property                           | Value                                                                                                                                                        |
| :--------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context**                | Ordering                                                                                                                                                     |
| **Owner Service**                  | [[service\|order-api]]                                                                                                                                       |
| **Protocol / Format**              | HTTP `PATCH`, `application/json` response                                                                                                                    |
| **Gateway Endpoint**               | `PATCH /ordering/api/v1/orders/{orderId}/complete` (service path `/api/v1/orders/{orderId}/complete`)                                                        |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write`                                                            |
| **Idempotency / Concurrency**      | Required `x-request-id` header (Redis-backed 3600s TTL; returns `409 Conflict` on duplicate); optimistic concurrency (`412 Precondition Failed` on conflict) |
| **Rate Limit / Caching**           | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`)                            |
| **Contract Version**               | `1.0.0` (`ApiVersions.V1`)                                                                                                                                   |

## Request & Response Contract

### Path Parameters & Headers

Accepts no request body.

| Name           | Type              | Required | Constraints                            | Description                                                        |
| :------------- | :---------------- | :------- | :------------------------------------- | :----------------------------------------------------------------- |
| `orderId`      | `string` (`uuid`) | Yes      | Path parameter; valid UUID             | Unique identifier of the order to complete                         |
| `x-request-id` | `string`          | Yes      | HTTP header; non-empty, non-whitespace | Client-generated idempotency key tracked in Redis for 3600 seconds |

### Success Response (`200 OK`)

| Name               | Type                   | Required | Constraints                         | Description                                                                      |
| :----------------- | :--------------------- | :------- | :---------------------------------- | :------------------------------------------------------------------------------- |
| `id`               | `string` (`uuid`)      | Yes      | Valid UUID                          | Unique identifier of the completed order                                         |
| `date`             | `string` (`date-time`) | Yes      | ISO 8601 UTC timestamp              | Creation timestamp                                                               |
| `total`            | `number`               | Yes      | Rounded to 2 decimal places         | Sum of `quantity * price` across all order items                                 |
| `status`           | `string`               | Yes      | `"Completed"` on success            | Current lifecycle status                                                         |
| `items`            | `object[]`             | Yes      | Array of line items                 | Purchased items belonging to the order                                           |
| `items[].id`       | `string` (`uuid`)      | Yes      | Valid UUID                          | Line item identifier                                                             |
| `items[].quantity` | `integer`              | Yes      | `> 0`                               | Purchased quantity for the item                                                  |
| `items[].price`    | `number`               | Yes      | `>= 0`, rounded to 2 decimal places | Unit price captured at order creation                                            |
| `items[].name`     | `string \| null`       | No       | Nullable                            | Book title (`null` in this response because catalog enrichment is not performed) |

## Behavior & Side Effects

- **Access scoping:** Administrators can target any `New` order; customers can only target orders matching their authenticated buyer ID.
- **State transition:** Transitions `New` to `Completed`. Orders already in `Completed` or `Cancelled` status cannot transition again (admins receive `404 Not Found`; customers targeting their own non-`New` order receive `500 Internal Server Error`).
- **Event publishing:** Appends the completion event to the event store and publishes [[event|OrderStatusChangedToCompleteIntegrationEvent]] via transactional outbox to [[channel|bookworm.&#123;env&#125;.ordering.order-status-change-to-complete]] (partitioned by `OrderId`).
- **Idempotency key lifecycle:** Claims the `x-request-id` key in Redis for 3600 seconds (`409 Conflict` on replay) and deletes the key if the operation fails with `5xx` so retries can proceed.

## Error Responses

| Status / Code               | Condition                                                                                                               | Client Recovery Action                                                                   |
| :-------------------------- | :---------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- |
| `400 Bad Request`           | Missing or whitespace `x-request-id` header, or invalid user identifier claim                                           | Provide a non-empty `x-request-id` header and valid token claims; do not retry unchanged |
| `401 Unauthorized`          | Missing, expired, or invalid Entra ID bearer token                                                                      | Acquire a fresh Entra ID access token and retry                                          |
| `403 Forbidden`             | Caller lacks `customer`/`admin` role or `ordering_read`/`ordering_write` scopes                                         | Request the required Entra ID role and scopes before retrying                            |
| `404 Not Found`             | Order does not exist, is soft-deleted, belongs to another buyer, or (for `admin`) is not in `New` status                | Verify the `orderId` and current order status; do not retry unchanged                    |
| `409 Conflict`              | Duplicate `x-request-id` for this path within the 3600-second TTL                                                       | Treat as a duplicate submission and query order status before taking further action      |
| `412 Precondition Failed`   | Concurrent update conflict on the order or event stream                                                                 | Refresh order state and retry with a new `x-request-id` if still `New`                   |
| `429 Too Many Requests`     | Rate limit quota exceeded (`Retry-After` header included)                                                               | Wait for the `Retry-After` interval before retrying                                      |
| `500 Internal Server Error` | Customer attempted to complete an owned order already in `Completed` or `Cancelled` status, or unhandled server failure | Inspect the order's current status; do not retry non-`New` transitions                   |

## Related Documentation

- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|order]] — Order aggregate invariants and lifecycle statuses.
- [[event|OrderStatusChangedToCompleteIntegrationEvent]] — Kafka event emitted on completion.
- [[channel|bookworm.&#123;env&#125;.ordering.order-status-change-to-complete]] — Kafka topic specification.
- [[command|CancelOrder]] — Transition a `New` order to `Cancelled`.

<NodeGraph />

<SchemaViewer file="schema.json" title="Complete order schema" maxHeight="500" search="true" />


 ## Raw Schema:schema.json

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"title": "CompleteOrderRequest",
	"description": "Path and header parameters for completing an Order. The operation has no request body.",
	"type": "object",
	"required": ["orderId", "x-request-id"],
	"properties": {
		"orderId": {
			"type": "string",
			"description": "Unique identifier of the Order to complete."
		},
		"x-request-id": {
			"type": "string",
			"description": "Idempotency key for the completion request."
		}
	}
}
