> **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 — Cart API (source-reviewed contract)

**Source:** `modules/Cart/Routes/api.php`, `CartController.php`, `CartViews.php`, `ProductRequest.php`, `BuyNowRequest.php` on GitLab `main`. Base URL `/api/v1`; examples are **illustrative**, not live captures. All 7 operations require `Authorization: Bearer <token>` and `Accept: application/json`; all work on the **authenticated buyer's own cart** (no cart ID supplied). Writes are throttled at 60/min; POST writes additionally use `Idempotency-Key`/`idempotent` middleware. API success envelopes are `{ "data": ... }` except where explicitly noted. UI labels are localized by the server.

## Reusable response contracts

**Money:** `{ "amount": "120.00", "currency": "SAR" }` (`amount`: decimal string, `currency`: string).

**Cart (`data` for GET /cart; `data.cart` on mutations):**

| Field | Type | Meaning |
|---|---|---|
| `id` | integer/null | Cart ID or null if absent |
| `title` | string | Localized screen title |
| `is_empty` | boolean | Whether count is zero |
| `count`, `available_count`, `unavailable_count`, `max_items` | integer | Counts and configured limit |
| `count_label` | string/null | Localized pieces count |
| `seller` | object/null | Seller summary below |
| `items` | array of CartLine | Cart lines |
| `product_ids` | integer[] | IDs for badge/ticks |
| `summary` | object | Price summary below |
| `note` | string | Localized notice |
| `checkout` | object | Checkout state below |
| `empty` | object | `title`, `body`, `action_label`: localized strings |
| `last_activity_at` | ISO8601 string/null | Last cart activity |

**Seller:** `id` integer, `available` boolean, `label` string, `display_name` string/null, `initial` string/null, `avatar_url` string/null, `rating_avg` decimal string/null, `rating_count` integer, `rating` object/null (external rating contract), `city` `{id:integer,name:string}`/null, `meta_line` string. An unavailable seller has `available=false` and null profile fields.

**CartLine:** `product_id` integer; `name` string; `cover_image_url` string/null (temporary signed URL); `size` string/null; `size_label` string/null; `condition` string/null; `meta_line` string; `price` Money; `old_price` Money/null; `discount_percent` number/null (Catalog-sourced); `available` boolean; `availability` string; `unavailable_reason` string/null; `unavailable_label` string/null; `in_your_checkout` boolean; `in_your_checkout_label` string/null; `price_changed` boolean; `price_changed_label` string/null; `added_price` Money; `remove_label` string; `added_at` ISO8601 string/null; `opens_product` boolean.

**Summary:** `items_total` Money; `items_total_label` string; `service_fee` Money/null; `service_fee_label` string; `delivery` null (not computed until checkout); `delivery_label`, `delivery_note` strings; `total` Money/null; `total_label` string; `vat_note` string/null. **Do not calculate delivery or fees on client.**

**Checkout:** `ready` boolean; `button_label` string; `blockers` array of `{code:string,message:string}`; `can_remove_unavailable` boolean; `remove_unavailable_label` string/null; `amount` Money/null. Exact blocker enum comes from Cart domain and may evolve.

### GET `/cart`
- **Request:** no body/query. **200:** `{ "data": Cart }`.
- **Example response (abridged illustration):**
```json
{"data":{"id":null,"title":"السلة","is_empty":true,"count":0,"count_label":null,"available_count":0,"unavailable_count":0,"max_items":30,"seller":null,"items":[],"product_ids":[],"summary":{"items_total":{"amount":"0.00","currency":"SAR"},"items_total_label":"0 قطع","service_fee":null,"service_fee_label":"رسوم الخدمة","delivery":null,"delivery_label":"التوصيل","delivery_note":"يحسب لاحقاً","total":null,"total_label":"الإجمالي","vat_note":null},"note":"","checkout":{"ready":false,"button_label":"إتمام الطلب","blockers":[{"code":"empty","message":"السلة فارغة"}],"can_remove_unavailable":false,"remove_unavailable_label":null,"amount":null},"empty":{"title":"السلة فارغة","body":"","action_label":"تسوق"},"last_activity_at":null}}
```
Localized text and configured limits in this example are placeholders; fields/types come from `CartViews::cart()`.

### GET `/cart/ids`
- **Request:** no body/query. **200:** `data.product_ids` integer[], `count` integer, `count_label` string/null, `seller_id` integer/null, `labels` object with string keys `add`, `in_cart`, `added`, `go_to_cart`, `in_cart_action` literal `open_cart`.
```json
{"data":{"product_ids":[101,102],"count":2,"count_label":"قطعتان","seller_id":8,"labels":{"add":"أضف للسلة","in_cart":"في السلة","added":"تمت الإضافة","go_to_cart":"الذهاب إلى السلة"},"in_cart_action":"open_cart"}}
```

### POST `/cart/items`
- **Body:** `product_id` **required integer >=1**. Headers: `Idempotency-Key` for safe retries. **201** when added; **200** when already in cart. `data`: `product_id` integer, `changed` boolean, `in_cart=true`, `message` string, `button_label` string, `button_settled_label` string, `button_action="open_cart"`, `cart` Cart.
```http
POST /api/v1/cart/items
Authorization: Bearer <token>
Content-Type: application/json
Idempotency-Key: add-101-001

{"product_id":101}
```
```json
{"data":{"product_id":101,"changed":true,"in_cart":true,"message":"تمت الإضافة","button_label":"تمت الإضافة","button_settled_label":"الذهاب إلى السلة","button_action":"open_cart","cart":{"id":1,"items":[{"product_id":101}],"count":1}}}
```
`cart` above is abbreviated; the real response contains **all Cart fields**. Another seller's product can return **409 `cart_seller_conflict`**, leaving the cart unchanged; present a confirmation UI then call `/cart/replace`.

### POST `/cart/replace`
- **Body:** `product_id` **required integer >=1**. Explicit buyer confirmation to replace another seller's cart. **201** if product added, else **200**.
- **Response data:** `product_id` integer, `changed` boolean, `in_cart=true`, `removed_product_ids` integer[], `message` string, `button_label` string, `button_settled_label` string, `button_action="open_cart"`, `cart` Cart.
```json
{"product_id":202}
```
```json
{"data":{"product_id":202,"changed":true,"in_cart":true,"removed_product_ids":[101],"message":"تم بدء سلة جديدة","button_label":"تمت الإضافة","button_settled_label":"الذهاب إلى السلة","button_action":"open_cart","cart":{"id":1,"count":1}}}
```
`cart` abbreviated.

### POST `/cart/buy-now`
- **Body:** `product_id` **required integer >=1**; `replace_cart` optional boolean (default `false`), indicating consent to clear a different seller's cart.
- **200 data:** `product_id` integer, `changed` boolean, `in_cart=true`, `removed_product_ids` integer[], `ready_for_checkout` boolean, `next` enum `checkout|cart`, `message` null, `cart` Cart.
```json
{"product_id":202,"replace_cart":false}
```
```json
{"data":{"product_id":202,"changed":true,"in_cart":true,"removed_product_ids":[],"ready_for_checkout":true,"next":"checkout","message":null,"cart":{"id":1,"count":1}}}
```
`cart` abbreviated. `ready_for_checkout` depends on backend checkout blockers, not client assumptions.

### DELETE `/cart/items/{productId}`
- **Path:** `productId` **numeric integer**. No request body. **200 data:** `product_id` integer, `changed` boolean, `in_cart=false`, `message` string, `cart` Cart. Repeated delete returns `changed=false`.
```json
{"data":{"product_id":101,"changed":true,"in_cart":false,"message":"تم الحذف","cart":{"id":1,"count":0}}}
```
`cart` abbreviated.

### DELETE `/cart/unavailable`
- **Request:** no body. **200 data:** `changed` boolean, `removed_product_ids` integer[], `message` string, `cart` Cart. Removes all unavailable pieces; repeated call is safe.
```json
{"data":{"changed":true,"removed_product_ids":[101,103],"message":"تم حذف المنتجات غير المتاحة","cart":{"id":1,"count":1}}}
```
`cart` abbreviated.

## Client integration and errors
- Read every mutation's `data.cart` to repaint the cart, header badge, and product ticks immediately; don't issue a second GET unnecessarily.
- **401** unauthenticated; **403/404/409/422/429** may arise depending on permissions, product state, seller conflict, validation, and throttling. Only the **409 seller-conflict behavior** is explicitly confirmed by controller comments; exact localized error envelope requires error middleware/exception mapping review.
- Monetary amounts are strings; use decimal-safe parsing. `Idempotency-Key` should be stable across retries of one user action, unique across different actions.

**Source:** `modules/Cart/Interfaces/Http/{Controllers/CartController.php,Presenters/CartViews.php,Requests/ProductRequest.php,Requests/BuyNowRequest.php}`.

## Verified domain error contracts and actionable Flutter handling

**Source-verified:** `modules/Cart/Interfaces/Http/Middleware/LocalizeCartErrors.php`, `Domain/Exception/{CartRuleViolation,CartSellerConflict,CartProductNotFound}.php`, and `Core/Interfaces/Http/Responses/ApiResponse.php` on `main` (2026-11-22). Unlike the illustrative successful examples above, the following **field names and decision rules** are derived from the actual middleware. Localized text is illustrative and must be rendered from `error.message` / `error.details` at runtime.

### Error envelope

```json
{
  "error": {
    "code": "cart_seller_conflict",
    "message": "Localized server-provided message",
    "request_id": null,
    "details": {}
  }
}
```

`error.request_id` is nullable. `error.details` is conditional: do not assume it exists on every error. Validation failures have the Core validation format (`validation_failed`, HTTP 422, with field-specific `details`).

| HTTP | `error.code` | When | `error.details` | Flutter action |
|---|---|---|---|---|
| 401 | `unauthenticated` | Missing/expired bearer token | Not required | Open sign-in / refresh session |
| 404 | `product_not_found` | Product does not exist or is not buyer-visible | Not required | Remove stale product affordance |
| 409 | `cart_seller_conflict` | Cart belongs to another seller | `current_seller`, `new_seller`, `product_id`, `sheet`, `confirm` | Display server-provided confirmation sheet; execute `confirm` only on explicit consent |
| 422 | `validation_failed` | Invalid input, including `product_id` or `replace_cart` | Field errors | Show field validation |
| 422 | `product_not_available` | Product sold, reserved, unavailable or removed | `reason`, `reason_label` | Display localized reason; refresh cart |
| 422 | `cart_own_product` | Buyer is product owner | Not required | Disable purchase action |
| 422 | `cart_full` | Configured maximum items reached | `max`: integer | Show limit and route to cart |
| 422 | `cart_empty` | Operation requires nonempty cart | Not required | Display empty state |
| 422 | `cart_has_unavailable_items` | Unavailable products block checkout | `product_ids`: integer[] | Offer `DELETE /cart/unavailable` |
| 429 | `too_many_attempts` | Write throttle exceeded (60/min) | May include retry metadata | Back off; do not retry in a tight loop |

**409 example (structure verified, values illustrative):**

```json
{
  "error": {
    "code": "cart_seller_conflict",
    "message": "The cart contains items from another seller",
    "request_id": null,
    "details": {
      "current_seller": {"id": 11, "display_name": "Seller A"},
      "new_seller": {"id": 22, "display_name": "Seller B"},
      "product_id": 202,
      "sheet": {
        "title": "Start a new cart?",
        "body": "Confirm replacing the current cart",
        "confirm_label": "Confirm",
        "cancel_label": "Cancel"
      },
      "confirm": {
        "method": "POST",
        "endpoint": "/api/v1/cart/replace",
        "body": {"product_id": 202}
      }
    }
  }
}
```

**Important distinction:** if the conflict originated from `POST /cart/buy-now`, `details.confirm` instead contains `{"method":"POST","endpoint":"/api/v1/cart/buy-now","body":{"product_id":202,"replace_cart":true}}`. Never blindly send a `/cart/replace` request for a buy-now conflict. Confirmation may discard existing cart items; do not execute automatically.

### Field-by-field request validation

| Endpoint | Input | Type | Required | Verified rule |
|---|---|---|---|---|
| `POST /cart/items` | `product_id` | integer | Yes | `min:1` |
| `POST /cart/replace` | `product_id` | integer | Yes | `min:1` |
| `POST /cart/buy-now` | `product_id` | integer | Yes | `min:1` |
| `POST /cart/buy-now` | `replace_cart` | boolean | No | `sometimes`; absent means `false` |
| `DELETE /cart/items/{productId}` | `productId` (path) | integer | Yes | Numeric route constraint |
| `GET /cart`, `GET /cart/ids`, `DELETE /cart/unavailable` | — | — | — | No request payload |

### Response-state details that must not be recomputed

| Response path | Server behavior | UI implication |
|---|---|---|
| `data.checkout.ready` | True only when `checkoutBlockers()` returns an empty list | Do not infer readiness from item count alone |
| `data.checkout.blockers[]` | Each contains `code` and localized `message` | Display the server-provided message |
| `data.checkout.can_remove_unavailable` | True when unavailable count is positive | Show the cleanup action conditionally |
| `data.summary.total` | Pricing quote excluding delivery; null when no buyable pieces or quote fails | Treat as provisional, not the final checkout total |
| `data.summary.service_fee` | Null when quote missing or fee is not positive | Hide fee line when null |
| `data.items[].price_changed` | Determined from current vs added price | Display `price_changed_label` when true |
| `data.items[].in_your_checkout` | Item already held by buyer's own pending checkout | Show `in_your_checkout_label`; do not interpret as an available new purchase |
| `data.items[].opens_product` | False for removed products or missing product summaries | Disable product detail navigation |
| `data.seller.available` | False if public seller profile is unavailable | Render fallback without assuming name/avatar/rating |
| `data.items[].cover_image_url` | Temporary signed media URL | Do not persist URL as permanent identifier |

### Integration sequence

1. On authenticated app bootstrap call `GET /cart/ids` for header count and product-card states; use `GET /cart` for the full cart screen.
2. On Add, Replace or Buy Now, generate a distinct `Idempotency-Key` per logical action and reuse it for retries of that action only. On success use the returned `data.cart` as the canonical state.
3. On `409 cart_seller_conflict`, show `error.details.sheet`; if confirmed, send the exact `error.details.confirm` method, endpoint and body. Use a **new** idempotency key for the new confirmed action.
4. On unavailable items, render the server-provided reason and offer the explicit cleanup endpoint. After cleanup, repaint from `data.cart`.
5. On `401`, require authentication; never create a guest cart locally and assume it is server-owned.

### Source links

- [Routes](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Cart/Routes/api.php)
- [Controller](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Cart/Interfaces/Http/Controllers/CartController.php)
- [CartViews presenter](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Cart/Interfaces/Http/Presenters/CartViews.php)
- [Localized error middleware](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Cart/Interfaces/Http/Middleware/LocalizeCartErrors.php)
- [Domain rule violations](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Cart/Domain/Exception/CartRuleViolation.php)

**Verification boundary:** contracts were reviewed against repository source, not exercised on Staging. Real push, pricing, checkout and idempotency behavior in a deployed environment require separate integration tests.
