# Maintenance Visit Scheduling API Testing Guide

## Overview
This guide demonstrates how to test the newly implemented visit scheduling features.

---

## 🎯 Testing Scenario

We'll test the complete workflow:
1. Preview visit dates with recurrence pattern
2. Create a recurrence rule
3. Generate planned visits automatically
4. View planned (unscheduled) visits
5. Schedule a planned visit
6. Bulk schedule multiple visits
7. Import visits from Excel

---

## 1️⃣ Preview Visit Dates (Before Creating)

Test different recurrence patterns to see what dates will be generated.

### Monthly Pattern (12 visits over 1 year)
```http
POST /api/maintenance/recurrence-rules/preview
Content-Type: application/json
Authorization: Bearer {token}

{
  "recurrence_type": "monthly",
  "frequency": 1,
  "total_visits": 12,
  "start_date": "2026-02-01",
  "end_date": "2027-01-31"
}
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Preview generated successfully",
  "data": {
    "dates": [
      "2026-02-01",
      "2026-03-01",
      "2026-04-01",
      "2026-05-01",
      "2026-06-01",
      "2026-07-01",
      "2026-08-01",
      "2026-09-01",
      "2026-10-01",
      "2026-11-01",
      "2026-12-01",
      "2027-01-01"
    ],
    "count": 12
  }
}
```

### Specific Dates Pattern (1st and 15th of each month)
```http
POST /api/maintenance/recurrence-rules/preview
Content-Type: application/json

{
  "recurrence_type": "specific_dates",
  "frequency": 1,
  "specific_days": [1, 15],
  "total_visits": 6,
  "start_date": "2026-02-01",
  "end_date": "2026-04-30"
}
```

**Expected Response:**
```json
{
  "success": true,
  "data": {
    "dates": [
      "2026-02-01",
      "2026-02-15",
      "2026-03-01",
      "2026-03-15",
      "2026-04-01",
      "2026-04-15"
    ],
    "count": 6
  }
}
```

### Weekly Pattern (Every 2 weeks)
```http
POST /api/maintenance/recurrence-rules/preview
Content-Type: application/json

{
  "recurrence_type": "weekly",
  "frequency": 2,
  "total_visits": 8,
  "start_date": "2026-02-01",
  "end_date": "2026-05-31"
}
```

---

## 2️⃣ Create Recurrence Rule

Create a rule that will be used to generate visits.

```http
POST /api/maintenance/recurrence-rules
Content-Type: application/json
Authorization: Bearer {token}

{
  "contract_id": 1,
  "addendum_id": 1,
  "maintenance_project_id": 1,
  "recurrence_type": "monthly",
  "frequency": 1,
  "total_visits": 12,
  "start_date": "2026-02-01",
  "end_date": "2027-01-31"
}
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Recurrence rule created successfully",
  "data": {
    "id": 1,
    "contract_id": 1,
    "addendum_id": 1,
    "maintenance_project_id": 1,
    "recurrence_type": "monthly",
    "frequency": 1,
    "total_visits": 12,
    "visits_generated": 0,
    "start_date": "2026-02-01",
    "end_date": "2027-01-31",
    "is_active": true,
    "created_at": "2026-01-22T12:00:00.000000Z"
  }
}
```

---

## 3️⃣ Generate Planned Visits from Rule

Generate actual visit records based on the recurrence rule.

```http
POST /api/maintenance/recurrence-rules/1/generate-visits
Authorization: Bearer {token}
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Visits generated successfully",
  "data": {
    "visits": [
      {
        "id": 101,
        "visit_number": "VISIT-2026-00001",
        "visit_sequence": 1,
        "planned_date": "2026-02-01",
        "is_scheduled": false,
        "scheduled_at": null,
        "visit_type": "preventive",
        "status": "scheduled"
      },
      {
        "id": 102,
        "visit_number": "VISIT-2026-00002",
        "visit_sequence": 2,
        "planned_date": "2026-03-01",
        "is_scheduled": false,
        "scheduled_at": null,
        "visit_type": "preventive",
        "status": "scheduled"
      }
      // ... 10 more visits
    ],
    "count": 12
  }
}
```

---

## 4️⃣ Get Planned (Unscheduled) Visits

Retrieve all visits that have been planned but not yet scheduled.

```http
GET /api/maintenance/visits/planned?per_page=10
Authorization: Bearer {token}
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Planned visits retrieved successfully",
  "data": [
    {
      "id": 101,
      "visit_number": "VISIT-2026-00001",
      "visit_sequence": 1,
      "planned_date": "2026-02-01",
      "is_scheduled": false,
      "scheduled_at": null,
      "visit_type": "preventive",
      "status": "scheduled",
      "project": {
        "id": 1,
        "name": "ABC Company - Main Office Maintenance"
      }
    }
    // ... more visits
  ],
  "pagination": {
    "total": 12,
    "per_page": 10,
    "current_page": 1,
    "last_page": 2
  }
}
```

---

## 5️⃣ Schedule a Planned Visit

Convert a planned visit to scheduled by assigning technicians and confirming the date.

```http
POST /api/maintenance/visits/101/schedule
Content-Type: application/json
Authorization: Bearer {token}

{
  "scheduled_at": "2026-02-01 09:00:00",
  "technician_ids": [1, 2],
  "notes": "Regular preventive maintenance - Check HVAC systems"
}
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Visit scheduled successfully",
  "data": {
    "id": 101,
    "visit_number": "VISIT-2026-00001",
    "is_scheduled": true,
    "planned_date": "2026-02-01",
    "scheduled_at": "2026-02-01 09:00:00",
    "visit_type": "preventive",
    "notes": "Regular preventive maintenance - Check HVAC systems",
    "technicians": [
      {
        "id": 1,
        "name": "John Smith",
        "responsibility": "assigned"
      },
      {
        "id": 2,
        "name": "Jane Doe",
        "responsibility": "assigned"
      }
    ]
  }
}
```

---

## 6️⃣ Bulk Schedule Multiple Visits

Schedule multiple visits at once with the same technicians and date range.

```http
POST /api/maintenance/visits/bulk-schedule
Content-Type: application/json
Authorization: Bearer {token}

{
  "visit_ids": [102, 103, 104],
  "scheduling_data": {
    "scheduled_at": "2026-03-01 10:00:00",
    "technician_ids": [1, 2],
    "notes": "Quarterly maintenance batch"
  }
}
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Visits scheduled successfully",
  "data": {
    "scheduled_count": 3,
    "visits": [
      {
        "id": 102,
        "visit_number": "VISIT-2026-00002",
        "is_scheduled": true,
        "scheduled_at": "2026-03-01 10:00:00"
      },
      {
        "id": 103,
        "visit_number": "VISIT-2026-00003",
        "is_scheduled": true,
        "scheduled_at": "2026-03-01 10:00:00"
      },
      {
        "id": 104,
        "visit_number": "VISIT-2026-00004",
        "is_scheduled": true,
        "scheduled_at": "2026-03-01 10:00:00"
      }
    ]
  }
}
```

---

## 7️⃣ Download Import Template

Get an Excel template to bulk import visits.

```http
GET /api/maintenance/visits/import-template
Authorization: Bearer {token}
```

**Response:** Downloads `visit_import_template.xlsx`

**Template Structure:**
| Visit Type  | Planned Date | Notes                          |
|-------------|--------------|--------------------------------|
| preventive  | 2026-02-15   | Regular maintenance check      |
| corrective  | 2026-02-20   | Fix reported issue             |
| inspection  | 2026-03-01   | Annual safety inspection       |

---

## 8️⃣ Import Visits from Excel

Upload the filled template to create multiple visits.

```http
POST /api/maintenance/projects/1/visits/import
Content-Type: multipart/form-data
Authorization: Bearer {token}

file: [Excel file]
project_id: 1
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Visits import completed",
  "data": {
    "imported": 3,
    "errors": [],
    "visits": [
      {
        "id": 105,
        "visit_number": "VISIT-2026-00005",
        "visit_type": "preventive",
        "planned_date": "2026-02-15",
        "is_scheduled": false
      },
      {
        "id": 106,
        "visit_number": "VISIT-2026-00006",
        "visit_type": "corrective",
        "planned_date": "2026-02-20",
        "is_scheduled": false
      },
      {
        "id": 107,
        "visit_number": "VISIT-2026-00007",
        "visit_type": "inspection",
        "planned_date": "2026-03-01",
        "is_scheduled": false
      }
    ]
  }
}
```

---

## 9️⃣ Automatic Visit Generation on Contract Approval

When a contract is approved, visits are automatically generated.

```http
POST /api/maintenance/contracts/1/approve
Authorization: Bearer {token}
```

**What Happens:**
1. Contract status changes to "active"
2. `MaintenanceContractApproved` event is fired
3. `GenerateVisitsFromContract` listener executes
4. For each addendum with `visit_generation_mode = 'automatic'`:
   - Creates a recurrence rule
   - Generates planned visits based on `number_of_visits`
5. Projects and visits are ready for scheduling

**Check the results:**
```http
GET /api/maintenance/visits/planned?project_id=1
```

---

## 🔍 View Recurrence Rule Details

Check the details of a specific recurrence rule.

```http
GET /api/maintenance/recurrence-rules/1
Authorization: Bearer {token}
```

**Expected Response:**
```json
{
  "success": true,
  "message": "Recurrence rule retrieved successfully",
  "data": {
    "id": 1,
    "contract": {
      "id": 1,
      "contract_number": "MC-2026-00001",
      "customer_id": 10
    },
    "project": {
      "id": 1,
      "name": "ABC Company - Main Office Maintenance",
      "status": "in_progress"
    },
    "recurrence_type": "monthly",
    "frequency": 1,
    "total_visits": 12,
    "visits_generated": 12,
    "start_date": "2026-02-01",
    "end_date": "2027-01-31",
    "is_active": true,
    "visits": [
      // Array of 12 generated visits
    ]
  }
}
```

---

## 📝 Error Handling Examples

### Invalid Recurrence Type
```http
POST /api/maintenance/recurrence-rules/preview
Content-Type: application/json

{
  "recurrence_type": "invalid_type",
  "total_visits": 12
}
```

**Response:**
```json
{
  "success": false,
  "message": "Validation error",
  "errors": {
    "recurrence_type": [
      "Recurrence type must be one of: weekly, monthly, specific_dates, custom"
    ]
  }
}
```

### Missing Technicians When Scheduling
```http
POST /api/maintenance/visits/101/schedule
Content-Type: application/json

{
  "scheduled_at": "2026-02-01 09:00:00"
}
```

**Response:**
```json
{
  "success": false,
  "message": "Validation error",
  "errors": {
    "technician_ids": [
      "At least one technician must be assigned"
    ]
  }
}
```

---

## 🎯 Testing Checklist

- [ ] Preview dates for monthly pattern
- [ ] Preview dates for specific dates pattern
- [ ] Preview dates for weekly pattern
- [ ] Create recurrence rule
- [ ] Generate visits from rule
- [ ] View planned visits list
- [ ] Schedule single visit
- [ ] Bulk schedule multiple visits
- [ ] Download import template
- [ ] Import visits from Excel
- [ ] Approve contract and verify auto-generation
- [ ] Verify event listener execution in logs

---

## 📊 Database Verification

Check the data directly:

```sql
-- Check recurrence rules
SELECT * FROM mod_visit_recurrence_rules;

-- Check planned visits
SELECT id, visit_number, is_scheduled, planned_date, visit_sequence
FROM mod_maintenance_visits
WHERE is_scheduled = 0;

-- Check scheduled visits
SELECT id, visit_number, is_scheduled, scheduled_at
FROM mod_maintenance_visits
WHERE is_scheduled = 1;

-- Check visits with recurrence rule link
SELECT v.id, v.visit_number, v.visit_sequence, r.recurrence_type
FROM mod_maintenance_visits v
JOIN mod_visit_recurrence_rules r ON v.recurrence_rule_id = r.id;
```

---

## 🚀 Quick Test with cURL

```bash
# Preview dates
curl -X POST "http://localhost/api/maintenance/recurrence-rules/preview" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "recurrence_type": "monthly",
    "frequency": 1,
    "total_visits": 6,
    "start_date": "2026-02-01",
    "end_date": "2026-07-31"
  }'

# Get planned visits
curl -X GET "http://localhost/api/maintenance/visits/planned" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

---

## ✅ Success Criteria

All features are working if:

1. ✅ Preview returns correct date calculations
2. ✅ Recurrence rules are created successfully
3. ✅ Visits are generated with correct sequences
4. ✅ Planned visits show `is_scheduled = false`
5. ✅ Scheduling updates `is_scheduled = true`
6. ✅ Bulk scheduling works for multiple visits
7. ✅ Import accepts Excel files and validates data
8. ✅ Contract approval triggers automatic visit generation
9. ✅ Event listener logs appear in `storage/logs/laravel.log`

---

**Testing Complete! All endpoints are ready for production use.** 🎉
