# Consultation Type Image — Frontend Integration Guide

Consultation types (مالية / ضريبية / إدارية …) now have an **image**. Admins can set it from the dashboard, and the learner web app receives it wherever consultation types are listed.

- **Audience:** frontend developers — **Admin dashboard** (`bateel-dashboard`) and **Learner web** (`bateel.react`)
- **Base path:** `{{base_url}}` = `/api/v1`. Envelope unchanged: `{ "status", "message", "data" }`.
- **Media base:** `{{media_base_url}}` = API host root, **no `/api/v1`**. See [media-upload-guide.md §3.1](./media-upload-guide.md#31-base-url--note-no-apiv1-prefix).
- **Related docs:** [consultations-admin.md](./consultations-admin.md) · [consultations-user.md](./consultations-user.md) · [media-upload-guide.md](./media-upload-guide.md) · [admin.md](./admin.md) / [user.md](./user.md) (auto-generated reference)

---

## Contents

1. [What changed](#1-what-changed)
2. [Admin dashboard](#2-admin-dashboard)
3. [Learner web](#3-learner-web)
4. [Behaviour details & edge cases](#4-behaviour-details--edge-cases)
5. [Error reference](#5-error-reference)
6. [Task checklist](#6-task-checklist)

---

## 1. What changed

This change only adds things. No existing field was renamed or removed, and `image` is **optional** on create and update, so current forms keep working without changes.

| Endpoint | App | Change |
|---|---|---|
| `POST /admin/consultation-types` | Admin | Accepts optional `image` (media hash) |
| `PUT /admin/consultation-types/{consultation_type}` | Admin | Accepts optional `image` (media hash) |
| `GET /admin/consultation-types` | Admin | Each row has `image` (URL) |
| `GET /admin/consultation-types/{consultation_type}` | Admin | Has `image` (URL) |
| `GET /user/consultation-types` | Web | Each row has `image` (URL) |
| `GET /user/search` | Web | Items under `consultation_types` have `image` (URL) |

**`image` is always a string URL in responses, never `null`.** A type without an uploaded image returns a placeholder URL (see [§4.1](#41-placeholder-image)).

No permission changes. The existing `admin.consultation-types.*` permissions cover everything here.

---

## 2. Admin dashboard

### 2.1 Flow

Images follow the standard two-step media flow ([media-upload-guide.md §1](./media-upload-guide.md#1-how-media-works-here-read-this-first)):

```
1. POST {{media_base_url}}/media          (multipart: file + collection=image)  →  { hash, url, … }
2. POST/PUT {{base_url}}/admin/consultation-types[/{uuid}]   { "image": "<hash>", … }
```

### 2.2 Step 1 — upload the file

`POST {{media_base_url}}/media` — `multipart/form-data`

| Field | Value |
|---|---|
| `file` | the image (`jpg`, `jpeg`, `png`, `webp`; max 10 MB at upload) |
| `collection` | `image` |

Headers: `Authorization: Bearer …`, **`Accept: application/json`** (mandatory on media routes). **Don't** set `Content-Type` yourself.

**201 Created** (trimmed):

```json
{
  "status": "success",
  "message": "Media uploaded successfully",
  "data": {
    "id": 812,
    "hash": "9f2c4b1ae07d4c55b8a3f1d2e6c7b901",
    "url": "https://api.example.com/storage/uploads/image/1f0c…e2.webp"
  }
}
```

Keep `data.hash` in form state and use `data.url` for an instant preview.

### 2.3 Step 2 — create

`POST {{base_url}}/admin/consultation-types`

```json
{
  "is_visible": true,
  "image": "9f2c4b1ae07d4c55b8a3f1d2e6c7b901",
  "en": { "name": "Financial Consulting", "description": "Expert advice on financial planning." },
  "ar": { "name": "الاستشارات المالية", "description": "مشورة متخصصة في التخطيط المالي." }
}
```

| Field | Type | Required | Rules |
|---|---|---|---|
| `is_visible` | boolean | no | — |
| `image` | string (media hash) | no | must be an uploaded **image** that is not attached to another record |
| `{en,ar}.name` | string | yes | max 150 |
| `{en,ar}.description` | string | no | — |

**201 Created:**

```json
{
  "status": "success",
  "message": "Data saved successfully",
  "data": {
    "id": "9d3f6a2e-8b1c-4f0a-a6e2-1c7b5d9e4f21",
    "name": "Financial Consulting",
    "description": "Expert advice on financial planning.",
    "image": "https://api.example.com/storage/uploads/image/1f0c…e2.webp",
    "is_visible": true
  }
}
```

### 2.4 Step 2 — update / replace the image

`PUT {{base_url}}/admin/consultation-types/{consultation_type}` — all fields optional.

| You send | Result |
|---|---|
| `image` omitted | Image unchanged |
| `image: "<new hash>"` | New image attached; **the previous file is deleted** |
| `image: "<current hash>"` | No-op (allowed) |
| `image: null` or `""` | **Image unchanged.** There's currently no way to clear an image. See [§4.2](#42-removing-an-image) |

Only send `image` when the admin actually picked a new file. Responses return the **URL**, not the hash, so you can't echo back what you received.

### 2.5 List & detail

`GET /admin/consultation-types` and `GET /admin/consultation-types/{consultation_type}` return the same row shape:

```json
{
  "id": "9d3f6a2e-8b1c-4f0a-a6e2-1c7b5d9e4f21",
  "name": "Financial Consulting",
  "description": "Expert advice on financial planning.",
  "image": "https://api.example.com/storage/uploads/image/1f0c…e2.webp",
  "is_visible": true
}
```

UI suggestions:

- **Table:** add a small thumbnail column (e.g. 40×40, `object-fit: cover`).
- **Edit form:** show `image` as the current preview, with a "Change image" control that runs §2.2. After a successful upload, swap the preview to the upload response's `url`.

### 2.6 Reference implementation (TypeScript)

```ts
async function uploadImage(file: File): Promise<{ hash: string; url: string }> {
  const form = new FormData();
  form.append('file', file);
  form.append('collection', 'image');

  const res = await fetch(`${MEDIA_BASE_URL}/media`, {
    method: 'POST',
    headers: { Accept: 'application/json', Authorization: `Bearer ${token}` },
    body: form,
  });
  const body = await res.json();
  if (res.status !== 201) throw new Error(body.message);
  return { hash: body.data.hash, url: body.data.url };
}

async function saveConsultationType(
  values: { is_visible: boolean; en: Translation; ar: Translation },
  newImageHash: string | null, // set only when the admin picked a new file
  uuid?: string,               // present when editing
) {
  const payload: Record<string, unknown> = { ...values };
  if (newImageHash) payload.image = newImageHash;

  const res = await fetch(
    `${BASE_URL}/admin/consultation-types${uuid ? `/${uuid}` : ''}`,
    {
      method: uuid ? 'PUT' : 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(payload),
    },
  );
  const body = await res.json();
  if (!res.ok) throw new Error(body.message); // 422 → show message (see §5)
  return body.data;
}
```

---

## 3. Learner web

### 3.1 Consultation types listing

`GET {{base_url}}/user/consultation-types` (public, no auth). Same query params as before.

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    {
      "id": "9d3f6a2e-8b1c-4f0a-a6e2-1c7b5d9e4f21",
      "name": "الاستشارات المالية",
      "description": "مشورة متخصصة في التخطيط المالي.",
      "image": "https://api.example.com/storage/uploads/image/1f0c…e2.webp"
    }
  ]
}
```

Render `image` on the consultation type cards and filter chips in the consultations section (قسم الاستشارات).

### 3.2 Global search

`GET {{base_url}}/user/search?search=…`. Items under `consultation_types` have the same shape as §3.1, `image` included. Use the same card component.

### 3.3 Rendering tips

- Use `object-fit: cover` in a fixed-ratio box. Uploaded images aren't cropped server-side, so aspect ratios vary.
- Add `loading="lazy"` on list cards.
- `image` is never `null`, but keep an `onError` fallback (a local default icon) in case a storage URL is unreachable.

---

## 4. Behaviour details & edge cases

### 4.1 Placeholder image

When no image was uploaded, `image` is a generated placeholder:

```
https://ui-avatars.com/api/?name=CT&background=e0f2fe&color=0369a1&size=200
```

- **Web:** if you'd rather show your own illustration, check `image.startsWith('https://ui-avatars.com/')` and swap in a local asset.
- **Admin:** use the same check to show "No image uploaded" instead of a preview.
- **Existing / seeded types** have no image yet, so they all show the placeholder until an admin uploads one.

### 4.2 Removing an image

There's currently **no "remove image" operation**. Sending `null`/`""` leaves the current image in place, and `DELETE /media/{id}` isn't applicable because responses don't expose the attached media id. **Admins can only replace an image, not clear it.** Hide any "remove" button until the backend adds this. Ask the backend team if you need it.

### 4.3 Upload expiry & reuse

- An uploaded file that isn't attached within **6 hours** is deleted. If an admin leaves the form open longer, the save fails with `The media file was not found.` Re-upload and retry.
- A hash can be attached to **one record only**. Don't reuse a hash from another consultation type, course, category, etc.

### 4.4 Recommended image specs (client-side)

The backend accepts any image up to 10 MB. For consistent cards, we recommend validating on the client before upload:

| Spec | Recommendation |
|---|---|
| Formats | `jpg`, `jpeg`, `png`, `webp` |
| Size | ≤ 2 MB |
| Dimensions | square-ish, ≥ 400×400, ≤ 800×800 |

`jpg`/`png` are re-encoded to WebP on upload, so the stored file is usually much smaller than the original.

---

## 5. Error reference

Validation errors return **HTTP 422**, `status: "fail"`, and only the **first** error in `message` (no per-field map). Show `message`.

| HTTP | `message` | Cause | Fix |
|---|---|---|---|
| 422 | `The media file was not found.` | Unknown hash, or the upload expired (> 6h) | Re-upload, then resave |
| 422 | `The media file is already associated with another record.` | Hash already attached to a different record | Upload a fresh file |
| 422 | `The file must be of type: image` | Hash belongs to a PDF/video/audio upload | Upload an image |
| 422 | `The physical file is missing from storage.` | Server-side storage problem | Re-upload; report if it repeats |

Upload-step errors (`POST /media`: 401, 413, 422 on extension/size) are listed in [media-upload-guide.md §14](./media-upload-guide.md#14-error-reference).

---

## 6. Task checklist

### Admin dashboard

- [ ] Add an image picker to the consultation type create/edit form. It uploads via `POST /media` with `collection=image`.
- [ ] Send `image: <hash>` only when a new file was picked.
- [ ] Show the current `image` as the preview on edit. Show "No image uploaded" when it's the placeholder (§4.1).
- [ ] Add a thumbnail column to the consultation types table.
- [ ] Show the 422 `message` on save failure (§5).
- [ ] Don't offer "remove image" (§4.2).

### Learner web

- [ ] Show `image` on consultation type cards and chips (`GET /user/consultation-types`).
- [ ] Show `image` on consultation type results in global search (`GET /user/search`).
- [ ] Optionally replace the placeholder with a local illustration (§4.1). Add an `onError` fallback.

### Retest

- [ ] Create a type with an image → the image shows in the admin list, admin detail, web listing and web search.
- [ ] Replace the image → the new image shows everywhere. The old URL stops working.
- [ ] Create a type without an image → the placeholder (or your local fallback) shows. No broken image.
- [ ] Save with an expired or already-used hash → the 422 message is shown and the form keeps its state.
