# Flutter Guide: Technician Order Items — `is_visit` & `is_quoted`

This document describes the changes to the technician order API (`Technician\Order\OrderResource` and `Technician\Order\OrderDetailsResource`). Every order **item** now exposes two flags so the technician app can tell **visit-only lines** and **quoted (custom-priced) lines** apart from regular catalog services.

---

## 1. Summary of Changes

| # | Change | Where | Breaking? |
|---|---|---|---|
| 1 | New field **`is_visit`** on each item | Orders list + order details | No (additive) |
| 2 | New field **`is_quoted`** on each item | Orders list + order details | No (additive) |
| 3 | Details `items[]` is now built by a dedicated `OrderItemResource` | Order details | No (same fields as before) |
| 4 | Details `category` is now omitted when `items` is not loaded | Order details | **Edge case** — see §5 |

---

## 2. New Item Fields

| Field | Type | Nullable? | Description |
|---|---|---|---|
| **`is_visit`** | `bool` | No (always `true`/`false`) | `true` when the line is a **visit-only service** (e.g. the base diagnostic/inspection visit fee). Comes from the item's category (`categories.is_visit`). Defaults to `false` if the item has no category. |
| **`is_quoted`** | `bool` | No | `true` for **custom-request (quote) lines** (`order_items.is_quoted`). Custom requests are created with `is_quoted = true` and `unit_price = 0`; an admin later sets the real `unit_price`. Catalog lines created at checkout are `false`. |

> **Meaning of the combinations**
>
> | `is_visit` | `is_quoted` | Line type |
> |---|---|---|
> | `false` | `false` | Regular catalog service, fixed price |
> | `true`  | `false` | Visit-only line (diagnostic / inspection fee) |
> | `false` | `true`  | Custom request, priced by quote |

> **Note:** a custom-request line has `unit_price = 0` until an admin prices it. Do not show `0` as a final price when `is_quoted == true`; treat it as "pending quote" (see §8).

---

## 3. Affected Endpoints

### 3.1 Order details — `items[]` gets both new fields

| Method | Endpoint |
|---|---|
| `GET` | `/api/v1/technician/orders/{id}` |
| `POST` | `/api/v1/technician/orders/{id}/accept-assignment` |
| `POST` | `/api/v1/technician/orders/{id}/reject-assignment` |
| `POST` | `/api/v1/technician/orders/{id}/start-heading` |
| `POST` | `/api/v1/technician/orders/{id}/start-execution` |
| `POST` | `/api/v1/technician/orders/{id}/finish` |
| `POST` | `/api/v1/technician/orders/{id}/unreachable` |

### 3.2 Orders list — `items[]` gets both new fields

| Method | Endpoint |
|---|---|
| `GET` | `/api/v1/technician/orders` |

> The list's `items[]` is a **lightweight** shape (`service_name`, `service_image`, `quantity` + the 2 new flags). The details `items[]` is the **full** shape. Use two separate Dart models (see §6).

---

## 4. Example Responses

### 4.1 Orders list item — `GET /technician/orders`

```json
{
  "id": 41,
  "uuid": "9b1f…",
  "order_number": "ORD-000041",
  "category": { "id": 3, "name": "Plumbing", "image": "https://…/plumbing.png" },
  "status": "accepted",
  "items": [
    {
      "service_name": "Inspection Visit",
      "service_image": "https://…/visit.png",
      "quantity": 1,
      "is_visit": true,
      "is_quoted": false
    },
    {
      "service_name": "Leak repair",
      "service_image": "https://…/leak.png",
      "quantity": 2,
      "is_visit": false,
      "is_quoted": false
    }
  ]
}
```

### 4.2 Order details — `GET /technician/orders/{id}`

```json
{
  "id": 41,
  "order_number": "ORD-000041",
  "category": { "id": 3, "name": "Plumbing", "image": "https://…/plumbing.png" },
  "items": [
    {
      "id": 88,
      "service_name": "Inspection Visit",
      "quantity": 1,
      "notes": null,
      "unit_price": "100.00",
      "is_visit": true,
      "is_quoted": false,
      "request_description": null,
      "request_media": []
    },
    {
      "id": 89,
      "service_name": "Custom request",
      "quantity": 1,
      "notes": null,
      "unit_price": "0.00",
      "is_visit": false,
      "is_quoted": true,
      "request_description": "Water heater makes a loud noise",
      "request_media": ["https://…/req-1.jpg"]
    }
  ]
}
```

---

## 5. Details Resource — Behaviour Notes

### 5.1 `category` handling

`category` is now resolved with `whenLoaded('items', …)`, the same way the Client app does it:

- Items loaded (always the case for the endpoints in §3.1) → `category` is the **main (top-level) category** of the first item: `{ id, name, image }`, or `null` if the first item has no category.
- Items **not** loaded → the `category` key is **absent** from the JSON (previously it was `null`).

In practice the technician endpoints always load items, so nothing changes at runtime. Still, parse the key as optional.

### 5.2 `items` handling

`items` is now produced by a dedicated `Technician\Order\OrderItemResource`. The existing fields are **unchanged** (`id`, `service_name`, `quantity`, `notes`, `unit_price`, `request_description`, `request_media`) — only `is_visit` and `is_quoted` were added.

`request_media` is still a **list of URL strings** (empty list for catalog lines).

---

## 6. Backend Resource Diff

### `Technician/Order/OrderResource.php` (list)

```diff
  'items' => $this->whenLoaded('items', fn () => $this->items->map(fn ($item) => [
      'service_name'      => $item->service_name,
      'service_image'     => $item->category?->image,
      'quantity'          => $item->quantity,
+     'is_visit'          => (bool) $item->category?->is_visit,
+     'is_quoted'         => $item->is_quoted,
  ])),
```

### `Technician/Order/OrderDetailsResource.php` (details)

```diff
- 'category'       => $items->first()?->categorySummary(),
+ 'category'       => $this->whenLoaded('items', fn () => $this->items->first()?->categorySummary()),
  …
- 'items' => $this->whenLoaded('items', fn() => $this->items->map(fn($item) => [ …inline mapping… ])),
+ 'items'          => OrderItemResource::collection($this->whenLoaded('items')),
```

### `Technician/Order/OrderItemResource.php` (new)

```php
return [
    'id'                  => $this->id,
    'service_name'        => $this->service_name,
    'quantity'            => $this->quantity,
    'notes'               => $this->notes,
    'unit_price'          => $this->unit_price,
    'is_visit'            => (bool) $this->category?->is_visit,
    'is_quoted'           => $this->is_quoted,
    'request_description' => $this->request_description,
    'request_media'       => $this->media
        ->where('collection', 'request_media')
        ->map(fn ($media) => $media->url())
        ->values(),
];
```

---

## 7. Flutter Model Update

### 7.1 List item (lightweight)

```dart
class OrderListItem {
  final String? serviceName;
  final String? serviceImage;
  final int quantity;
  final bool isVisit;    // new
  final bool isQuoted;   // new

  OrderListItem({
    this.serviceName,
    this.serviceImage,
    required this.quantity,
    this.isVisit = false,
    this.isQuoted = false,
  });

  factory OrderListItem.fromJson(Map<String, dynamic> json) => OrderListItem(
        serviceName: json['service_name'],
        serviceImage: json['service_image'],
        quantity: (json['quantity'] as num?)?.toInt() ?? 1,
        isVisit: json['is_visit'] ?? false,
        isQuoted: json['is_quoted'] ?? false,
      );
}
```

### 7.2 Details item (full)

```dart
class OrderItem {
  final int id;
  final String? serviceName;
  final int quantity;
  final String? notes;
  final String? unitPrice;
  final bool isVisit;               // new
  final bool isQuoted;              // new
  final String? requestDescription;
  final List<String> requestMedia;

  OrderItem({
    required this.id,
    this.serviceName,
    required this.quantity,
    this.notes,
    this.unitPrice,
    this.isVisit = false,
    this.isQuoted = false,
    this.requestDescription,
    this.requestMedia = const [],
  });

  factory OrderItem.fromJson(Map<String, dynamic> json) => OrderItem(
        id: json['id'],
        serviceName: json['service_name'],
        quantity: (json['quantity'] as num?)?.toInt() ?? 1,
        notes: json['notes'],
        unitPrice: json['unit_price']?.toString(),
        isVisit: json['is_visit'] ?? false,
        isQuoted: json['is_quoted'] ?? false,
        requestDescription: json['request_description'],
        requestMedia: (json['request_media'] as List?)
                ?.map((e) => e.toString())
                .toList() ??
            const [],
      );
}
```

> **Defaults matter:** use `?? false` so older cached responses or any response missing the keys still parse.

---

## 8. UI Guidance

| Condition | Suggested UI |
|---|---|
| `isVisit == true` | Show a **"Visit"** badge/chip on the line; treat it as an inspection fee rather than a repair service. |
| `isQuoted == true` | Show a **"Custom request / Quoted"** badge; display `requestDescription` and `requestMedia` prominently since the technician needs them to assess the job. |
| `isQuoted == true` and `unitPrice` is `0` / empty | Show "Pending quote" instead of a price (admin has not priced it yet). |
| Both `false` | Render exactly as before. |

On the orders **list** card, a small badge next to the service name is enough. The full request description/media are only available on the details screen.

---

## 9. Migration Checklist

- [ ] Add `isVisit` / `isQuoted` to the list item model (§7.1) and details item model (§7.2).
- [ ] Parse both with a `false` default.
- [ ] Treat the details `category` key as optional (§5.1).
- [ ] Add the badges / pending-quote state to the list card and details screen (§8).
- [ ] Re-test: list, details, and the lifecycle actions (accept, start-heading, start-execution, finish, unreachable) — they all return the details resource.
