> **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.

# Delivery API — Dashboard (source-reviewed)

**Source of truth:** GitLab `alalmiyalhura/outlet`, `main`, `modules/Delivery/Routes/api.php`; `Interfaces/Http/Controllers/Admin/{DeliveryRateAdminController,DeliverySettingsController,AuditTrail}.php`; `Interfaces/Http/Requests/DeliveryRateRequest.php`; `Interfaces/Http/Presenters/DeliveryPresenter.php`.

**Base path:** `/api/v1/admin/delivery` (confirmed by module tests and route conventions; check deployed route list before runtime sign-off). All 13 endpoints require `Authorization: Bearer <token>` via `auth:sanctum`. For localized messages, supply the app's supported language header. `GET` has no request body. Money amounts are **decimal strings** (e.g. `"25.00"`), not integer cents. Examples below are **illustrative**; their values are not captured from a live environment.

## Shared response types

### `Rate` object — exact presenter keys

| Field | Type | Meaning |
|---|---|---|
| `id`, `city_id` | integer | Rate and city identifiers |
| `city` | object | `{id: integer, name: {locale: string|null}, is_active: boolean}`; enabled locale keys are dynamic |
| `courier_available`, `is_active`, `covered` | boolean | Per-rate switches and effective city coverage |
| `available_at_checkout` | boolean or null | `covered && courier_enabled` when settings supplied |
| `courier_fee` | decimal string | E.g. `"25.00"` |
| `currency` | string | Configured currency |
| `estimated_days` | string or null | Localized estimated-day text resolved for request locale; nullable |
| `created_at`, `updated_at` | ISO-8601 string or null | Timestamps |

Example `Rate` (illustrative):

```json
{"id":7,"city_id":3,"city":{"id":3,"name":{"ar":"مدينة تجريبية","en":"Example City"},"is_active":true},"courier_available":true,"is_active":true,"covered":true,"available_at_checkout":true,"courier_fee":"25.00","currency":"SAR","estimated_days":"2-3 أيام","created_at":"2026-11-01T10:00:00+00:00","updated_at":"2026-11-02T10:00:00+00:00"}
```

All ordinary single-object actions use `{"data": <payload>}`; creation is HTTP **201**, updates/actions **200**. **Exceptions:** rate list uses a Laravel JSON resource collection with paginator `data`, `links`, `meta`; audit histories use `data` and a smaller `meta` object. Missing rate IDs throw `DeliveryRateNotFound`; precise error status/envelope depends on exception mapping and is not verified here.

## Rate list and detail — `delivery.rates.view`

### 1. `GET /api/v1/admin/delivery/rates`

**Query validation:** `per_page` integer 1–100, default 25. Filters: `filter[courier_available]`, `filter[is_active]`, `filter[covered]`, `filter[city_active]` booleans; `filter[city_id]` exact ID(s) supported by Spatie exact filter; `filter[fee_min]` and `filter[fee_max]` decimal strings matching `^\d{1,6}(\.\d{1,2})?$`; `filter[created_from]`, `[created_to]`, `[updated_from]`, `[updated_to]` dates; `filter[q]` city-name search in available locales, string max 100. Allowed `sort`: `city_name`, `courier_fee`, `city_id`, `created_at`, `updated_at`, `id`; prefix `-` for descending. Default `city_id` ascending.

Example: `GET /api/v1/admin/delivery/rates?filter[covered]=true&filter[fee_min]=10.00&sort=-courier_fee&per_page=25`.

**200 response:** `data: Rate[]`, `links: {first,last,prev,next}`, `meta` Laravel pagination metadata (including `current_page`, `last_page`, `per_page`, `total`, `links` depending on resource serialization). Do **not** wrap the entire paginator in another `data` object.

### 2. `GET /api/v1/admin/delivery/rates/{id}`

`id` positive numeric path ID. **200:** `{"data": {...Rate, "recent_changes": Change[]}}`, latest **5** changes. `Change` shape is specified in history below.

### 3. `GET /api/v1/admin/delivery/rates/{id}/history`

`id` numeric; `per_page` integer 1–100, default 25. **200:**

```json
{"data":[{"id":10,"event":"updated","changes":[{"field":"courier_fee","old":"20.00","new":"25.00"}],"actor":{"id":2,"name":"Example Admin"},"ip_address":"127.0.0.1","at":"2026-11-02T10:00:00+00:00"}],"meta":{"current_page":1,"last_page":1,"per_page":25,"total":1}}
```

`actor` may be null, and values in `changes` may have different types depending on audited fields. This history has **no `links` key** in its controller response.

### 4. `GET /api/v1/admin/delivery/cities`

Optional query: `has_rate` and `covered`, each one of `true`, `false`, `1`, `0` (as strings). **200:** `{"data": [{"city_id":3,"name":{"ar":"مدينة تجريبية","en":"Example City"},"rate":{...Rate},"covered":true}]}`. `rate` is **null** if the active city has no rate. This lists active Locations cities only; `covered` is rate-level coverage, not necessarily globally enabled checkout courier availability.

## Rate mutations — `delivery.rates.manage`

### 5. `POST /api/v1/admin/delivery/rates`

**Request JSON:**

```json
{"city_id":3,"courier_fee":"25.00","courier_available":true,"estimated_days":{"ar":"2-3 أيام","en":"2-3 days"}}
```

| Field | Validation |
|---|---|
| `city_id` | Required integer, min 1; existence/business checks in handler |
| `courier_fee` | Required string matching `^\d{1,6}(\.\d{1,2})?$` (verified in `SetCourierFeeAction::FEE_RULE`) |
| `courier_available` | Optional boolean, defaults true |
| `estimated_days` | Optional nullable localized object; default locale required when supplied, unknown locales rejected, text length bounded by domain constant |
| `is_active` | Prohibited |

**201:** `{"data": Rate}`. A duplicate city rate or invalid city can be rejected by domain handlers; exact status not confirmed.

### 6. `PATCH /api/v1/admin/delivery/rates/{id}`

Only `courier_fee` (optional decimal string) and `estimated_days` (optional localized object or `null` to clear) are writable. `city_id`, `courier_available`, and `is_active` are **prohibited**. Example:

```json
{"courier_fee":"30.00","estimated_days":null}
```

**200:** `{"data": Rate}`. Switches must use the dedicated action routes below.

## Coverage switches — `delivery.coverage.manage`

All four requests have **no JSON body** and return **200** `{"data": Rate}`. `id` is a numeric rate ID.

### 7. `POST /api/v1/admin/delivery/rates/{id}/courier/enable`

Sets `courier_available=true` for the rate; does not independently activate the rate or the city.

### 8. `POST /api/v1/admin/delivery/rates/{id}/courier/disable`

Sets `courier_available=false` for the rate.

### 9. `POST /api/v1/admin/delivery/rates/{id}/activate`

Sets `is_active=true` for the rate.

### 10. `POST /api/v1/admin/delivery/rates/{id}/deactivate`

Sets `is_active=false` for the rate. **There is no DELETE route** for rates; use deactivation.

## Global delivery settings — `settings.manage`

### 11. `GET /api/v1/admin/delivery/settings`

**200 response** (example):

```json
{"data":{"courier_enabled":true,"direct_enabled":true,"direct_fee":"0.00","currency":"SAR","shipping_driver":"manual","shipping_drivers":["manual"]}}
```

Fields `courier_enabled`, `direct_enabled` booleans; `direct_fee` decimal string; `currency` and `shipping_driver` strings; `shipping_drivers` string array of installed drivers. The currently registered shipping implementation is manual; do not hard-code the array permanently in the UI.

### 12. `PATCH /api/v1/admin/delivery/settings`

Any subset of:

| Field | Validation |
|---|---|
| `courier_enabled` | Optional boolean |
| `direct_enabled` | Optional boolean |
| `direct_fee` | Optional string matching `^\d{1,6}(\.\d{1,2})?$` |
| `shipping_driver` | Optional string; must be in `shipping_drivers` allowed names |

Example request: `{"courier_enabled":false,"direct_fee":"15.00"}`. **200:** same `data` object as settings GET, reflecting the updated state. Changes are audited.

### 13. `GET /api/v1/admin/delivery/settings/history`

Optional `per_page` integer 1–100, default 25. **200:** `{"data": Change[],"meta":{"current_page":1,"last_page":1,"per_page":25,"total":0}}`. Same `Change` structure as rate history, with changed setting field names normalized (e.g. `delivery.direct_fee` becomes `direct_fee`).

## Error handling and implementation notes

- **401/403:** authentication and route permission failures (status conventional; exact exception JSON must be verified in Core middleware).
- **422:** request validation failure (exact localized error envelope not captured).
- **404 / domain error:** unknown rate ID, unsupported city, duplicate rate or domain rule violation; confirm mapped status and error code in deployment before binding UI behavior.
- The dashboard must distinguish `covered`, `available_at_checkout`, and the global `courier_enabled` switch; they are not interchangeable.
- Source review is **static** against `main`; no live endpoint calls or database-state assertions were made.

## Field-by-field implementation contract (dashboard handoff)

### Shared rate response fields

| JSON path | Type | Nullable | Dashboard behavior |
|---|---|---|---|
| `data.id` | integer | no | Stable rate ID; use for detail/actions |
| `data.city_id` | integer | no | Foreign key to Locations city |
| `data.city.id` | integer | no | City ID |
| `data.city.name` | object of locale-to-string/null | no | Select current locale with fallback |
| `data.city.is_active` | boolean | no | Whether city remains active in Locations |
| `data.courier_available` | boolean | no | Per-rate courier switch |
| `data.is_active` | boolean | no | Per-rate activation switch |
| `data.covered` | boolean | no | Effective coverage for rate and city |
| `data.available_at_checkout` | boolean/null | yes | Also accounts for global courier setting |
| `data.courier_fee` | decimal string | no | Display without floating-point conversion |
| `data.currency` | string | no | Fee currency |
| `data.estimated_days` | string/null | yes | Already localized by presenter; **not** a translation object |
| `data.created_at` | ISO-8601 string/null | yes | Creation timestamp |
| `data.updated_at` | ISO-8601 string/null | yes | Last modification timestamp |
| `data.recent_changes` | array | only on show | Latest five audit entries |

### Endpoint query/body matrix

| Method and path (relative to `/api/v1/admin/delivery`) | Query/path fields | JSON body fields | Success | Required permission |
|---|---|---|---|---|
| `GET rates` | `filter[...]`, `sort`, `per_page`, `page` | none | 200 paginated collection | `delivery.rates.view` |
| `GET rates/{id}` | numeric `id` | none | 200 Rate + `recent_changes` | `delivery.rates.view` |
| `GET rates/{id}/history` | numeric `id`, `per_page`, `page` | none | 200 `data` + `meta` | `delivery.rates.view` |
| `GET cities` | `has_rate`, `covered` | none | 200 city summary array | `delivery.rates.view` |
| `POST rates` | none | `city_id`, `courier_fee`, optional `courier_available`, `estimated_days` | 201 Rate | `delivery.rates.manage` |
| `PATCH rates/{id}` | numeric `id` | optional `courier_fee`, `estimated_days` | 200 Rate | `delivery.rates.manage` |
| `POST rates/{id}/courier/enable` | numeric `id` | none | 200 Rate | `delivery.coverage.manage` |
| `POST rates/{id}/courier/disable` | numeric `id` | none | 200 Rate | `delivery.coverage.manage` |
| `POST rates/{id}/activate` | numeric `id` | none | 200 Rate | `delivery.coverage.manage` |
| `POST rates/{id}/deactivate` | numeric `id` | none | 200 Rate | `delivery.coverage.manage` |
| `GET settings` | none | none | 200 Settings | `settings.manage` |
| `PATCH settings` | none | optional `courier_enabled`, `direct_enabled`, `direct_fee`, `shipping_driver` | 200 Settings | `settings.manage` |
| `GET settings/history` | `per_page`, `page` | none | 200 `data` + `meta` | `settings.manage` |

### Validations and business constraints

- `estimated_days` **request** is `null` or a localized map (for example `{"ar":"2-3 أيام","en":"2-3 days"}`); its **response** is a single localized string or `null`. The default locale is required when a non-null map is supplied, enabled locale keys are optional, and unknown keys are rejected.
- On `PATCH rates/{id}`, `city_id`, `courier_available`, and `is_active` are explicitly prohibited. On `POST rates`, `is_active` is prohibited.
- `courier_fee` and `direct_fee` are decimal **strings**, with 1–6 integral digits and up to two fractional digits.
- `filter[fee_min]` / `filter[fee_max]` have the same decimal pattern; `filter[q]` max 100 chars; date filters require valid dates; `per_page` 1–100, default 25.
- Settings' `shipping_driver` is constrained to installed `shipping_drivers`; the current source registers `manual`.
- Audit history items contain `id`, `event`, `changes[]` (`field`, `old`, `new`), nullable `actor` (`id`, nullable `name`), `ip_address`, and `at`; histories are newest first.
- List filters/sorts are restricted to the controller allowlists; unknown filters/sorts should be treated as client errors rather than silently supported.

### Source links

- [Delivery routes](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Delivery/Routes/api.php)
- [Rate admin controller](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Delivery/Interfaces/Http/Controllers/Admin/DeliveryRateAdminController.php)
- [Delivery settings controller](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Delivery/Interfaces/Http/Controllers/Admin/DeliverySettingsController.php)
- [Delivery rate validation](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Delivery/Interfaces/Http/Requests/DeliveryRateRequest.php)
- [Delivery presenter](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Delivery/Interfaces/Http/Presenters/DeliveryPresenter.php)
- [Audit trail](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Delivery/Interfaces/Http/Controllers/Admin/AuditTrail.php)

**Verification boundary:** source-reviewed only. No Staging requests, shipping-provider integration checks, or migration execution were performed.
