---
id: order-api
name: Order API
version: 1.0.0
summary: |
  Authenticated Ordering service for Buyer profiles and the Order lifecycle,
  creating Orders from baskets, snapshotting prices, and coordinating status events.
owners:
  - commerce-fulfillment-team
badges:
  - content: Internal
    backgroundColor: gray
    textColor: gray
  - content: HTTP API
    backgroundColor: teal
    textColor: teal
diagrams:
  - id: order-lifecycle
    version: 1.0.0
  - id: checkout-interaction
    version: 1.0.0
readsFrom:
  - id: order-database
    version: 1.0.0
  - id: order-cache
    version: 1.0.0
writesTo:
  - id: order-database
    version: 1.0.0
  - id: order-cache
    version: 1.0.0
receives:
  - id: CreateOrder
    version: 1.0.0
    group: Order Commands
  - id: CompleteOrder
    version: 1.0.0
    group: Order Commands
  - id: CancelOrder
    version: 1.0.0
    group: Order Commands
  - id: DeleteOrder
    version: 1.0.0
    group: Order Commands
  - id: CreateBuyer
    version: 1.0.0
    group: Buyer Commands
  - id: UpdateAddress
    version: 1.0.0
    group: Buyer Commands
  - id: DeleteBuyer
    version: 1.0.0
    group: Buyer Commands
  - id: GetOrder
    version: 1.0.0
    group: Order Queries
  - id: ListOrders
    version: 1.0.0
    group: Order Queries
  - id: GetBuyer
    version: 1.0.0
    group: Buyer Queries
  - id: ListBuyers
    version: 1.0.0
    group: Buyer Queries
  - id: DeleteBasketCompleteCommand
    version: 1.0.0
    group: Basket Cleanup Outcomes
    from:
      - id: bookworm.{env}.finance.delete-basket-complete
        version: 1.0.0
  - id: DeleteBasketFailedCommand
    version: 1.0.0
    group: Basket Cleanup Outcomes
    from:
      - id: bookworm.{env}.finance.delete-basket-failed
        version: 1.0.0
sends:
  - id: GetBasketGrpc
    version: 1.0.0
    group: Checkout Enrichment Queries
  - id: GetBookGrpc
    version: 1.0.0
    group: Checkout Enrichment Queries
  - id: GetBooksGrpc
    version: 1.0.0
    group: Checkout Enrichment Queries
  - id: GetDashboardGrpc
    version: 1.0.0
  - id: UserCheckedOutIntegrationEvent
    version: 1.0.0
    to:
      - id: bookworm.{env}.ordering.user-checked-out
        version: 1.0.0
  - id: OrderStatusChangedToCompleteIntegrationEvent
    version: 1.0.0
    group: Order Status Changes
    to:
      - id: bookworm.{env}.ordering.order-status-change-to-complete
        version: 1.0.0
  - id: OrderStatusChangedToCancelIntegrationEvent
    version: 1.0.0
    group: Order Status Changes
    to:
      - id: bookworm.{env}.ordering.order-status-change-to-cancel
        version: 1.0.0
entities:
  - id: buyer
    version: 1.0.0
  - id: order
    version: 1.0.0
  - id: order-item
    version: 1.0.0
styles:
  icon: /icons/languages/dotnet.svg
specifications:
  - type: openapi
    path: openapi-v1.yaml
    name: OpenAPI v1
  - type: asyncapi
    path: asyncapi-v1.yml
    name: AsyncAPI v1
  - type: generic
    path: sla.yaml
    name: Carrier Service Levels
repository:
  language: C#
  url: "https://github.com/foxminchan/BookWorm"
---

## Service Responsibility & Boundary

Order API is the system of record within the [[domain|ordering]] domain for [[entity|buyer]] profiles, accepted [[entity|order]] aggregates, purchase-time [[entity|order-item]] price snapshots, and Order lifecycle statuses (`New`, `Completed`, `Cancelled`). It serves versioned HTTP endpoints and Server-Sent Events (SSE) backoffice dashboards, queries [[service|basket-api]] and [[service|catalog-api]] over gRPC during checkout, and delegates post-checkout basket cleanup and email coordination to [[service|order-orchestration]] over Kafka.

## Service Profile

| Property                                  | Value                                                                                                                                                                                                |
| :---------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain**              | [[domain\|ordering]]                                                                                                                                                                                 |
| **Owner Team**                            | [[team\|commerce-fulfillment-team]]                                                                                                                                                                  |
| **Runtime Style**                         | REST API, SSE Dashboard Stream, gRPC Client, and Async Kafka Producer/Consumer                                                                                                                       |
| **Public / Gateway Exposure**             | Yes via API Gateway                                                                                                                                                                                  |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT via [[system\|identity-provider]]; `customer` or `admin` roles with ordering scopes; backoffice dashboard also requires `admin` and catalog read scope                        |
| **Owned Data Store(s)**                   | [[container\|order-database]] (relational, event-sourced history, and transactional outbox), [[container\|order-cache]] (distributed locks, idempotency markers, and dashboard cache)                |
| **Key Resilience / Idempotency Pattern**  | 1-hour `x-request-id` idempotency markers, buyer-scoped distributed write locks, per-user rate limiting, and dead-letter routing on [[channel\|bookworm.&#123;env&#125;.ordering.dead-letter-queue]] |

## Contracts & Data Ownership

Order API owns [[entity|buyer]], [[entity|order]], and [[entity|order-item]] in [[container|order-database]] and uses [[container|order-cache]] for checkout concurrency locks, idempotency markers, and short-lived dashboard caching.

:::note
Every new Order starts in `New` status with line totals locked to active Catalog prices (sale price when set, otherwise regular price). Later Catalog price edits never rewrite accepted Orders, and soft-deletion on failed basket cleanup preserves audit records without altering business status.
:::

:::warning
State-changing Order operations require an `x-request-id` idempotency header. Duplicate keys within the 1-hour idempotency window return `409 Conflict`—callers should inspect existing Order status before generating a new idempotency key.
:::

<MessageTable format="all" limit={20} showChannels={true} />

<Accordion title="Event Sourcing & Downstream Coordination">
	- **Order event stream:** Domain events append to an event stream in [[container|order-database]]
	to support chronological order history and time-travel summary views. - **Lifecycle separation:**
	Completing or cancelling an Order is permitted only from `New` status; receiving
	[[command|DeleteBasketCompleteCommand]] never auto-completes an Order, and
	[[command|DeleteBasketFailedCommand]] soft-deletes the Order without changing its business status.
</Accordion>

## Architecture Visualizations & Specifications

### Order API Context

<MermaidFileLoader file="mermaids/OrderAPI-diagram-1.mmd" />

### Service Interactions

<NodeGraph />

### Owned Entities

<EntityMap />

## Attached Resources & Related Docs

- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka directory.
- [[service|order-orchestration]] — Downstream Finance durable workflow.
- [[container|order-database]] — PostgreSQL relational, event-store, and outbox storage.
- [[container|order-cache]] — Redis locks, idempotency, and dashboard cache.
- [[diagram|order-lifecycle]] — Order status transitions and saga separation.
- [[doc|domains/bookworm/subdomains/ordering/engineering/01-order-consistency-and-data-ownership]] — Ordering consistency and ownership boundaries.


 ## Raw Schema:openapi-v1.yaml

openapi: 3.2.0
info:
  title: Ordering Service API
  description: "Orchestrates the entire order lifecycle, from creation to completion or cancellation, for the BookWorm platform"
  contact:
    name: BookWorm Engineering
    url: https://github.com/foxminchan
    email: engineering@bookworm.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT
  version: "1.0"
  summary: A service responsible for managing the order lifecycle for the BookWorm platform
paths:
  /api/v1/orders:
    get:
      tags:
        - Order
      summary: List Orders
      description: List orders with pagination and filtering
      operationId: ListOrdersEndpoint
      parameters:
        - name: PageIndex
          in: query
          description: Number of items to return in a single page of results
          schema:
            pattern: "^-?(?:0|[1-9]\\d*)$"
            type:
              - integer
              - string
            format: int32
            default: 1
        - name: PageSize
          in: query
          description: Number of items to return in a single page of results
          schema:
            pattern: "^-?(?:0|[1-9]\\d*)$"
            type:
              - integer
              - string
            format: int32
            default: 20
        - name: Status
          in: query
          description: Status to filter results by
          schema:
            $ref: "#/components/schemas/Status"
        - name: BuyerId
          in: query
          description: Buyer ID to filter results by
          schema:
            type: string
            format: uuid
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/OrderDto"
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
    post:
      tags:
        - Order
      summary: Create Order
      description: Create a new order
      operationId: CreateOrderEndpoint
      parameters:
        - name: x-request-id
          in: header
          description: The idempotency key of the order to be created
          required: true
          schema:
            type: string
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OrderId"
  "/api/v1/orders/{id}":
    get:
      tags:
        - Order
      summary: Get Order
      description: Get an order if it exists
      operationId: GetOrderEndpoint
      parameters:
        - name: id
          in: path
          description: The unique identifier of the order to be retrieved
          required: true
          schema:
            type: string
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OrderDetailDto"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
    delete:
      tags:
        - Order
      summary: Delete Order
      description: Delete an order if it exists
      operationId: DeleteOrderEndpoint
      parameters:
        - name: id
          in: path
          description: The unique identifier of the order to be deleted
          required: true
          schema:
            type: string
      responses:
        "204":
          description: No Content
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  "/api/v1/orders/{id}/summary":
    get:
      tags:
        - Order
      summary: Get Order Event-Sourced Summary
      description: Reconstructs the order summary from its event stream (optionally at a specific version) and returns its stream version as an ETag
      operationId: GetOrderSummaryEndpoint
      parameters:
        - name: id
          in: path
          description: The unique identifier of the order
          required: true
          schema:
            type: string
        - name: version
          in: query
          description: Optional stream version for point-in-time replay
          schema:
            pattern: "^-?(?:0|[1-9]\\d*)$"
            type:
              - integer
              - string
            format: int64
        - name: at
          in: query
          description: Optional UTC timestamp for point-in-time replay
          schema:
            type: string
            format: date-time
        - name: If-None-Match
          in: header
          description: Entity tag for conditional requests; returns 304 Not Modified when the resource has not changed
          schema:
            type: string
      responses:
        "200":
          description: OK
          headers:
            ETag:
              description: Entity tag representing the current resource version
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OrderSummaryDto"
        "304":
          description: Not Modified
          headers:
            ETag:
              description: Entity tag representing the current resource version
              schema:
                type: string
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  "/api/v1/orders/{id}/history":
    get:
      tags:
        - Order
      summary: Get Order Event History
      description: Get the chronological event stream history for an order
      operationId: GetOrderHistoryEndpoint
      parameters:
        - name: id
          in: path
          description: The unique identifier of the order
          required: true
          schema:
            type: string
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/OrderEventHistoryDto"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  "/api/v1/orders/{orderId}/complete":
    patch:
      tags:
        - Order
      summary: Complete Order
      description: Complete an order
      operationId: CompleteOrderEndpoint
      parameters:
        - name: x-request-id
          in: header
          description: The idempotency key of the order to be completed
          required: true
          schema:
            type: string
        - name: orderId
          in: path
          description: The unique identifier of the order to be completed
          required: true
          schema:
            type: string
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OrderDetailDto"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  "/api/v1/orders/{orderId}/cancel":
    patch:
      tags:
        - Order
      summary: Cancel Order
      description: Cancel an order
      operationId: CancelOrderEndpoint
      parameters:
        - name: x-request-id
          in: header
          description: The idempotency key of the order to be cancelled
          required: true
          schema:
            type: string
        - name: orderId
          in: path
          description: The unique identifier of the order to be cancelled
          required: true
          schema:
            type: string
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OrderDetailDto"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  /api/v1/dashboard:
    get:
      tags:
        - Dashboard
      summary: Get backoffice dashboard
      description: "Get store-wide totals, seven UTC daily buckets, categories, and the five newest orders"
      operationId: GetDashboardEndpoint
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DashboardDto"
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
  /api/v1/dashboard/stream:
    get:
      tags:
        - Dashboard
      summary: Stream backoffice dashboard
      description: Send cached dashboard snapshots every 15 seconds; reconnect to resynchronize
      operationId: StreamDashboardEndpoint
      responses:
        "200":
          description: OK
          content:
            text/event-stream:
              itemSchema:
                required:
                  - data
                type: object
                properties:
                  data:
                    $ref: "#/components/schemas/DashboardDto"
                  event:
                    type: string
                  id:
                    type: string
  /api/v1/buyers/address:
    patch:
      tags:
        - Buyer
      summary: Update Buyer Address
      description: "Update the current buyer's address"
      operationId: UpdateAddressEndpoint
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/UpdateAddressCommand"
        required: true
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BuyerDto"
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  /api/v1/buyers:
    get:
      tags:
        - Buyer
      summary: List Buyers
      description: List all buyers with pagination options
      operationId: ListBuyersEndpoint
      parameters:
        - name: PageIndex
          in: query
          description: Number of items to return in a single page of results
          schema:
            pattern: "^-?(?:0|[1-9]\\d*)$"
            type:
              - integer
              - string
            format: int32
            default: 1
        - name: PageSize
          in: query
          description: Number of items to return in a single page of results
          schema:
            pattern: "^-?(?:0|[1-9]\\d*)$"
            type:
              - integer
              - string
            format: int32
            default: 20
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/BuyerDto"
    post:
      tags:
        - Buyer
      summary: Create Buyer
      description: Create a new buyer in the system
      operationId: CreateBuyerEndpoint
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateBuyerCommand"
        required: true
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BuyerId"
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
  /api/v1/buyers/me:
    get:
      tags:
        - Buyer
      summary: Get Buyer
      description: "Get the current buyer's information"
      operationId: GetBuyerEndpoint
      parameters:
        - name: Id
          in: query
          description: "Only 'ADMIN' role can retrieve other users' data"
          required: true
          schema:
            type: string
            format: uuid
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BuyerDto"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  "/api/v1/buyers/{id}":
    delete:
      tags:
        - Buyer
      summary: Delete Buyer
      description: Delete a buyer by ID if it exists
      operationId: DeleteBuyerEndpoint
      parameters:
        - name: id
          in: path
          description: The unique identifier of the buyer to be deleted
          required: true
          schema:
            type: string
      responses:
        "204":
          description: No Content
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
components:
  schemas:
    BuyerDto:
      required:
        - id
        - name
        - address
      type: object
      properties:
        id:
          $ref: "#/components/schemas/BuyerId"
        name:
          type:
            - "null"
            - string
        address:
          type:
            - "null"
            - string
    BuyerId:
      type: string
      format: uuid
    CategoryCountDto:
      required:
        - name
        - value
      type: object
      properties:
        name:
          type: string
        value:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
    CreateBuyerCommand:
      required:
        - street
        - city
        - province
      type: object
      properties:
        street:
          type: string
        city:
          type: string
        province:
          type: string
    DailyOrdersDto:
      required:
        - date
        - orders
        - revenue
      type: object
      properties:
        date:
          type: string
          format: date
        orders:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
        revenue:
          format: double
    DashboardDto:
      required:
        - totalOrders
        - totalRevenue
        - totalCustomers
        - totalBooks
        - dailyOrders
        - categories
        - recentOrders
        - updatedAt
      type: object
      properties:
        totalOrders:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
        totalRevenue:
          format: double
        totalCustomers:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
        totalBooks:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
        dailyOrders:
          type: array
          items:
            $ref: "#/components/schemas/DailyOrdersDto"
        categories:
          type: array
          items:
            $ref: "#/components/schemas/CategoryCountDto"
        recentOrders:
          type: array
          items:
            $ref: "#/components/schemas/RecentOrderDto"
        updatedAt:
          type: string
          format: date-time
    HttpValidationProblemDetails:
      type: object
      properties:
        type:
          type:
            - "null"
            - string
        title:
          type:
            - "null"
            - string
        status:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - "null"
            - integer
            - string
          format: int32
        detail:
          type:
            - "null"
            - string
        instance:
          type:
            - "null"
            - string
        errors:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
    OrderDetailDto:
      required:
        - id
        - date
        - total
        - status
        - items
      type: object
      properties:
        id:
          $ref: "#/components/schemas/OrderId"
        date:
          type: string
          format: date-time
        total:
          format: double
        status:
          $ref: "#/components/schemas/Status"
        items:
          type: array
          items:
            $ref: "#/components/schemas/OrderItemDto"
    OrderDto:
      required:
        - id
        - date
        - total
        - status
      type: object
      properties:
        id:
          $ref: "#/components/schemas/OrderId"
        date:
          type: string
          format: date-time
        total:
          format: double
        status:
          $ref: "#/components/schemas/Status"
    OrderEventHistoryDto:
      required:
        - sequence
        - version
        - eventType
        - timestamp
        - status
        - totalPrice
      type: object
      properties:
        sequence:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
        version:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
        eventType:
          type: string
        timestamp:
          type: string
          format: date-time
        status:
          oneOf:
            - type: "null"
            - $ref: "#/components/schemas/Status"
        totalPrice:
          format: double
    OrderId:
      type: string
      format: uuid
    OrderItemDto:
      required:
        - id
        - quantity
        - price
      type: object
      properties:
        id:
          type: string
          format: uuid
        quantity:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int32
        price:
          format: double
        name:
          type:
            - "null"
            - string
    OrderSummaryDto:
      required:
        - id
        - status
        - totalPrice
        - version
      type: object
      properties:
        id:
          type: string
          format: uuid
        status:
          $ref: "#/components/schemas/Status"
        totalPrice:
          format: double
        version:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int64
    ProblemDetails:
      type: object
      properties:
        type:
          type:
            - "null"
            - string
        title:
          type:
            - "null"
            - string
        status:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - "null"
            - integer
            - string
          format: int32
        detail:
          type:
            - "null"
            - string
        instance:
          type:
            - "null"
            - string
    RecentOrderDto:
      required:
        - id
        - date
        - total
        - status
      type: object
      properties:
        id:
          type: string
          format: uuid
        date:
          type: string
          format: date-time
        total:
          format: double
        status:
          type: string
    Status:
      enum:
        - New
        - Cancelled
        - Completed
    UpdateAddressCommand:
      required:
        - street
        - city
        - province
      type: object
      properties:
        street:
          type: string
        city:
          type: string
        province:
          type: string
tags:
  - name: Buyer
  - name: Dashboard
  - name: Order


 ## Raw Schema:asyncapi-v1.yml

asyncapi: 3.1.0
info:
  title: Order API integration messages
  version: 1.0.0
  description: |
    AsyncAPI contract for Order API's Finance integration. Order API publishes
    checkout and Order status events, and consumes basket-cleanup outcomes.
defaultContentType: application/cloudevents+json
channels:
  userCheckedOut:
    address: bookworm.{env}.ordering.user-checked-out
    description: Order API publishes this event after placing an Order.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      userCheckedOut:
        $ref: "#/components/messages/UserCheckedOutIntegrationEvent"
  orderStatusChangedToComplete:
    address: bookworm.{env}.ordering.order-status-change-to-complete
    description: Order API publishes this event after completing an Order.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      orderStatusChangedToComplete:
        $ref: "#/components/messages/OrderStatusChangedToCompleteIntegrationEvent"
  orderStatusChangedToCancel:
    address: bookworm.{env}.ordering.order-status-change-to-cancel
    description: Order API publishes this event after cancelling an Order.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      orderStatusChangedToCancel:
        $ref: "#/components/messages/OrderStatusChangedToCancelIntegrationEvent"
  deleteBasketComplete:
    address: bookworm.{env}.finance.delete-basket-complete
    description: Finance publishes this command after successful basket cleanup.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      deleteBasketComplete:
        $ref: "#/components/messages/DeleteBasketCompleteCommand"
  deleteBasketFailed:
    address: bookworm.{env}.finance.delete-basket-failed
    description: Finance publishes this command when basket cleanup fails.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      deleteBasketFailed:
        $ref: "#/components/messages/DeleteBasketFailedCommand"
operations:
  sendUserCheckedOut:
    action: send
    channel:
      $ref: "#/channels/userCheckedOut"
    summary: Publish checkout details
    messages:
      - $ref: "#/channels/userCheckedOut/messages/userCheckedOut"
  sendOrderStatusChangedToComplete:
    action: send
    channel:
      $ref: "#/channels/orderStatusChangedToComplete"
    summary: Publish completed Order details
    messages:
      - $ref: "#/channels/orderStatusChangedToComplete/messages/orderStatusChangedToComplete"
  sendOrderStatusChangedToCancel:
    action: send
    channel:
      $ref: "#/channels/orderStatusChangedToCancel"
    summary: Publish cancelled Order details
    messages:
      - $ref: "#/channels/orderStatusChangedToCancel/messages/orderStatusChangedToCancel"
  receiveDeleteBasketComplete:
    action: receive
    channel:
      $ref: "#/channels/deleteBasketComplete"
    summary: Receive successful basket-cleanup outcomes
    messages:
      - $ref: "#/channels/deleteBasketComplete/messages/deleteBasketComplete"
  receiveDeleteBasketFailed:
    action: receive
    channel:
      $ref: "#/channels/deleteBasketFailed"
    summary: Receive failed basket-cleanup outcomes
    messages:
      - $ref: "#/channels/deleteBasketFailed/messages/deleteBasketFailed"
components:
  parameters:
    env:
      description: BookWorm deployment environment.
      enum:
        - development
        - staging
        - production
      default: development
  messages:
    UserCheckedOutIntegrationEvent:
      name: UserCheckedOutIntegrationEvent
      title: User checked out
      summary: An Order was placed and checkout details are ready for Finance.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/OrderIntegrationEventPayload"
    OrderStatusChangedToCompleteIntegrationEvent:
      name: OrderStatusChangedToCompleteIntegrationEvent
      title: Order completed
      summary: An Order transitioned from New to Completed.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/OrderIntegrationEventPayload"
    OrderStatusChangedToCancelIntegrationEvent:
      name: OrderStatusChangedToCancelIntegrationEvent
      title: Order cancelled
      summary: An Order transitioned from New to Cancelled.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/OrderIntegrationEventPayload"
    DeleteBasketCompleteCommand:
      name: DeleteBasketCompleteCommand
      title: Basket deletion completed
      summary: Finance reports that basket cleanup completed successfully.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/DeleteBasketCompletePayload"
    DeleteBasketFailedCommand:
      name: DeleteBasketFailedCommand
      title: Basket deletion failed
      summary: Finance reports that basket cleanup failed.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/DeleteBasketFailedPayload"
  schemas:
    OrderIntegrationEventPayload:
      type: object
      additionalProperties: false
      required:
        - id
        - creationDate
        - orderId
        - basketId
        - fullName
        - email
        - totalMoney
      properties:
        id:
          type: string
          format: uuid
          description: Unique identifier assigned to the integration event.
        creationDate:
          type: string
          format: date-time
          description: UTC timestamp when the integration event was created.
        orderId:
          type: string
          format: uuid
          description: Identifier of the Order.
        basketId:
          type: string
          format: uuid
          description: |
            UUID serialized as basketId. The current EventMapper supplies the
            Order's BuyerId for this field.
        fullName:
          type:
            - string
            - "null"
          description: Customer name, when available.
        email:
          type:
            - string
            - "null"
          format: email
          description: Customer email, when available.
        totalMoney:
          type: number
          format: double
          description: Total purchase amount associated with the Order.
    DeleteBasketCompletePayload:
      type: object
      additionalProperties: false
      required:
        - id
        - creationDate
        - orderId
        - totalMoney
      properties:
        id:
          type: string
          format: uuid
          description: Unique identifier assigned to the integration message.
        creationDate:
          type: string
          format: date-time
          description: UTC timestamp when the integration message was created.
        orderId:
          type: string
          format: uuid
          description: Identifier of the Order whose basket cleanup completed.
        totalMoney:
          type: number
          format: double
          description: Total purchase amount associated with the Order.
    DeleteBasketFailedPayload:
      type: object
      additionalProperties: false
      required:
        - id
        - creationDate
        - basketId
        - email
        - orderId
        - totalMoney
      properties:
        id:
          type: string
          format: uuid
          description: Unique identifier assigned to the integration message.
        creationDate:
          type: string
          format: date-time
          description: UTC timestamp when the integration message was created.
        basketId:
          type: string
          format: uuid
          description: Identifier of the basket whose cleanup failed.
        email:
          type:
            - string
            - "null"
          format: email
          description: Customer email, when available.
        orderId:
          type: string
          format: uuid
          description: Identifier of the affected Order.
        totalMoney:
          type: number
          format: double
          description: Total purchase amount associated with the Order.


 ## Raw Schema:sla.yaml

kind: CarrierServiceLevelAgreement
version: 2026.1
status: draft
domain: ordering
purpose: >-
  Provide delivery estimates for order planning. The carrier owns shipment
  execution; delivery does not itself change the BookWorm Order status.
effectiveDate: Upon signature by both parties

carriers:
  - id: bookworm-primary-carrier
    name: BookWorm Primary Parcel Carrier
    regions:
      - BookWorm-supported domestic delivery destinations
    serviceLevels:
      - code: STANDARD
        deliveryDays: "3-5"
        deliveryDayType: business-days
        deliveryPeriodStarts: carrier-acceptance
        cutOffTime: "16:00"
        cutOffTimeZone: destination-local-time
        maxParcelWeightKg: 30
        targetStatus: proposed
      - code: EXPRESS
        deliveryDays: "1-2"
        deliveryDayType: business-days
        deliveryPeriodStarts: carrier-acceptance
        cutOffTime: "14:00"
        cutOffTimeZone: destination-local-time
        maxParcelWeightKg: 20
        targetStatus: proposed
      - code: NEXT_DAY
        deliveryDays: "1"
        deliveryDayType: business-days
        deliveryPeriodStarts: carrier-acceptance
        cutOffTime: "12:00"
        cutOffTimeZone: destination-local-time
        maxParcelWeightKg: 10
        targetStatus: proposed
    collection:
      window: "17:00-19:00"
      timeZone: BookWorm warehouse local time
      days: [MON, TUE, WED, THU, FRI]
      targetStatus: proposed
    penalties:
      lateDeliveryCreditPercent: 15
      lostParcelReimbursement: full-value
      status: proposed
      terms: >-
        Define the credit basis, claim window, evidence requirements, exclusions,
        and reimbursement cap in the signed carrier contract.

support:
  escalationEmail: engineering@bookworm.com
  responseTimeHours: 4
  responseTimeBasis: business-hours
  targetStatus: proposed

assumptions:
  - Delivery estimates are measured from carrier acceptance, not Order creation.
  - The carrier name is a BookWorm placeholder, not a confirmed provider.
  - The existing BookWorm engineering contact is used as a provisional escalation email; confirm the operational owner before signing.
  - The delivery area means the domestic destinations enabled at checkout; confirm the actual country and coverage with the carrier.
  - Confirm local business-day calendars, warehouse time zone, parcel dimensions, and holiday handling with the carrier.
  - The escalation contact, service targets, and remedies are proposed terms and are not binding until agreed in the signed contract.
