# Maintenance Checklists API - Postman Collection Guide

## Overview

This Postman collection provides complete API testing for the Maintenance Visit Checklists system with inheritance support.

## Features

- ✅ Full CRUD operations for checklists
- ✅ Checklist item management
- ✅ Visit checklist responses
- ✅ **Inheritance support** - Get checklists from parent asset types
- ✅ Search and filtering
- ✅ Complete workflow examples

---

## Getting Started

### 1. Import Collection

1. Open Postman
2. Click **Import**
3. Select `postman_collection_maintenance_checklists.json`
4. Collection will appear in your workspace

### 2. Configure Variables

The collection uses the following variables:

| Variable | Description | Example Value |
|----------|-------------|---------------|
| `base_url` | API base URL | `http://localhost/api` |
| `access_token` | Bearer token for authentication | Your JWT token |
| `checklist_id` | Current checklist ID | Auto-set from responses |
| `item_id` | Current item ID | Auto-set from responses |
| `project_id` | Maintenance project ID | `1` |
| `asset_type_id` | Asset type ID | `1` |
| `visit_id` | Maintenance visit ID | `1` |

**To set variables:**
1. Click on collection name
2. Go to **Variables** tab
3. Set `base_url` and `access_token`
4. Other variables auto-populate from test scripts

---

## API Endpoints Overview

### 📋 Checklists CRUD

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/maintenance/checklists` | GET | Get all checklists (paginated) |
| `/maintenance/checklists/{id}` | GET | Get specific checklist with items |
| `/maintenance/checklists` | POST | Create new checklist |
| `/maintenance/checklists/{id}` | PUT | Update checklist |
| `/maintenance/checklists/{id}` | DELETE | Soft delete checklist |
| `/maintenance/checklists/{id}/duplicate` | POST | Duplicate checklist |
| `/maintenance/checklists/search/query` | GET | Search checklists |

### 🔍 Filtering Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/maintenance/checklists/project/{projectId}` | GET | Get checklists by project |
| `/maintenance/checklists/asset-type/{assetTypeId}` | GET | Get checklists by asset type (direct only) |

### 🧬 Inheritance Endpoints (NEW)

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/maintenance/checklists/asset-type/{assetTypeId}/with-inheritance` | GET | Get checklists including inherited from parents |
| `/maintenance/checklists/project/{projectId}/asset-type/{assetTypeId}/with-inheritance` | GET | Get inherited checklists for project + asset type |

### 📝 Checklist Items

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/maintenance/checklists/{id}/items` | POST | Add item to checklist |
| `/maintenance/checklists/{id}/items/{itemId}` | PUT | Update checklist item |
| `/maintenance/checklists/{id}/items/{itemId}` | DELETE | Delete checklist item |

### ✅ Visit Responses

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/maintenance/checklists/visits/{visitId}/checklist` | GET | Get visit checklist responses |
| `/maintenance/checklists/visits/{visitId}/responses` | POST | Save visit checklist responses |

---

## Request/Response Examples

### Create Checklist with Items

**Request:**
```http
POST /api/maintenance/checklists
Content-Type: application/json
Authorization: Bearer {token}
```

```json
{
    "title": "HVAC Maintenance Checklist",
    "description": "General HVAC equipment maintenance",
    "maintenance_project_id": 1,
    "maintenance_asset_type_id": 1,
    "is_active": true,
    "items": [
        {
            "question_text": "Check refrigerant levels",
            "question_type": "yes_no",
            "is_required": true,
            "order_position": 1,
            "help_text": "Verify refrigerant is at proper levels"
        },
        {
            "question_text": "Temperature reading",
            "question_type": "number",
            "is_required": true,
            "order_position": 2,
            "help_text": "Record temperature in Celsius"
        },
        {
            "question_text": "Overall condition rating",
            "question_type": "rating",
            "is_required": false,
            "order_position": 3,
            "help_text": "Rate from 1-5"
        },
        {
            "question_text": "Additional notes",
            "question_type": "text",
            "is_required": false,
            "order_position": 4
        }
    ]
}
```

**Response:**
```json
{
    "success": true,
    "message": "تم إنشاء قائمة التحقق بنجاح",
    "code": 201,
    "data": {
        "id": 1,
        "title": "HVAC Maintenance Checklist",
        "description": "General HVAC equipment maintenance",
        "maintenance_project_id": 1,
        "maintenance_asset_type_id": 1,
        "is_active": true,
        "items": [
            {
                "id": 1,
                "question_text": "Check refrigerant levels",
                "question_type": "yes_no",
                "is_required": true,
                "order_position": 1,
                "help_text": "Verify refrigerant is at proper levels"
            }
            // ... more items
        ]
    }
}
```

---

### Get Checklists with Inheritance

**Scenario:** You have:
- Parent Asset Type: "HVAC Equipment" (ID: 1) with Checklist A
- Child Asset Type: "Air Conditioner" (ID: 2) with Checklist B

**Request:**
```http
GET /api/maintenance/checklists/asset-type/2/with-inheritance
Authorization: Bearer {token}
```

**Response:**
```json
{
    "success": true,
    "message": "قوائم التحقق لنوع الأصل مع الوراثة",
    "code": 200,
    "data": [
        {
            "id": 2,
            "title": "Air Conditioner Specific Checklist",
            "maintenance_asset_type_id": 2,
            "items": [...]
        },
        {
            "id": 1,
            "title": "General HVAC Checklist",
            "maintenance_asset_type_id": 1,
            "items": [...]
        }
    ]
}
```

---

### Save Visit Checklist Responses

**Request:**
```http
POST /api/maintenance/checklists/visits/1/responses
Content-Type: application/json
Authorization: Bearer {token}
```

```json
{
    "maintenance_visit_id": 1,
    "responses": [
        {
            "maintenance_checklist_item_id": 1,
            "response_value": "yes",
            "notes": "Refrigerant levels are normal",
            "is_compliant": true
        },
        {
            "maintenance_checklist_item_id": 2,
            "response_value": "22.5",
            "notes": "Temperature reading in Celsius",
            "is_compliant": true
        },
        {
            "maintenance_checklist_item_id": 3,
            "response_value": "5",
            "notes": "Excellent condition",
            "is_compliant": true
        },
        {
            "maintenance_checklist_item_id": 4,
            "response_value": "Unit is operating efficiently",
            "notes": null,
            "is_compliant": true
        }
    ]
}
```

**Response:**
```json
{
    "success": true,
    "message": "تم حفظ الإجابات بنجاح",
    "code": 201,
    "data": [
        {
            "id": 1,
            "maintenance_visit_id": 1,
            "maintenance_checklist_item_id": 1,
            "response_value": "yes",
            "notes": "Refrigerant levels are normal",
            "is_compliant": true
        }
        // ... more responses
    ]
}
```

---

## Question Types

The checklist system supports 4 question types:

| Type | Description | Response Format | Example |
|------|-------------|-----------------|---------|
| `yes_no` | Yes/No questions | `"yes"` or `"no"` | "Is equipment working?" |
| `text` | Free text | Any string | "Describe the issue..." |
| `number` | Numeric value | Number as string | `"22.5"`, `"100"` |
| `rating` | Rating scale | Number 1-5 | `"5"` (for 5 stars) |

---

## Testing Workflow - Complete Example

The collection includes a complete workflow example in the **"Examples - Complete Workflow"** folder:

### Step-by-Step Process:

1. **Create Parent Asset Type** (HVAC Equipment)
   - Sets `parent_asset_type_id` variable

2. **Create Child Asset Type** (Air Conditioner)
   - Uses `parent_id` to link to parent
   - Sets `child_asset_type_id` variable

3. **Create Checklist for Parent**
   - General HVAC checks
   - Sets `parent_checklist_id`

4. **Create Checklist for Child**
   - AC-specific checks
   - Sets `child_checklist_id`

5. **Get Inherited Checklists**
   - Call with `child_asset_type_id`
   - Should return **BOTH** checklists (parent + child)

### Run Complete Workflow:

1. Open the **"Examples - Complete Workflow"** folder
2. Click **Run** (Runner icon)
3. Select all requests
4. Click **Run Maintenance Visit...**
5. Review results - all should pass ✅

---

## Inheritance Use Cases

### Use Case 1: Equipment Hierarchy

```
HVAC Equipment
  ├─ Air Conditioner
  │   ├─ Central AC
  │   └─ Window AC
  └─ Heating System
      ├─ Furnace
      └─ Boiler
```

- Add common checks to "HVAC Equipment"
- Add AC-specific checks to "Air Conditioner"
- Add unit-specific checks to "Central AC"
- When servicing "Central AC", get all 3 levels of checklists

### Use Case 2: Building Systems

```
Building Systems (parent)
  ├─ Electrical (child)
  ├─ Plumbing (child)
  └─ Fire Safety (child)
```

- Common building checks at parent level
- System-specific checks at child level
- Each maintenance visit inherits common + specific checks

### Use Case 3: Vehicle Maintenance

```
Vehicles (parent)
  ├─ Heavy Equipment (child)
  │   ├─ Excavator (grandchild)
  │   └─ Crane (grandchild)
  └─ Light Vehicles (child)
```

- General vehicle safety checks at top level
- Equipment category checks at middle level
- Machine-specific checks at bottom level

---

## Tips & Best practices

### 1. Order Positioning
- Use increments of 10 (10, 20, 30...) for `order_position`
- Allows inserting items between existing ones

### 2. Help Text
- Always provide `help_text` for clarity
- Explain what constitutes compliance

### 3. Required Questions
- Mark critical safety checks as `is_required: true`
- Optional items for additional notes

### 4. Inheritance Strategy
- Put common checks at highest level
- Add specific checks at lower levels
- Avoid duplication across levels

### 5. Deactivating Checklists
- Use `is_active: false` instead of deleting
- Maintains historical data

### 6. Response Value Standards
- **yes_no**: Use lowercase `"yes"` or `"no"`
- **number**: Always send as string `"22.5"`
- **rating**: Use strings `"1"` to `"5"`
- **text**: Any text content

---

## Troubleshooting

### Issue: 401 Unauthorized
**Solution:** Check your `access_token` is valid and set in collection variables

### Issue: Checklist not inheriting
**Causes:**
1. Parent asset type not set (`parent_id` is null)
2. Using wrong endpoint (use `/with-inheritance` endpoints)
3. Parent checklist is inactive (`is_active: false`)

**Solution:** Verify hierarchy and use correct endpoints

### Issue: Duplicate responses
**Behavior:** Multiple calls with same `maintenance_checklist_item_id` will update (not duplicate)
**Explanation:** Using `updateOrCreate` - this is expected behavior

### Issue: Items not ordered correctly
**Solution:** Check `order_position` values - query results are ordered by this field

---

## Environment Variables Setup

For multiple environments (dev, staging, prod):

1. Create environments in Postman
2. Set these variables per environment:

```
base_url: http://localhost/api (dev)
base_url: https://staging.example.com/api (staging)
base_url: https://api.example.com/api (prod)

access_token: <environment-specific token>
```

---

## Auto-Generated IDs

The collection includes test scripts that automatically capture IDs:

```javascript
// After creating checklist
if (pm.response.code === 201) {
    var jsonData = pm.response.json();
    pm.collectionVariables.set('checklist_id', jsonData.data.id);
}
```

This allows sequential requests to use previously created resources.

---

## Authentication

All endpoints require authentication via Bearer token:

```http
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...
```

Set your token in the collection variable `access_token` and it will be automatically included in all requests.

---

## Support & Documentation

- **API Base URL:** `{base_url}/maintenance/checklists`
- **Migration File:** `database/migrations/2026_01_23_000001_add_parent_id_to_maintenance_asset_types_table.php`
- **Model:** `app/Domains/Maintenance/SubDomains/Assets/Models/MaintenanceAssetType.php`
- **Service:** `app/Domains/Maintenance/SubDomains/VisitChecklists/Services/MaintenanceVisitChecklistService.php`
- **Controller:** `app/Domains/Maintenance/SubDomains/VisitChecklists/Http/Controllers/V1/MaintenanceVisitChecklistController.php`
- **Routes:** `routes/apis/maintenance_visit_checklists.php`

---

## Quick Reference Card

```
📋 CRUD
GET    /maintenance/checklists              List all
GET    /maintenance/checklists/{id}         Get one
POST   /maintenance/checklists              Create
PUT    /maintenance/checklists/{id}         Update
DELETE /maintenance/checklists/{id}         Delete

🔍 FILTERS
GET /maintenance/checklists/project/{projectId}
GET /maintenance/checklists/asset-type/{assetTypeId}

🧬 INHERITANCE (NEW)
GET /maintenance/checklists/asset-type/{id}/with-inheritance
GET /maintenance/checklists/project/{pid}/asset-type/{aid}/with-inheritance

📝 ITEMS
POST   /maintenance/checklists/{id}/items
PUT    /maintenance/checklists/{id}/items/{itemId}
DELETE /maintenance/checklists/{id}/items/{itemId}

✅ RESPONSES
GET  /maintenance/checklists/visits/{visitId}/checklist
POST /maintenance/checklists/visits/{visitId}/responses
```

---

## License & Credits

Part of the Building Maintenance Management System
Created: 2026-01-23
