# Test Scenario Guide: Backlog Dispatching & Smart Scheduling

### 1. Scenario Introduction 🚀
The **Backlog Dispatching & Smart Scheduling** module is designed to streamline the management of maintenance visit backlogs. Its primary business goal is to transition "Planned" visits into "Scheduled" visits by assigning them to qualified technicians based on **system specialties**, **geographic clustering**, and **workload capacity**.

This feature introduces a **Smart Scheduling** engine that prioritizes critical assets (e.g., Chillers) and groups visits by location to minimize travel time, while ensuring no technician is overloaded beyond their weekly capacity.

---

### 2. Technical Schema Changes (Detailed) 🔍

#### Database Migration
* **Table:** `mod_maintenance_visits`
* **New Columns:**
    * `scheduled_week`: `tinyInteger` (1-4) representing the week of the month.
    * `dispatched_by`: `foreignId` linked to `users.id`.
    * `dispatched_at`: `timestamp` recording the exact time of assignment.

#### FormRequest Validation
* **Endpoint:** `POST /api/v1/maintenance/visits/{visit_id}/dispatch`
    * **Rules:**
        * `technician_id`: `required`, `uuid`, `exists:users,id`.
        * `scheduled_week`: `required`, `integer`, `between:1,4`.
        * `notes`: `nullable`, `string`.
* **Endpoint:** `POST /api/v1/maintenance/backlog-dispatching/validate-assignment`
    * **Rules:**
        * `visit_id`: `required`, `uuid`, `exists:mod_maintenance_visits,id`.
        * `technician_id`: `required`, `uuid`, `exists:users,id`.
        * `week`: `required`, `integer`, `between:1,4`.

#### API Responses
* **Resource:** `Backlog Statistics`
    * **Added:** `delay_margin` object containing `is_behind` (boolean) and `alert` (boolean) based on scheduling velocity.
* **Resource:** `Technician Workload`
    * **Added:** `load_percentage` and `daily_load` (breakdown of counts per day).

---

### 3. Why the Update? (Change Log) 🔄

| Feature | Previous Behavior | New Behavior | Benefit |
| :--- | :--- | :--- | :--- |
| **Assignment Logic** | Manual status update only. | Automated validation of technician specialty. | **Data Integrity:** Prevents assigning Chillers to non-certified techs. |
| **Visibility** | Simple list of visits. | Kanban-style `schedule-view` grouped by technician and week. | **UX Efficiency:** Rapid overview of monthly distribution. |
| **Capacity Management** | No workload tracking. | Real-time calculation of `load_percentage`. | **Efficiency:** Prevents technician burnout and scheduling conflicts. |
| **Clustering** | Sequential processing. | Geographic clustering (City/Region). | **Optimization:** Reduces travel costs and fuel consumption. |

---

### 4. API Endpoints Table 📊

| Process | Endpoint | Method | Description |
| :--- | : :--- | :--- | :--- |
| **Config** | `/api/v1/maintenance/backlog-dispatching/config` | `GET` | Get filters (months, projects, system types, regions). |
| **Statistics** | `/api/v1/maintenance/backlog-dispatching/statistics` | `GET` | Get backlog health, delay margin, and alerts. |
| **Backlog List** | `/api/v1/maintenance/backlog-dispatching/backlog` | `GET` | Paginated list of "Planned" visits with coordinates. |
| **Technicians** | `/api/v1/maintenance/backlog-dispatching/technicians` | `GET` | List technicians with their monthly workload data. |
| **Validation** | `/api/v1/maintenance/backlog-dispatching/validate-assignment` | `POST` | Check compatibility before final dispatch. |
| **Schedule View** | `/api/v1/maintenance/backlog-dispatching/schedule-view` | `GET` | Data for the monthly Kanban/Calendar board. |
| **Dispatch** | `/api/v1/maintenance/visits/{visit_id}/dispatch` | `POST` | Assign a specific visit to a technician. |
| **Smart Suggest** | `/api/v1/maintenance/backlog-dispatching/smart-suggest` | `POST` | Generate an optimized distribution proposal. |
| **Bulk Accept** | `/api/v1/maintenance/backlog-dispatching/smart-suggest/accept` | `POST` | Confirm and process multiple suggested assignments. |

---

### 5. Test Cases 🧪

#### **[Case 1] The Happy Path**
1.  **Request Statistics:** Call `GET /statistics` to verify current backlog health.
2.  **Suggest Distribution:** Call `POST /smart-suggest` for the current month.
3.  **Verify Proposal:** Ensure "Chiller" system types are prioritized and grouped in clusters.
4.  **Accept Suggestion:** Call `POST /smart-suggest/accept` with the proposed assignments.
5.  **Verify State:** Ensure visit status changed to `scheduled` and technician received a `VisitDispatchedNotification`.

#### **[Case 2] Backward Compatibility**
*   Ensure that visits created before the migration (without `scheduled_week`) still appear in the `backlog` endpoint and can be dispatched using the new workflow without database errors.
*   Verify that `dispatchedBy` relationship returns `null` or `System` for legacy data instead of crashing.

#### **[Case 3] Edge Cases & Constraints**
*   **Specialty Mismatch:** Attempt to dispatch a "Chiller" visit to a technician without the "Chiller" specialty. Expected: `422 Unprocessable Entity` or `technician_not_certified` error.
*   **Overload Warning:** Assign a visit to a technician who already has 100% load. Expected: Success but with an `overloaded` warning flag in the response.
*   **Invalid Week:** Send `scheduled_week: 5`. Expected: Validation failure on `between:1,4`.
*   **Empty Clusters:** Run `smart-suggest` for a month with zero "Planned" visits. Expected: `200 OK` with empty clusters and zero summary counts.
