# Test Scenario Guide: Maintenance Visit Management & Automated Compliance

This feature enhances the maintenance lifecycle by automating contract compliance, cost responsibility splitting, and proactive request generation based on technical faults. It ensures that contractual agreements regarding spare parts budgets are strictly enforced at the point of invoicing and visit scheduling.

## 1. Scenario Introduction
The maintenance visit management system now intelligently bridges the gap between field technical work and financial contract terms. By introducing **Automated Contract Linking** and **Budget Consumption Tracking**, the system eliminates manual verification of whether a client should be billed for specific spare parts. Additionally, it ensures continuity of service by automatically converting discovered faults in preventive visits into new corrective maintenance requests.

## 2. Technical Schema Changes 🔍

### Database & Model Updates
*   **MaintenanceContract**: Added `spare_parts_budget`. Introduced `getRemainingSparePartsBudget()` logic to track consumption in real-time.
*   **MaintenanceVisitSparePart**: Added `company_cost` and `client_cost` to track who pays for what based on the contract threshold.
*   **MaintenanceVisitReport**: Added `operational_test_result` (pass/fail) and `operational_test_notes`.
*   **MaintenanceInvoice**: Added `internal_*` fields to track the actual cost vs. the billable cost to the client.
*   **MaintenanceVisit**: Added `cost_approval_status` (none, pending, approved, rejected).

### Business Logic Enhancements
*   **MaintenanceRequestService**: Now includes `resolveContractForRequest`, which auto-detects active contracts based on `customer_id`, `location_id`, and `asset_id`.
*   **MaintenanceInvoiceService**: Implements `applyContractCoverage` to automatically zero-out costs covered by active contracts during invoice generation.
*   **MaintenanceVisitFaultService**: Implements `autoCreateRequestFromFault` to trigger a new `new` status corrective request when a fault is found in a `preventive` visit.

## 3. Why the Update? (Change Log) 🔄
| Feature | Previous Behavior | New Behavior | Benefit |
| :--- | :--- | :--- | :--- |
| **Contract Linking** | Manual assignment of contracts to maintenance requests. | AI-driven auto-detection and linking of active contracts. | Reduced human error and faster processing. |
| **Spare Parts Billing** | Manual calculation of client charges for materials. | Automatic splitting of costs against the `spare_parts_budget`. | Guaranteed contractual compliance and transparency. |
| **Scheduling Guardrails**| Visits could be scheduled even if the client owed extra money. | Scheduling is blocked if `cost_approval_status` is `pending`. | Financial risk mitigation. |
| **Field Accountability** | Operational testing after repair was optional/untracked. | Corrective reports **cannot be approved** without a test result. | Higher service quality and verified fixes. |

## 4. API Endpoints Table 📊
| Process | Endpoint | Method | Description |
| :--- | :--- | :--- | :--- |
| **Request Creation** | `/api/v1/maintenance/requests` | `POST` | Corrective requests now auto-link contracts |
| **Fault Recording** | `/api/v1/maintenance/reports/{id}/faults`| `POST` | Triggers a new corrective request if in preventive visit |
| **Visit Scheduling** | `/api/v1/maintenance/visits/{id}/schedule`| `POST` | Now validates cost approval before finalizing |
| **Invoice Generation**| `/api/v1/maintenance/invoices` | `POST` | Auto-calculates billable amount vs. internal cost |

## 5. Test Cases 🧪

### [Case 1] Automated Budget Splitting (The Happy Path)
1.  **Prep**: A contract with `spare_parts_budget = 1000`.
2.  **Action**: Add a spare part worth `1500` to a corrective visit.
3.  **Expectation**: 
    *   `company_cost` should be `1000`.
    *   `client_cost` should be `500`.
    *   `cost_approval_status` of the visit should change to `pending`.

### [Case 2] Proactive Fault Management
1.  **Action**: During a **Preventive Visit**, record a "Leaking Valve" fault on a specific AC unit.
2.  **Expectation**: A new **Corrective Request** should be created automatically, linked to the same location and asset, with the source marked as `system`.

### [Case 3] Edge Cases & Constraints
*   **Validation Block**: Try to approve a **Corrective Report** without filling the `operational_test_result`. System must return an error: *"لا يمكن اعتماد تقرير صيانة تصحيحية بدون تسجيل نتيجة اختبار التشغيل"*.
*   **Scheduling Block**: Attempt to schedule a visit where `cost_approval_status = pending`. System must block the action until the client approves the extra cost.
*   **Contract Expired**: Create a request for a customer whose contract ended yesterday. System should mark `has_active_contract = false` and keep the request in `draft` or `new` (instead of `AWAITING_EXECUTION`).

---

> [!IMPORTANT]
> The **Internal Total** and **Client Total** on invoices must be audited together; the difference should always equal the amount covered by the contract.

> [!NOTE]
> Notifications are now dispatched automatically to clients via `MaintenanceVisitScheduledNotification` as soon as a corrective visit is confirmed.
