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

# Dashboard — Identity user management (source-reviewed)

**Base URL:** `/api/v1`. **Authentication:** `Authorization: Bearer <Sanctum token>` on every route. **Error localization:** `LocalizeIdentityErrors`. **Evidence:** [`Routes/api.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Identity/Routes/api.php), [`UserController`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Identity/Interfaces/Http/Controllers/Admin/UserController.php), [`UserSuspensionController`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Identity/Interfaces/Http/Controllers/Admin/UserSuspensionController.php), [`IdentitySettingsController`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Identity/Interfaces/Http/Controllers/Admin/IdentitySettingsController.php), request validators and resources under `modules/Identity/Interfaces/Http/`.

**Status:** 10 distinct endpoints source-reviewed on `main`; examples are illustrative, **not live HTTP captures**. Error response bodies are not asserted without inspecting the exception renderer. `admin/auth/login` and `admin/me` belong to Access, not this module.

## Shared response schemas

### `AdminUser` — JSON object

| Field | Type | Notes |
|---|---|---|
| `id` | integer | User ID |
| `name` | string | Display name |
| `email`, `phone` | string or null | Account contacts |
| `locale`, `locale_label` | string | Language code and localized name |
| `status` | string | Account status, e.g. `active`, `suspended`, `pending` |
| `display_status`, `status_label` | string | UI badge; `banned` and `deleted` distinguished |
| `email_verified_at`, `phone_verified_at`, `created_at`, `updated_at` | ISO date-time or null | Account timestamps |
| `avatar_url` | string or null | Avatar location |
| `roles` | array of strings, optional | Only when role capability is installed |
| `suspension` | object, conditional | Present for suspended users: `kind`, `reason`, `at` |
| `pending_since`, `suspended_at`, `last_seen_at`, `deleted_at` | ISO date-time or null | Lifecycle timestamps |
| `suspension_reason`, `suspension_reference`, `unsuspension_reason` | string or null | Admin audit context |
| `suspended_by`, `signup_city_id` | integer or null | References |
| `suspension_kind` | string or null | `suspension` or `ban` when suspended |
| `terms` | object | `accepted_at`: ISO date-time/null, `version`: string/null |
| `deletion` | object or null | When deleted: `reason`, `by`, `by_owner`, `anonymized_at` |
| `active_tokens_count` | integer | Session count |

Illustrative detail:

```json
{"data":{"id":42,"name":"Example User","email":"example@example.com","phone":"+966501234567","locale":"ar","locale_label":"العربية","status":"active","display_status":"active","status_label":"Active","email_verified_at":null,"phone_verified_at":"2026-11-01T10:00:00+00:00","avatar_url":null,"created_at":"2026-10-01T10:00:00+00:00","pending_since":null,"suspended_at":null,"suspension_reason":null,"suspended_by":null,"suspension_kind":null,"suspension_reference":null,"unsuspension_reason":null,"signup_city_id":null,"terms":{"accepted_at":null,"version":null},"deleted_at":null,"deletion":null,"active_tokens_count":1,"last_seen_at":null,"updated_at":"2026-11-01T10:00:00+00:00"}}
```

`roles` and `suspension` may be omitted conditionally. Example field values are not fixtures.

### `AuditEntry` — history item

| Field | Type | Notes |
|---|---|---|
| `id` | integer | Audit ID |
| `event`, `action`, `action_label` | string | Raw event, stable action code, localized label |
| `old_values`, `new_values` | object | Empty objects rather than empty arrays |
| `actor_id` | integer or null | Administrator |
| `actor` | object or null | `{id: integer, name: string|null}` |
| `ip_address` | string or null | Audit origin |
| `created_at` | ISO date-time or null | Audit time |

Action codes include `registered`, `deleted`, `restored`, `banned`, `suspended`, `unsuspended`, `verified`, `renamed`, `phone_changed`, `email_changed`, `locale_changed`, `password_changed`, `account_updated`.

## 1. `GET /api/v1/admin/users`

**Permission:** `users.view`. **Purpose:** Search/filter/sort user directory. **Request body:** none.

| Query | Type / validation | Meaning |
|---|---|---|
| `filter[search]` | string | Searches name/email/phone, including normalized Saudi phone |
| `filter[name]`, `filter[email]`, `filter[phone]` | string | Partial matches; valid phone may be normalized |
| `filter[status]` | string or comma-separated values | Includes `banned` pseudo-status (suspended + permanent ban) |
| `filter[suspension_kind]`, `filter[locale]` | string | Exact |
| `filter[phone_verified]` | boolean-like | Verified phone |
| `filter[created_from]`, `filter[created_to]`, `filter[suspended_from]`, `filter[suspended_to]` | date | Inclusive boundaries; bare `*_to` date covers full day |
| `filter[trashed]` | `with` or `only` | Include/only soft-deleted users |
| `filter[role]`, `filter[roles.name]` | string | Available only when roles integration is installed |
| `sort` | `name`, `email`, `phone`, `status`, `created_at`, `suspended_at` with optional `-` | Default `-created_at` |
| `include` | role include names | Depends on installed role capability |
| `per_page` | integer >= 1 | Default 15; capped at 100 |
| `page` | positive integer | Pagination |

**Example:** `GET /api/v1/admin/users?filter[status]=banned&sort=-created_at&per_page=15&page=1`.

**Response 200:** Laravel JSON Resource paginated collection: `data: AdminUser[]`, `links` and `meta` pagination objects. Illustrative shape:

```json
{"data":[{"id":42,"name":"Example User","status":"suspended","display_status":"banned","suspension_kind":"ban"}],"links":{"first":"...","last":"...","prev":null,"next":null},"meta":{"current_page":1,"last_page":1,"per_page":15,"total":1}}
```

The row above is intentionally abbreviated; use the shared `AdminUser` schema for full fields. Unknown filters/sorts may be rejected by Spatie QueryBuilder.

## 2. `GET /api/v1/admin/users/{userId}`

**Permission:** `users.view`. **Path:** `userId` numeric. **Body/query:** none. **Response 200:** `{"data": AdminUser}` using shared schema. Deleted accounts remain readable to admins. Missing user: not-found error (exact localized envelope pending runtime check).

## 3. `GET /api/v1/admin/users/{userId}/history`

**Permission:** `users.view`. **Path:** numeric user ID. **Query:** `per_page` integer default 25 capped 100; `page` positive integer. **Response 200:** Laravel Resource pagination (`data: AuditEntry[]`, `links`, `meta`), newest audit first.

```json
{"data":[{"id":12,"event":"updated","action":"suspended","action_label":"Suspended","old_values":{"status":"active"},"new_values":{"status":"suspended"},"actor_id":7,"actor":{"id":7,"name":"Admin"},"ip_address":null,"created_at":"2026-11-01T10:00:00+00:00"}],"links":{"next":null},"meta":{"current_page":1,"total":1}}
```

Example pagination objects are abbreviated; actual Laravel resource pagination includes further keys.

## 4. `DELETE /api/v1/admin/users/{userId}`

**Permission:** `users.delete`. **Path:** numeric user ID. **Body:**

| Field | Type | Validation |
|---|---|---|
| `reason` | string | Required; max **500** characters (`User::MAX_DELETION_REASON`) |

```json
{"reason":"Administrative account removal"}
```

**Response:** `204 No Content` (JSON body absent). Repeating deletion on already-deleted account is idempotent. Deleting oneself is subject to domain restrictions. Do not parse `data` for 204.

## 5. `POST /api/v1/admin/users/{user}/suspend`

**Permission:** `users.suspend`; additionally `users.ban` when `kind=ban`. **Path:** `{user}` is model-bound; unlike `{userId}` no numeric route regex is explicitly set.

| Field | Type | Validation |
|---|---|---|
| `reason` | string | Required; max `User::MAX_SUSPENSION_REASON` |
| `reference` | string or null | Optional; max `User::MAX_SUSPENSION_REFERENCE` |
| `kind` | enum string | Optional; default `suspension`; `ban` requires `users.ban` |

```json
{"reason":"Fraud investigation","reference":"DSP-0012","kind":"suspension"}
```

**Response 200:** `{"data": AdminUser}` with refreshed `status`, `suspension_kind`, `suspension_reason`, `suspended_at`, `suspended_by`. Domain rules can reject self-suspension and invalid transitions.

## 6. `POST /api/v1/admin/users/{user}/ban`

**Permission:** `users.ban`. **Body:** same `SuspendUserRequest` schema (`reason` required, `reference` optional, `kind` accepted by validator), but the controller **always** executes permanent `ban` regardless of supplied `kind`. Prefer omitting `kind` on this endpoint.

```json
{"reason":"Confirmed policy violation","reference":"DSP-0012"}
```

**Response 200:** `{"data": AdminUser}` with `display_status="banned"`, `suspension_kind="ban"`.

## 7. `POST /api/v1/admin/users/{user}/unsuspend`

**Permission:** `users.suspend`; **lifting a permanent ban additionally requires `users.ban`** (checked by handler/controller). **Body:** `reason` optional nullable string, max `User::MAX_SUSPENSION_REASON`.

```json
{"reason":"Appeal accepted"}
```

**Response 200:** `{"data": AdminUser}` with refreshed state. Avoid assuming any user can lift a ban just because they can lift a temporary suspension.

## 8. `POST /api/v1/admin/users/{user}/revoke-sessions`

**Permission:** `users.suspend`. **Body:** `reason` required string, max `User::MAX_SUSPENSION_REASON`.

```json
{"reason":"Possible account takeover"}
```

**Response 200:** `data: AdminUser` plus `meta.revoked_sessions: integer`, `meta.message: string` (localized).

```json
{"data":{"id":42,"name":"Example User","status":"active"},"meta":{"revoked_sessions":3,"message":"Sessions revoked"}}
```

`data` is abbreviated here; real response contains the full `AdminUser` schema. Repeated action with no sessions returns `revoked_sessions: 0`.

## 9. `GET /api/v1/admin/identity/settings`

**Permission:** `identity.settings.manage`. **Body/query:** none. **Response 200:** `{"data": IdentitySettings}`.

| Field | Type | Meaning |
|---|---|---|
| `login_identifier` | enum string | Email or phone |
| `password_reset_ticket_ttl_seconds` | integer | Password reset ticket lifetime |
| `pending_registration_ttl_seconds` | integer | Pending registration lifetime |
| `password_min_length` | integer | Password minimum |
| `password_require_mixed_case`, `password_reject_breached` | boolean | Password rules |
| `allowed_phone_countries` | string[] | ISO country codes or `*` |
| `default_locale` | string | Enabled locale |

```json
{"data":{"login_identifier":"phone","password_reset_ticket_ttl_seconds":3600,"pending_registration_ttl_seconds":86400,"password_min_length":8,"password_require_mixed_case":true,"password_reject_breached":true,"allowed_phone_countries":["SA"],"default_locale":"ar"}}
```

## 10. `PATCH /api/v1/admin/identity/settings`

**Permission:** `identity.settings.manage`. **Body:** partial `IdentitySettings` object; all fields optional (`sometimes`).

| Field | Type | Validation |
|---|---|---|
| `login_identifier` | enum string | `LoginIdentifier` enum (`email`/`phone`) |
| `password_reset_ticket_ttl_seconds` | integer | 60–86400 |
| `pending_registration_ttl_seconds` | integer | 3600–2592000 |
| `password_min_length` | integer | 6–64 |
| `password_require_mixed_case`, `password_reject_breached` | boolean | Boolean |
| `allowed_phone_countries` | string[] | 1–50 entries; each two letters or `*` |
| `default_locale` | string | Must be enabled locale |

```json
{"password_min_length":10,"password_require_mixed_case":true,"allowed_phone_countries":["SA","EG"]}
```

**Response 200:** `{"data": IdentitySettings}` (full updated settings object, same schema as GET). Country codes are uppercased and deduplicated. Settings updates are audited. Pending-registration TTL must not undercut verification OTP lifetime (cross-module business rule).

## Integration and error checklist

- Use Sanctum bearer token and render/handle localized validation/business errors; framework expectations are 401 unauthenticated, 403 forbidden, 422 invalid request, 404 missing account, but **exact response body and every status have not been live-tested**.
- Do not treat a suspended account and a permanently banned account as the same dashboard badge: `display_status` distinguishes them.
- Deletion returns **204**; other mutation responses return updated user/settings, not an empty success.
- List/history use **Laravel Resource pagination**, not the flat `ApiResponse::ok` shape.
- Keep `reason` for admin actions; it is mandatory for suspend, ban, delete and revoke-sessions, optional for unsuspend.
- The `MAX_*` limits are named domain constants; numeric values should be resolved from `Modules\Identity\Domain\User` before hardcoding UI counters.
- No admin endpoint here edits arbitrary user profile fields; only the listed actions are exposed.


## Source-confirmed domain constraints and state transitions (2026-11-22)

Source: [`Domain/User.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Identity/Domain/User.php), [`Domain/SuspensionKind.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Identity/Domain/SuspensionKind.php), [`Domain/LoginIdentifier.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Identity/Domain/LoginIdentifier.php). These rules were read from source, not observed in a live API call.

| Constraint | Exact source value | Applies to |
|---|---:|---|
| `MAX_SUSPENSION_REASON` | 500 characters | suspend, ban, unsuspend reason, revoke sessions reason |
| `MAX_DELETION_REASON` | 500 characters | admin user deletion reason |
| `MAX_SUSPENSION_REFERENCE` | 100 characters | optional dispute/report reference on suspend/ban |
| `MIN_NAME` / `MAX_NAME` | 2 / 120 characters | user name domain invariant |
| `SuspensionKind` | `suspension`, `ban` | `kind` request and `suspension_kind` response |
| `LoginIdentifier` | `email`, `phone` | Identity settings `login_identifier` |

**Behavior important for dashboard integration:**

- `suspend` on an already suspended or banned account is idempotent; it does **not** downgrade a permanent ban to suspension.
- `ban` escalates a temporary suspension to permanent ban, but retrying an existing ban makes no state change.
- `unsuspend` on an active account is idempotent. A pending account cannot be unsuspended; lifting a permanent ban requires `users.ban`.
- Administrators cannot suspend or delete their own accounts using these admin operations.
- `DELETE /admin/users/{userId}` is a **soft deletion** and returns `204` even when repeated. The domain retains the account's phone/email until anonymization; **do not equate admin soft deletion with self-service anonymization**.
- `POST /admin/users/{user}/revoke-sessions` is idempotent and may return `meta.revoked_sessions: 0`.
- `login_identifier=email` creates an immediately active registration; `phone` registration stays pending until SMS verification.

**Client implementation:** Treat `204` as a successful empty response, use `display_status` for the badge (especially `banned` and `deleted`), refresh the returned `AdminUser` after account actions, and display the localized server error on forbidden state transitions. Exact error codes and envelopes remain unverified pending exception-handler review and runtime captures.
