# Test Scenario Guide: Schedule Corrective Visit Based on Parts Receipt

### 1. Scenario Introduction 🏢
This feature introduces a strict, supply-aware lifecycle for **Corrective Maintenance Visits**. In the previous implementation, visits could be scheduled immediately after a Price Offer was approved, often resulting in technicians being dispatched to sites before required parts were physically available.

The new workflow enforces a multi-stage clearance process to ensure logistical and financial readiness:
1.  **Finance Clearance**: Validates that required advance payments are settled (or the client is on approved credit terms).
2.  **Supply Planning**: Blocks progress until a procurement plan (**SupplyOrder**) has been generated for all required parts.
3.  **Parts Custody**: Tracks parts through the receipt chain, ensuring they have reached a "With Technician" or "With Client" status before permitting the final schedule.
4.  **Ready to Schedule**: Automatically notifies the supervisor only when all prerequisites are met, allowing for efficient resource allocation.

---

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

Analyze the changes in **Models**, **Enums**, and **API Responses**:

#### **Visit Status Enum Updates**
*   **File:** `App\Domains\Maintenance\SubDomains\Visits\Enums\VisitStatus`
*   **New Statuses:**
    *   `PENDING_FINANCE_CLEARANCE`: Finance block for advance payments.
    *   `PARTIALLY_SUPPLIED`: At least one part received, but not all.
    *   `READY_TO_SCHEDULE`: All parts received and in custody.

#### **API Response Changes (MaintenanceVisitResource)**
*   **Endpoint:** `GET /api/v1/maintenance/visits/{id}`
*   **New Fields:**
    *   `finance_clearance_status`: `pending_advance` | `deferred_client` | `cleared`.
    *   `supply_readiness`: Object containing `total_parts`, `received_parts`, and `all_received` (boolean).

#### **Service Layer Guards**
*   **MaintenanceVisitService::scheduleUnscheduledVisit**:
    *   Throws `Exception` if status is `PENDING_FINANCE_CLEARANCE`, `PENDING_SUPPLY`, or `PARTIALLY_SUPPLIED`.
*   **AutomaticProcurementService::createSupplyRequest**:
    *   Throws `Exception` if the visit is blocked by finance clearance.

---

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

| Aspect | Previous Behavior | New Behavior | Benefit |
| :--- | :--- | :--- | :--- |
| **Scheduling** | Visits could be scheduled immediately after approval. | Scheduling is blocked until parts are in custody. | **Operational Efficiency**: Prevents wasted dispatches. |
| **Finance** | Procurement could start before payment. | Procurement blocked until advance payment is cleared. | **Financial Security**: Reduces risk on high-value parts. |
| **Visibility** | Part status was separate from visit status. | Visit status auto-syncs with PO receipt progress. | **Data Integrity**: Single source of truth for "Ready" state. |

---

### 4. API Endpoints Table 📊

| Process | Endpoint | Method | Description |
| :--- | :--- | :--- | :--- |
| **Scheduling** | `/api/v1/maintenance/visits/{id}/schedule-unscheduled` | `POST` | Assigns date/team; now blocked by supply guards. |
| **Procurement** | `/api/v1/maintenance/automatic-procurement/create-supply-request` | `POST` | Generates PO Plan; now blocked by finance guards. |
| **Status View** | `/api/v1/maintenance/visits/{id}` | `GET` | Retrieves detailed finance and supply readiness state. |

---

### 5. Test Cases 🧪

#### **[Case 1] The Happy Path: Standard Supply Flow**
1.  **Price Offer Approved**: Visit is created in `PENDING_FINANCE_CLEARANCE` status.
2.  **Payment Settled**: Client pays advance; status auto-transitions to `PENDING_SUPPLY`.
3.  **PO Plan Generated**: Supervisor generates PO Plan; status auto-transitions to `PARTIALLY_SUPPLIED`.
4.  **Parts Received**: Goods Receipt is processed for all items; status auto-transitions to `READY_TO_SCHEDULE`.
5.  **Supervisor Notified**: Supervisor receives a `VisitReadyToScheduleNotification`.
6.  **Final Schedule**: Supervisor assigns a date; status transitions to `SCHEDULED`.

#### **[Case 2] Backward Compatibility: No Parts Required**
1.  **Corrective Visit**: A visit with no spare parts required (no POs needed).
2.  **Behavior**: The visit skips `PENDING_FINANCE_CLEARANCE` and `PENDING_SUPPLY`, remaining in `AWAITING_SCHEDULING` (or jumping to `READY_TO_SCHEDULE`).
3.  **Validation**: Legacy visits already in `SCHEDULED` or `IN_PROGRESS` are not affected by the recalculation logic.

#### **[Case 3] Edge Cases & Constraints**
*   **Deferred Client**: If a client has `allow_deferred_sale = true`, the visit must skip `PENDING_FINANCE_CLEARANCE` even if an advance is scheduled.
*   **Partial Receipt Block**: Scheduling must fail if even one part from the `SupplyOrder` is still in `supplying` status.
*   **Unauthorized Scheduling**: Ensure that the `scheduleUnscheduledVisit` endpoint returns a meaningful English error message when guards are triggered.
