> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Flutter — Checkout, buyer orders, seller sales

Source: `modules/Orders/Routes/api.php`, `PlaceOrderRequest.php`, `CheckoutQuoteRequest.php` on `main`. All require `auth:sanctum`, localized order errors. Paths relative to API base path.

| Method | Endpoint | Purpose | Notes |
|---|---|---|---|
| GET, POST | `/checkout/quote` | Checkout quote | `throttle:60,1` |
| POST | `/checkout/` | Place order | `throttle:60,1`; requires `Idempotency-Key` |
| GET | `/orders/` | Buyer orders | Current buyer |
| GET | `/orders/summary` | Buyer order summary | Current buyer |
| GET | `/orders/{ref}` | Buyer order detail | Order ref pattern below |
| GET | `/orders/{ref}/receipt` | Receipt | `throttle:30,1` |
| POST | `/orders/{ref}/pay` | Initiate payment | `throttle:30,1` |
| POST | `/orders/{ref}/confirm-receipt` | Confirm delivery receipt | `throttle:30,1` |
| POST | `/orders/{ref}/cancel` | Request/carry out cancellation | `throttle:30,1` |
| GET | `/sales/` | Seller sales | Current seller |
| GET | `/sales/{ref}` | Seller sale detail | Current seller |
| GET | `/sales/{ref}/receipt` | Seller receipt | `throttle:30,1` |
| GET | `/sales/{ref}/pickup` | Pickup details | Current seller |
| POST | `/sales/{ref}/handed-over` | Mark handover | `throttle:30,1` |
| POST | `/sales/{ref}/cancel-request` | Seller cancellation request | `throttle:30,1` |

`{ref}` route constraint: `[A-Za-z]{3}-\d{4,12}`.

## GET/POST `/checkout/quote`

| Field | Type | Required | Validation |
|---|---|---|---|
| `address_id` | integer/null | No | `min:1` |
| `delivery_method` | string/null | No | `max:20` |

Example request body for POST:

```json
{"address_id":12,"delivery_method":"delivery"}
```

`delivery` is an **illustrative string**; allowed business values must be confirmed from the controller/domain. GET sends these as query parameters, subject to the controller implementation.

## POST `/checkout/`

| Field | Type | Required | Validation |
|---|---|---|---|
| `address_id` | integer | Yes | `min:1` |
| `delivery_method` | string | Yes | `max:20` |
| `payment_method` | string/null | No | `max:30` |
| `Idempotency-Key` | header | Yes | Checked before body validation; invalid/missing key produces HTTP 422 on `idempotency_key` per request comment |

Example **shape**:

```http
POST /api/checkout/
Authorization: Bearer <token>
Accept: application/json
Content-Type: application/json
Idempotency-Key: example-unique-checkout-key
```
```json
{"address_id":12,"delivery_method":"delivery","payment_method":"example-method"}
```

Method values are illustrative, **not validated enum values**. The module comments say checkout idempotency uses the order's stored key, returning current order state on repeats rather than replaying a cached first response. Exact success/error response schemas require controller/presenter review.

---

## Source-verified checkout response contracts (2026-11-22)

Reviewed `CheckoutController`, `CheckoutQuoteRequest`, `PlaceOrderRequest` and `Orders/Routes/api.php` on GitLab `main`. These details supersede the earlier statement that the checkout response was not reviewed. Nested objects still require presenter review.

### `GET|POST /api/v1/checkout/quote`

Both methods invoke the **same** `quote()` controller and are throttled at **60 requests/minute**. Authentication: Sanctum. The controller takes validated `address_id` and `delivery_method` (both nullable/optional) and passes `fallback: true` to `CheckoutQuoter`.

| Input | Location | Type | Required | Validation |
|---|---|---|---|---|
| `address_id` | GET query / POST JSON | integer or null | No | `min:1` |
| `delivery_method` | GET query / POST JSON | string or null | No | `max:20` |

**200 response:** `{"data": <CheckoutPresenter::quote(...) result>}`. The exact nested `data` contract is **not yet verified** here; do not implement assumed totals or delivery options from this section. The quote is computed for the **authenticated user's cart**, not an arbitrary cart ID.

### `POST /api/v1/checkout`

| Input | Location | Type | Required | Validation / behavior |
|---|---|---|---|---|
| `Authorization` | header | bearer token | Yes | Sanctum |
| `Idempotency-Key` | header | string | Yes | Trimmed, nonempty, max **100 bytes**; otherwise **422** with `idempotency_key` validation field |
| `address_id` | JSON | integer | Yes | `min:1` |
| `delivery_method` | JSON | string | Yes | `max:20`; permitted domain values not verified |
| `payment_method` | JSON | string or null | No | `max:30`; when present and hold is live, starts payment in same call |

**Top-level success envelope** (exact keys from controller; nested `order` and `payment` must be checked against their presenters):

| `data` field | Type | Meaning |
|---|---|---|
| `order` | object | Current buyer order detail, not a cached initial snapshot |
| `payment` | object or null | Started payment result; null if no payment started |
| `payment_error` | object or null | `{code: string, message: string}` when optional payment start throws a business exception |
| `replayed` | boolean | Whether checkout idempotency key matched an existing placement |
| `next` | object | `{screen:"gateway"}` when payment started; otherwise `{screen:"payment",pay:{method:"POST",endpoint:"/api/v1/orders/{ref}/pay",requires_idempotency_key:true}}` |

**Status:** **201** for newly placed order, **200** for replay. An optional payment failure **does not roll back** the placed order or its hold: response includes `payment_error` and `next.screen="payment"`. The app should navigate to the payment screen and use the returned `next.pay.endpoint` rather than retrying placement with a new key.

Illustrative **shape only** (references and business values are placeholders):

```json
{
  "data": {
    "order": {"ref": "ORD-0001"},
    "payment": null,
    "payment_error": {"code": "example_error", "message": "Localized payment error"},
    "replayed": false,
    "next": {
      "screen": "payment",
      "pay": {
        "method": "POST",
        "endpoint": "/api/v1/orders/ORD-0001/pay",
        "requires_idempotency_key": true
      }
    }
  }
}
```

**Important:** `example_error` is **not** a verified error code, and the short `order` object above is intentionally incomplete. Business exceptions from the optional payment-start branch are converted into `payment_error`; other validation/business errors can still fail the request. The checkout idempotency key is stored against the order; replays return the order/payment **as they are now**, not a frozen first response.

**Source:** [CheckoutController.php](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Controllers/CheckoutController.php), [CheckoutQuoteRequest.php](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Requests/CheckoutQuoteRequest.php), [PlaceOrderRequest.php](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Requests/PlaceOrderRequest.php).

---

## Source-verified buyer orders contract (2026-11-22)

Source: `modules/Orders/Interfaces/Http/Controllers/OrderController.php`, `Requests/BuyerOrdersRequest.php`, `Requests/PayOrderRequest.php`, `Presenters/OrderViews.php`, `Presenters/PaymentStartPresenter.php` on `main`. Routes are under `/api/v1` (as generated presenter links show). All require Bearer/Sanctum authentication. Buyer detail and mutations are owner-scoped: an order belonging to another buyer returns the same not-found behavior as an absent order. Order refs match `[A-Za-z]{3}-\d{4,12}` at routing.

### GET `/api/v1/orders` — buyer list

| Query | Type | Required | Rule/default |
|---|---|---|---|
| `tab` | `all \| current \| past` | No | Default `all` |
| `per_page` | integer | No | `1..50`; default `20` |
| `page` | integer | No | Laravel paginator page |

Response **is not wrapped in one `data` object**: `data` is an array of buyer cards, with top-level `title`, `tab`, `tabs`, `empty`, `links`, and `meta`. Cards are sorted by `placed_at DESC`, then `id DESC`.

| Response field | Type | Meaning |
|---|---|---|
| `data[]` | object[] | Buyer cards (see below) |
| `title` | string | Localized heading |
| `tab` | string | Selected tab |
| `tabs[]` | `{key:string,label:string,count:int,selected:bool}`[] | All/current/past counters |
| `empty` | `{title:string,body:string}` or null | Empty-state text |
| `links` | `{first:string,last:string,prev:?string,next:?string}` | Pagination links |
| `meta` | `{current_page:int,from:?int,last_page:int,per_page:int,to:?int,total:int}` | Pagination numbers |

`data[]` card: `ref:string`, `date:string`, `placed_at:string|null`, `status:{value,key,label,tone}`, `group:"current"|"past"`, `thumbnails:[{product_id,image_url,alt}]` (up to 3), `pieces:int`, `pieces_label:string`, `seller:{id,display_name}`, `summary_line:string`, `note:string|null`, `total` (formatted monetary value), `open_label:string`.

Example (illustrative values, grounded keys):

```json
{
  "data": [{"ref":"ORD-0001","date":"2026-11-22","placed_at":"2026-11-22T10:00:00+00:00","status":{"value":"paid","key":"paid","label":"Paid","tone":"attention"},"group":"current","thumbnails":[],"pieces":1,"pieces_label":"1","seller":{"id":12,"display_name":"Seller"},"summary_line":"1 item","note":null,"total":"100.00","open_label":"View"}],
  "title":"My orders","tab":"all","tabs":[{"key":"all","label":"All","count":1,"selected":true},{"key":"current","label":"Current","count":1,"selected":false},{"key":"past","label":"Past","count":0,"selected":false}],
  "empty":null,"links":{"first":"https://example.test/api/v1/orders?page=1","last":"https://example.test/api/v1/orders?page=1","prev":null,"next":null},"meta":{"current_page":1,"from":1,"last_page":1,"per_page":20,"to":1,"total":1}
}
```

### GET `/api/v1/orders/{ref}` — buyer detail

No body. Returns `ApiResponse::ok(OrderViews::buyerDetail(...))`, i.e. `data` with these top-level fields:

| Field | Type | Notes |
|---|---|---|
| `ref`, `title`, `date`, `placed_at` | string / nullable date | Order identity and localized title |
| `status` | `{value,key,label,tone}` | `value` is actual backend status; displayed key can differ during dispute return |
| `status_card` | object | Localized state explanation |
| `auto_complete`, `dispute`, `refund` | object or null | Optional workflows |
| `timeline_title`, `timeline` | string, array | Buyer progress |
| `seller` | `{id,display_name,line}` | Seller summary |
| `items_title`, `items` | string, array | Order item snapshot |
| `delivery`, `totals` | object | Delivery and pricing snapshots |
| `payment` | object | Payment status, attempt, hold and pay action |
| `payment_screen`, `success`, `receipt` | object or null | State-specific UI content |
| `chat` | `{available:bool,label:string,aria_label:string}` | Chat state |
| `actions` | array | Server-provided actionable UI definitions |
| `can` | object | Server-provided action permissions |

`payment` fields: `status`, `status_label`, `failure`, `failure_block`, `method`, `method_label`, `attempt_id`, `latest_attempt_id`, `latest_attempt_status`, `paid_at`, `paid_at_label`, `can_pay:bool`, `hold_expires_at`, `hold_seconds_left`, `pay` (nullable `{method:"POST",endpoint,requires_idempotency_key:true}`). If `payment.status == failed`, `failure_block` contains `code,title,reason,causes_title,causes,nothing_charged`. **Do not infer that a charge failed merely from a timeout**; poll the latest attempt if provided. `receipt` is null before payment.

### POST `/api/v1/orders/{ref}/pay` — start or retry payment

Requires `Idempotency-Key` header (nonempty after trim, maximum 100 bytes; invalid/missing yields validation error under `idempotency_key`). Route throttled at 30/min.

| Body | Type | Required | Validation |
|---|---|---|---|
| `payment_method` | string | Yes | Max 30 characters |
| `return_url` | URL string or null | No | Valid URL, max 500 characters |

HTTP `201` for a newly started attempt; HTTP `200` for replay. Response `data` contains the payment-start fields **plus** `order` (full buyer detail):

| Field | Type | Description |
|---|---|---|
| `order_ref` | string | Order reference |
| `attempt_id` | identifier | Payment attempt ID (use returned type) |
| `status`, `method`, `method_label`, `driver` | string | Payment status and method |
| `amount` | object | Money shape from `OrderTexts::money` |
| `gateway_ref` | string or null | Provider reference |
| `replayed` | boolean | Whether payment start was replayed |
| `next_action` | object or null | `{type:"redirect"|"sdk",driver,gateway_ref,client_secret,redirect_url}` when pending and actionable |
| `poll` | `{method:"GET",endpoint:string}` | `/api/v1/payments/attempts/{attempt_id}` |
| `order_link` | `{method:"GET",endpoint:string}` | Buyer order details |
| `order` | object | Updated buyer detail |

If `next_action` is null, do **not** force-open a gateway. Follow returned `poll` and order status. Never use a fresh idempotency key to blindly retry an uncertain payment without first checking the attempt.

### POST `/api/v1/orders/{ref}/confirm-receipt` — buyer confirmation

No request body is read by the controller. Route throttled 30/min. Buyer must own the order. Permitted when the order is in a confirmable delivery/handover state. Response HTTP `200`, `data`:

| Field | Type | Notes |
|---|---|---|
| `changed` | boolean | `false` for an idempotent repeat |
| `message` | string or null | Localized toast if changed |
| `order` | object | Refreshed `OrderViews::buyerDetail` |

Domain failures documented in controller comments: HTTP `409` `order_not_confirmable` / `order_disputed`. Do not display a second success transition when `changed=false`.

### POST `/api/v1/orders/{ref}/cancel` — buyer cancellation

No request body is read by the controller. Route throttled 30/min. Buyer can cancel only before shipping when policy permits. HTTP `200` response is the same `{changed,message,order}` shape as confirmation. Repeat returns `changed:false`. Controller documents HTTP `409` `order_cancel_disabled` / `order_cancel_after_shipping`. On successful cancellation, stock is restored and refund recorded to the wallet; localized message distinguishes a refund still settling. Do not calculate refund availability client-side.

### GET `/api/v1/orders/summary` — account cards

No query/body validated by the controller. Returns `data.buy` and `data.sell`:

| Field | Type | Notes |
|---|---|---|
| `buy.orders_count`, `buy.current_count` | integer | Buyer order counts |
| `buy.orders_row_value` | string | Localized account row |
| `buy.pending_payment` | object or null | `{ref,label,hold_expires_at,pay:{method,endpoint}}` |
| `buy.pending_confirmation` | object or null | Ref, badge, status, title, sub, auto-complete, image, endpoints, actions, `can` |
| `sell.active_count` | integer | Active incoming sales |
| `sell.incoming_row_value` | string or null | Localized seller row |
| `sell.latest_incoming` | object or null | Ref, badge, image, title, sub, action label and endpoint |

**Flutter integration:** Treat all nullable blocks as optional. Render the actions and `can` flags supplied by the backend, rather than reconstructing cancellation/dispute/confirmation rules from status labels. For payment, poll the returned payment-attempt endpoint and use `payment.can_pay` and `payment.pay`.

**Verification boundary:** These contracts are static source-reviewed, not live-tested. Monetary formatting, localized labels, all nested `items/delivery/totals` structures, and exact error envelope require separate presenter/error-middleware review and runtime tests. The JSON example above is illustrative and not a captured API response.


## Seller Sales and receipts — source-reviewed contracts

Source: `modules/Orders/Routes/api.php`, `Interfaces/Http/Controllers/SalesController.php`, `ReceiptController.php`, `Requests/SalesRequest.php`, `SellerCancelRequest.php`, `ReceiptRequest.php`, and `Domain/Cancellation/SellerCancelReason.php` on GitLab `main`. All endpoints use `/api/v1`, `auth:sanctum`, and localized order errors. Order `{ref}` matches `[A-Za-z]{3}-\d{4,12}`. Seller ownership and paid-sale visibility are enforced; unauthorized/unknown orders return the same not-found behavior.

| Method | Endpoint | Request / validation | Successful response | Notes |
|---|---|---|---|---|
| GET | `/sales` | `tab?: current\|past` (default `current`), `per_page?: integer 1..50` (default 20), `page?: integer` (paginator) | `200` JSON list envelope described below | Only the signed-in seller's paid, visible orders; newest `paid_at` first |
| GET | `/sales/{ref}` | Path `ref` | `200` `{data: SellerOrderDetail}` | Detail assembled by `OrderViews::sellerDetail`; not a buyer checkout |
| GET | `/sales/{ref}/pickup` | Path `ref` | `200` `{data:{ref,method,pickup,status}}` | Pickup information for courier collection; `pickup` comes from `FulfilmentViews` |
| POST | `/sales/{ref}/handed-over` | Path `ref`; no body validated by controller | `200` `{data:{changed,message,order}}` | Direct hand-over moves toward buyer confirmation; retry returns `changed:false`; invalid states can return 409 |
| POST | `/sales/{ref}/cancel-request` | JSON `reason` required enum, `note?` string max 500, **required when `reason=other`** | `201` on newly created request, `200` on idempotent pending repeat; `{data:{changed,message,request_ref,order}}` | Request pauses shipping pending admin decision; cannot request after shipping |
| GET | `/sales/{ref}/receipt` | `locale?` enabled locale; `download?` boolean | `200 application/pdf` bytes | Seller's copy excludes buyer private information; paid orders only |
| GET | `/orders/{ref}/receipt` | Same receipt query | `200 application/pdf` bytes | Buyer's own order only; paid orders only |
| GET | `/admin/orders/{ref}/receipt` | Same receipt query; additionally `can:orders.view` | `200 application/pdf` bytes | Dashboard admin copy; **not a Flutter seller endpoint** |

### Seller cancellation request fields

| Field | Type | Required | Constraints |
|---|---|---|---|
| `reason` | enum string | Yes | `item_unavailable`, `item_damaged`, `cannot_deliver_in_time`, `other` |
| `note` | string or null | Conditional | Max 500 characters; required if `reason=other` |

Illustrative request:

```http
POST /api/v1/sales/ORD-0001234/cancel-request
Authorization: Bearer <token>
Content-Type: application/json

{"reason":"other","note":"Cannot fulfil this sale"}
```

Response shape, with example values only (not a captured response):

```json
{
  "data": {
    "changed": true,
    "message": "<localized message>",
    "request_ref": "<generated request reference>",
    "order": {"ref": "ORD-0001234"}
  }
}
```

`order` above is **abbreviated**: the real object is the complete `OrderViews::sellerDetail` result. For `handed-over`, `message` is `null` on a no-change retry. For `cancel-request`, `message` is also `null` on repeat. A decided request cannot be reopened; the controller documents `409 cancel_request_already_decided`, `cancel_request_disabled`, and `cancel_request_after_shipping` cases.

### GET `/sales` response contract

| Top-level field | Type | Meaning |
|---|---|---|
| `data` | array of `SellerOrderCard` | Each item is `OrderViews::sellerCard` |
| `title` | string | Localized list title |
| `tab` | `current` or `past` | Selected tab |
| `tabs` | array of objects | `{key,label,count,selected}` for current/past |
| `pending_note` | string | Localized note |
| `empty` | object or null | `{body}` if selected tab has zero results |
| `links` | object | `{first,last,prev,next}`; `prev/next` nullable |
| `meta` | object | `{current_page,from,last_page,per_page,to,total}`; `from/to` nullable |

The seller detail, cards and pickup subobjects are produced by presenters; their exact nested field-by-field schema requires a separate presenter pass. Do not assume the abbreviated sample is exhaustive.

### PDF receipt transport contract

Receipts are **binary PDF responses**, not JSON. A paid receipt responds with these headers:

| Header | Value |
|---|---|
| `Content-Type` | `application/pdf` |
| `Content-Disposition` | `inline; filename="..."` by default; `attachment; filename="..."` when `download=1` |
| `Content-Language` | Actual receipt locale |
| `Cache-Control` | `private, no-store` |
| `X-Receipt-Number` | Receipt/order reference |

`locale` must be one of the platform's enabled languages; without it, the current request language applies. `download` is a boolean query parameter. Unpaid receipts fail with `409 receipt_not_available`. Flutter should handle the response as PDF bytes, respect disposition for preview/save, and avoid decoding it as JSON. These PDF routes have a `30/min` throttle on the buyer and seller endpoints.

**Source-review status:** Routes, controller-level validation, ownership, status codes and top-level response structures reviewed. Not yet live-tested; nested seller presenter fields, PDF rendering and full localized error envelope still require verification.

## Presenter-level contract: seller cards and details (verified against `OrderViews.php`)

The following field names are taken from `OrderViews::sellerCard` and `OrderViews::sellerDetail`, rather than inferred from screen mockups. For `GET /api/v1/sales`, each `data[]` entry has the card shape below. For `GET /api/v1/sales/{ref}`, these are fields inside the standard `ApiResponse::ok` data payload.

### Seller list card: `data[]`

| JSON path | Type | Meaning / nullability |
|---|---|---|
| `ref` | string | Order reference |
| `date` | string or null | Localized display date |
| `paid_at` | ISO date-time or null | Payment timestamp |
| `buyer.first_name` | string | Buyer's first name only |
| `buyer.line` | string | Localized buyer display line |
| `status` | object | `{value,key,label,tone}` |
| `group` | `current` or `past` | Tab grouping |
| `item.product_id` | integer or null | First product |
| `item.image_url` | string or null | First product cover |
| `item.alt` | string or null | First product name |
| `item.title` | string | First product title, with additional-item count where applicable |
| `pieces` | integer | Total pieces |
| `method` | string | Delivery method (`courier` or `direct` in current flow) |
| `method_label` | string | Localized short label |
| `items_total` | string | Decimal money amount |
| `next_text` | string or null | Localized next-step message |
| `net` | string | Seller net decimal amount |
| `net_line` | string | Localized seller net message |
| `open_label` | string | Localized open-order action |

### Seller detail: `data`

| JSON path | Type | Notes |
|---|---|---|
| `ref`, `title` | string | Order reference |
| `status` | object | `{value,key,label,tone}`; `value` is the underlying status |
| `status_card` | object | `{title:string,sub:string,tone:string,notice:string|null}` |
| `timeline_title` | string | Localized heading |
| `timeline[]` | array of objects | Each `{key,label,state,time,at}`; `time`/`at` nullable |
| `buyer.first_name` | string | No full buyer identity exposed here |
| `items_title` | string | Localized heading |
| `items[]` | array of objects | Fields detailed below |
| `delivery` | object | `{title,method,method_label,place_line}`; `place_line` nullable |
| `earnings` | object | Fields detailed below |
| `pickup` | object or null | Generated by `FulfilmentViews::pickup` |
| `cancel_request` | object or null | Generated by `FulfilmentViews::cancelRequest` |
| `auto_complete` | object or null | Generated by `FulfilmentViews::autoComplete` |
| `dispute` | object or null | `{ref:string}` when linked |
| `chat` | object | `{available:boolean,label:string}` |
| `receipt` | object or null | Generated by `ReceiptViews::link`; only available for eligible paid orders |
| `actions` | array | Generated by `FulfilmentViews::sellerActions`; render server-provided actions |
| `can` | object | Generated by `FulfilmentViews::sellerActions`; use as action gating |

**`items[]` object:**

| Field | Type | Meaning |
|---|---|---|
| `product_id` | integer | Product ID |
| `name` | string | Product snapshot name |
| `cover_image_url` | string or null | Product image |
| `alt` | string | Image alt text |
| `size` | string or null | Product size |
| `condition` | string | Localized condition |
| `meta_line` | string | Localized item context; first row includes buyer first name |
| `price` | string | Decimal amount |

**`earnings` object:**

| Field | Type | Meaning |
|---|---|---|
| `lines[]` | array | Item-price, negative commission, seller-net; optional negative return charge |
| `lines[].key` | string | `item_price`, `commission`, `seller_net`, optional `return_charge` |
| `lines[].label` | string | Localized text |
| `lines[].amount` | money object | Money presenter object, not a raw numeric field |
| `commission_rate` | number | Percentage from stored order terms |
| `note` | string | Localized earnings note |
| `status` | string | `pending`, `available`, or `cancelled` |
| `status_label` | string | Localized earnings state |

The seller earnings status is derived from order state: completed → `available`; cancelled/refunded/awaiting return → `cancelled`; other states → `pending`. Do not release earnings or infer settlement client-side. The nested `pickup`, `cancel_request`, `auto_complete`, `receipt`, `actions`, and `can` contracts are owned by separate presenters and need their own full field-level pass; no guessed subfields are included here.

**Sources:** [`OrderViews.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Presenters/OrderViews.php), [`SalesController.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Controllers/SalesController.php). Static source review, not a runtime response capture.

## Fulfilment nested contracts — source-reviewed presenter pass

These nested blocks are returned inside buyer/seller order details, or the admin fulfilment detail. Their presence is conditional; **do not fabricate a placeholder object when the API returns `null`**.

### `auto_complete` — `FulfilmentViews::autoComplete`

| JSON path | Type | Meaning |
|---|---|---|
| `auto_complete` | object or `null` | `null` unless `auto_complete_at` exists and status is `arrived` or `awaiting_confirmation` |
| `auto_complete.at` | ISO timestamp or `null` | Stored deadline |
| `auto_complete.seconds_left` | integer | Nonnegative remaining seconds at response time |
| `auto_complete.hours_left` | integer | `ceil(seconds_left / 3600)` |
| `auto_complete.label` | string | Localized long countdown label |
| `auto_complete.short_label` | string | Localized short countdown label |

**Client:** treat the server deadline as authoritative; a locally displayed ticking countdown is only presentation. Zero seconds does not authorize a client-side completion transition.

### `timeline[]` — buyer/seller

| JSON path | Type | Meaning |
|---|---|---|
| `timeline` | array of objects | Ordered progress steps; buyer pending-payment returns all `todo`, cancelled-unpaid returns `[]` |
| `timeline[].key` | string | Step identifier, e.g. `paid`, `preparing`, `in_delivery`, `arrived`, `completed`, `handover`, `handed`, `disputed`, `returning`, `cancelled`, `refunded` depending on delivery method/outcome |
| `timeline[].label` | string | Localized step title |
| `timeline[].state` | string | `done`, `now`, `todo` |
| `timeline[].time` | string or `null` | Localized time or next-step explanatory text |
| `timeline[].at` | ISO timestamp or `null` | Event timestamp, when available |

Courier and direct hand-over use different step sequences. Disputes, failed delivery and returns alter the timeline; **render the returned array instead of constructing a fixed five-step UI**.

### `delivery.proof` / dashboard `delivery.proofs`

| JSON path | Type | Meaning |
|---|---|---|
| `delivery.proof` | object or `null` | Buyer proof block; `null` when no proofs or no arrival timestamp |
| `delivery.proof.title` | string | Localized heading |
| `delivery.proof.arrived_at` | ISO timestamp or `null` | Arrival time |
| `delivery.proof.arrived_label` | string or `null` | Localized arrival label |
| `delivery.proof.photos[]` | array | Proof photos |
| `delivery.proof.photos[].url` | string or `null` | Signed media URL for `med_` references, or original carrier URL |
| `delivery.proof.photos[].alt` | string | Localized image alternative text |
| `delivery.proofs[]` | array | Admin proof list (different shape) |
| `delivery.proofs[].reference` | string | Original media reference / carrier URL |
| `delivery.proofs[].url` | string or `null` | Resolved image URL |

### `refund` — buyer-visible breakdown

| JSON path | Type | Meaning |
|---|---|---|
| `refund` | object or `null` | Only present when a refund breakdown was stored |
| `refund.title` | string | Localized heading |
| `refund.case` | string | Refund-case key |
| `refund.paid` | object | `{label, amount}` |
| `refund.lines[]` | array | Nonzero returned components; each `{key, label, amount}` |
| `refund.kept[]` | array | Nonzero retained/charged components; each `{key, label, amount}` |
| `refund.total` | object | `{label, amount}` buyer refund total |
| `refund.destination` | string | Literal `wallet` |
| `refund.note` | string | Localized note |
| `refund.return_shipping` | object or `null` | `{payer, cost, label}` when applicable |
| `refund.refunded_at` | ISO timestamp or `null` | Derived from cancellation timestamp |

The `amount` fields above are **money objects**, not floating-point numbers. `lines` and `kept` omit zero-amount entries; don't require every possible fee row.

### Seller `actions[]` and `can`

| JSON path | Type | Meaning |
|---|---|---|
| `actions[]` | array of objects | Server-selected available UI actions |
| `actions[].key` | string | `chat`, `handed_over`, `cancel_request`, `rate`, or a dispute action |
| `actions[].label` | string | Localized label |
| `actions[].style` | string | UI styling hint |
| `actions[].method` | string or `null` | `GET`, `POST`, or `null` for local navigation |
| `actions[].endpoint` | string or `null` | API URL when supplied |
| `actions[].sheet` | object or `null` | Server-provided confirmation content |
| `actions[].screen` | string (conditional) | Navigation hint such as `chat` or `rate` |
| `actions[].read_only` | boolean (conditional) | Chat read-only state |
| `can.handed_over` | boolean | Seller may mark direct hand-over |
| `can.cancel_request` | boolean | Seller may request cancellation |
| `can.chat` | boolean | Chat currently writable |
| `can.rate` | boolean | Order completed |

`cancel_request` action `sheet.reasons[]` contains `{value,label,note_required,body}`; `other` has `note_required: true`. The sheet also supplies `pick_title`, `body_template`, `title`, `body`, `confirm`, `dismiss`, `toast`. `handed_over` sheet supplies `title`, `body`, `confirm`, `dismiss`, `toast`. Use server-returned actions and enforce permissions again on submit; a displayed action is not a guarantee that order state has not changed.

### `cancel_request` — seller detail

| JSON path | Type | Meaning |
|---|---|---|
| `cancel_request` | object or `null` | No cancellation request → `null` |
| `cancel_request.ref` | string | Request reference |
| `cancel_request.status` | string | Current request status |
| `cancel_request.status_label` | string | Localized status |
| `cancel_request.reason` | string | Machine-readable reason |
| `cancel_request.reason_label` | string | Localized reason |
| `cancel_request.note` | string or `null` | Seller note |
| `cancel_request.requested_at` | ISO timestamp or `null` | Creation time |
| `cancel_request.decided_at` | ISO timestamp or `null` | Decision time |
| `cancel_request.message` | string | Localized status message |

### Receipt link vs PDF response

`receipt` in an order detail is a **link descriptor**, not a PDF payload. If available it has `available: true`, `label`, `endpoint`, `filename` (`receipt-{ref}.pdf`), and `mime: application/pdf`; otherwise `null`. Fetch the `endpoint` as **binary PDF**, not JSON. Buyer, seller and admin receipts have different audience-specific contents; the seller receipt intentionally excludes the buyer's address and payment method. `GET .../receipt` may fail with `409 receipt_not_available` or `409 receipt_payment_rejected` based on the stored payment/cancellation state.

**Source:** [`FulfilmentViews.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Presenters/FulfilmentViews.php), [`ReceiptViews.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Presenters/ReceiptViews.php). Static source inspection; live response verification remains outstanding.

## Orders business errors — verified codes and client recovery (source review)

All Orders routes use `LocalizeOrderErrors`. For Orders `BusinessLogicException` responses, the middleware edits `error.message` to the request locale and may attach `error.details`; it does **not** guarantee a `details` property on every failure. Treat the sample below as illustrative, not a captured HTTP response.

```json
{
  "error": {
    "code": "checkout_hold_expired",
    "message": "Localized error text",
    "details": {"order_ref": "OUT-1234", "next": "cart"}
  }
}
```

| Code | HTTP | Where / what it means | Verified `error.details` | Flutter recovery |
|---|---:|---|---|---|
| `order_not_found` | 404 | Order missing **or belongs to another user** | Not attached by this middleware | Show not found; never expose existence of another user's order |
| `order_not_payable` | 409 | Pay attempted in invalid status | `order_ref`, `status` | Refresh order and disable Pay |
| `order_already_paid` | 409 | Payment already recorded | `order_ref` | Refresh detail instead of creating another payment |
| `checkout_hold_expired` | 409 | Reserved items no longer held | `order_ref`, `next: "cart"` | Return to cart and re-quote |
| `checkout_payment_in_progress` | 409 | Previous payment still processing | `order_ref` | Poll/reload payment state; avoid duplicate attempts |
| `checkout_key_conflict` | 409 | Idempotency key reused for different order data | `order_ref` | Do not silently retry with a new key; reconcile user action |
| `order_invalid_transition` | 409 | Disallowed status transition | `order_ref: null` (exception provides `from`/`to`, not `order`) | Reload order state |
| `order_not_direct` / `order_not_courier` | 409 | Wrong delivery method for action | `order_ref` | Hide invalid action after refresh |
| `order_not_handable` | 409 | Seller/admin hand-over not currently allowed | `order_ref`, `status` | Refresh detail/actions |
| `order_not_confirmable` / `order_disputed` | 409 | Buyer confirmation unavailable | `order_ref`, `status` | Refresh; navigate to dispute when applicable |
| `order_cancel_disabled` / `order_cancel_after_shipping` | 409 | Buyer cancellation disabled or too late | `order_ref`; `status` on after-shipping | Refresh `actions` / `can` |
| `cancel_request_disabled` / `cancel_request_after_shipping` | 409 | Seller cancellation request unavailable | `order_ref`; `status` on after-shipping | Refresh seller detail |
| `cancel_request_already_decided` / `cancel_request_not_pending` | 409 | Request already decided or not pending | `order_ref` | Refresh cancellation request |
| `order_status_changed` | 409 | Order changed during dispute flow | `order_ref`, `status` | Reload eligibility and detail |
| `receipt_not_available` / `receipt_payment_rejected` | 409 | PDF receipt unavailable or payment rejected/refunded | `order_ref`, `status` | Hide receipt action and refresh |
| `order_not_in_delivery` / `order_not_shippable` | 409 | Delivery milestone not allowed | `order_ref`, `status` | Refresh status before retry |
| `order_not_awaiting_return` | 409 | Return verification not allowed | `order_ref`, `status` | Refresh delivery state |

**Additional typed detail cases:** `cart_has_unavailable_items` and `checkout_pieces_unavailable` supply `product_ids` and `next: "cart"`; `cart_empty` supplies `next: "cart"`; `delivery_method_unavailable` supplies `method`, `reason`, `reason_label`; `unknown_delivery_method` supplies an `error.details.delivery_method` validation-message array; `address_not_found` / `address_required` supply `error.details.address_id` message arrays; `DeliveryProofInvalid` supplies `proofs` message array and `max` integer. These details come from the middleware; the complete error code/status inventory for every checkout exception remains a separate verification task.

**Implementation:** use `error.code` for control flow and localized `error.message` for display. Do not parse text messages, assume every 409 is retryable, or treat `details` as a fixed schema. Validation errors and authorization errors can use separate framework paths; their exact HTTP serialization is not asserted here.

**Source:** [`LocalizeOrderErrors.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Interfaces/Http/Middleware/LocalizeOrderErrors.php), [`OrderStateConflict.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Domain/Exception/OrderStateConflict.php), [`OrderNotFound.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Orders/Domain/Exception/OrderNotFound.php). Static code review; illustrative JSON, not a live API capture.

---

## Presenter-verified Flutter contracts — 2026-11-22 (supersedes earlier unverified nested-response notes)

Sources: `modules/Orders/Interfaces/Http/Controllers/CheckoutController.php`, `modules/Orders/Interfaces/Http/Presenters/{CheckoutPresenter,OrderViews,PaymentStartPresenter}.php` on GitLab `main`. These are source-derived contracts, **not Staging test results**.

### Checkout quote — exact `data` field inventory

`GET|POST /api/v1/checkout/quote` returns `ApiResponse::ok(CheckoutPresenter::quote(...))`, i.e. the JSON envelope has a `data` object with the following fields:

| `data` key | Type / nested keys | Client implementation |
|---|---|---|
| `title` | string | Localized screen heading. |
| `step` | `{current:number,total:number,label:string}` | Checkout step 1 of 2. |
| `ready` | boolean | Whether order placement can proceed. |
| `blockers` | `[{code:string,message:string}]` | Display server-provided blockers. |
| `address_title`, `address_sheet_title`, `change_address_label`, `add_address_label` | string | Localized copy. |
| `address` | object or null | `{id,label,kind,line,detail,city:{id,name},is_default}`. |
| `address_missing` | string or null | Display if no selected address. |
| `address_options` | array | Each address plus `selected`, `courier_available`, `direct_available`, `note`, `select:{method,endpoint,query}`. |
| `delivery` | object | `{title,selected_method,method_switched,courier_notice,methods}`. |
| `delivery.methods[]` | object | `{method,label,short_label,description,available,selected,show_fee,fee,is_free,fee_text,unavailable_reason,unavailable_message}`. |
| `items` | object | `{title,count,count_label,seller,summary_line,lines}`; `lines[]` has `product_id,name,cover_image_url,size,condition,meta_line,price,old_price,available,availability`. |
| `totals` | object | `{pieces,items_label,lines,total,tax}`; see money/tax notes below. |
| `cart_summary` | object | `{pieces,items_label,items_total,service_fee_label,service_fee,delivery_label,delivery_note,total_label,total,vat_note,button}`. |
| `hold_note` | string | Localized checkout-hold message. |
| `hold_minutes` | integer | Server policy; do not hard-code. |
| `pay_button` | object | `{label,amount,enabled}`. |
| `place` | object | `{method:'POST',endpoint:'/api/v1/checkout',body:{address_id,delivery_method},requires_idempotency_key:true}`. |
| `pending_order` | object or null | `{ref,message,pay:{method:'POST',endpoint}}`; resume existing payment when present. |

**Money and totals:** `totals.lines[]` contains `key`, `label`, `amount`, `display` (VAT line additionally `informational:true`); `totals.total` has `label`, `amount`, `note`; `totals.tax` has `enabled`, `rate`, `prices_include_vat`, `amount`, `included_amount`. A `direct` handover **omits** the delivery fee row, while a zero-fee courier can show a free-delivery row. The VAT row is informational, not an extra charge to add on the client. Monetary object serialization comes from `OrderTexts::money` and should not be independently recomputed in Flutter.

**Delivery method:** source code explicitly distinguishes `direct` and `courier`. Render available options from `delivery.methods`, not a hard-coded list. If the requested method is unavailable, `delivery.method_switched` describes the server-selected fallback.

### Place order — response status and nested payload

`POST /api/v1/checkout` returns **201 for a newly placed order** and **200 for a replay** with the existing checkout key. The envelope is `data:{order,payment,payment_error,replayed,next}`. This corrects any earlier example that implied 200 for all successful placements.

- `order`: the full buyer detail from `OrderViews::buyerDetail`, with `ref,title,date,placed_at,status,status_card,auto_complete,dispute,refund,timeline_title,timeline,seller,items_title,items,delivery,totals,payment,payment_screen,success,receipt,chat,actions,can`.
- `payment`: null unless optional `payment_method` starts a payment successfully. When present, `PaymentStartPresenter::started` emits `{order_ref,attempt_id,status,amount,method,method_label,driver,gateway_ref,replayed,next_action,poll,order_link}`. `next_action` is null or `{type,driver,gateway_ref,client_secret,redirect_url}`. `poll` and `order_link` provide GET endpoints.
- `payment_error`: null or `{code,message}` if the optional payment start failed after the order was placed. **Do not treat this as a failed checkout**; the order and hold remain, and `next.pay` points to the retry endpoint.
- `replayed`: boolean. The response reflects **current order state**, not a frozen first response.
- `next`: `{screen:'gateway'}` if payment started, otherwise `{screen:'payment',pay:{method:'POST',endpoint:'/api/v1/orders/{ref}/pay',requires_idempotency_key:true}}`.

The buyer detail's `payment` object contains `status,status_label,failure,failure_block,method,method_label,attempt_id,latest_attempt_id,latest_attempt_status,paid_at,paid_at_label,can_pay,hold_expires_at,hold_seconds_left,pay`. `receipt` may be null until payment is complete. Use `can`/`actions` for buttons rather than inferring allowed actions from status alone.

### Flutter integration / QA checklist

1. Decode **both 200 and 201** as successful checkout responses; persist the order reference from `data.order.ref`.
2. Supply a stable `Idempotency-Key` for retries of the *same* checkout action, and a new key for a genuinely new action.
3. Render server `blockers`, `ready`, `pay_button.enabled`, method availability and fallback, and do not compute prices or VAT in the app.
4. If `payment_error` is populated, show the localized error but retain the placed order; follow `data.next.pay` to retry.
5. When `payment.next_action` is present, follow `redirect` or `sdk` as specified; use the provided polling endpoint for the outcome.
6. Test address changes, unavailable courier, free courier vs direct handover, expired hold, payment-start failure, duplicate checkout key, and receipt visibility on Staging before sign-off.


## Seller Sales — controller-verified HTTP behavior (2026-11-22)

Source: `modules/Orders/Interfaces/Http/Controllers/SalesController.php`, `ReceiptController.php`, `Requests/SellerCancelRequest.php` on GitLab `main`. These are source contracts, **not** staging test results.

| Method | Endpoint | Input | Successful response | Important behavior |
|---|---|---|---|---|
| GET | `/api/v1/sales` | `tab=current\|past` (default current), `per_page` (default 20; see `SalesRequest` for limits) | JSON with top-level `data[]`, `title`, `tab`, `tabs[]`, `pending_note`, `empty`, `links`, `meta` | Only paid, seller-owned orders. Sorted by `paid_at DESC`, then `id DESC`. |
| GET | `/api/v1/sales/{ref}` | Path `ref` | `data` = `OrderViews::sellerDetail` | Non-owned or unpaid orders appear as 404. |
| GET | `/api/v1/sales/{ref}/pickup` | Path `ref` | `data:{ref,method,pickup,status}` | `pickup` is built by `FulfilmentViews::pickup`. |
| POST | `/api/v1/sales/{ref}/handed-over` | No required JSON body in controller | `data:{changed,message,order}`; HTTP 200 | Direct hand-over only. Repeated valid call returns `changed:false`, `message:null`; invalid transition returns 409 (`order_not_direct` / `order_not_handable`). |
| POST | `/api/v1/sales/{ref}/cancel-request` | `reason` required; `note` conditional | `data:{changed,message,request_ref,order}`; HTTP **201** if newly created, **200** if repeated while pending | After decision returns 409 `cancel_request_already_decided`; disabled/after shipping returns 409 `cancel_request_disabled` / `cancel_request_after_shipping`. |
| GET | `/api/v1/sales/{ref}/receipt` | `locale` / `download` query per `ReceiptRequest` | Binary PDF (HTTP 200), **not JSON** | Only seller's own order; seller PDF omits buyer-private data. Unpaid: 409 `receipt_not_available`. |

### Seller cancellation payload

```json
{"reason":"other","note":"Item damaged before handover"}
```

`reason` must be one of `item_unavailable`, `item_damaged`, `cannot_deliver_in_time`, `other`. `note` is nullable string, maximum 500 characters, **required when `reason=other`**. Do not interpret a 200 replay as a newly created request; use `changed` and `request_ref`.

### Sales list envelope (structure, values illustrative)

```json
{
  "data": [],
  "title": "...",
  "tab": "current",
  "tabs": [{"key":"current","label":"...","count":0,"selected":true},{"key":"past","label":"...","count":0,"selected":false}],
  "pending_note": "...",
  "empty": {"body":"..."},
  "links": {"first":null,"last":null,"prev":null,"next":null},
  "meta": {"current_page":1,"from":null,"last_page":1,"per_page":20,"to":null,"total":0}
}
```

The example is **illustrative**; link URLs and translated strings depend on the environment and locale. Unlike `ApiResponse::ok` detail endpoints, the sales index returns a **top-level paginated envelope** directly.

### Receipt download handling

Buyer `/api/v1/orders/{ref}/receipt` and seller `/api/v1/sales/{ref}/receipt` both return bytes with `Content-Type: application/pdf`, `Content-Disposition: inline` by default or `attachment` when `download` is true, `Content-Language`, `Cache-Control: private, no-store`, and `X-Receipt-Number`. Use a binary HTTP client/stream in Flutter; do not JSON-decode. PDF receipts are order receipts, **not ZATCA tax invoices**. Unauthorized ownership is indistinguishable from missing order (404). Check `ReceiptRequest` for exact accepted locale/download validation.

### Flutter QA cases still requiring Staging

1. Verify current/past tabs, counts, sorting, and empty state with a seller who has both types of orders.
2. Verify seller cannot fetch a different seller's order or an unpaid checkout (404).
3. Verify hand-over's first/repeat transitions and the expected 409 invalid-state codes.
4. Verify cancellation `201` creation vs `200` pending replay, `other` requiring `note`, and 409 after decision/shipping.
5. Verify receipt binary handling, inline/attachment headers, Arabic/English output, privacy redaction, and 409 before payment.
