# Asset History Management API Documentation

## Overview

The Asset History Management API provides comprehensive endpoints to access detailed history for each asset within a maintenance project. This includes basic asset data, maintenance visits, breakdowns, spare parts usage, performance indicators, photos, and a complete timeline of events.

**Base URL:** `/api/maintenance/projects/{projectId}/assets/{assetId}`

**Authentication:** All endpoints require authentication via Sanctum token.

---

## Table of Contents

1. [Comprehensive History Endpoint](#comprehensive-history-endpoint)
2. [Header Information](#header-information)
3. [Overview (Basic Asset Data)](#overview-basic-asset-data)
4. [Maintenance History (Visits)](#maintenance-history-visits)
5. [Breakdowns & Failures Log](#breakdowns--failures-log)
6. [Spare Parts Usage Log](#spare-parts-usage-log)
7. [Asset KPIs](#asset-kpis)
8. [Photos and Attachments](#photos-and-attachments)
9. [Timeline](#timeline)

---

## Comprehensive History Endpoint

Get all asset history data in a single request.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/maintenance-history
```

### Description

Returns comprehensive asset history including all tabs: header, overview, maintenance history, breakdowns, spare parts, KPIs, photos, and timeline.

### Parameters

| Parameter | Type | Location | Required | Description |
|-----------|------|----------|----------|-------------|
| projectId | integer | Path | Yes | The ID of the maintenance project |
| assetId | integer | Path | Yes | The ID of the asset |

### Response

```json
{
  "data": {
    "header": {
      "asset_name": "AC Unit 001",
      "asset_code": "AC-001",
      "current_status": "operational",
      "status_label": "تشغيلي",
      "location": "Building A - Floor 2",
      "date_of_last_visit": "2024-01-15 10:30:00"
    },
    "overview": {
      "equipment_name": "Air Conditioning Unit",
      "location_building": "Building A - Floor 2",
      "code": "AC-001",
      "specifications": "3.5 Ton Split Unit",
      "model": "LG-3500",
      "serial_number": "SN123456789",
      "voltage": "220V",
      "frequency": "50Hz",
      "capacity_operating_pressure": "350 PSI",
      "manufacturer_address": "Seoul, South Korea",
      "internal_distributor": "ABC Distributors",
      "production_date": "2020-05-15",
      "delivery_installation_date": "2020-06-20",
      "manufacturer": "LG Electronics",
      "asset_type": "HVAC System"
    },
    "maintenance_history": [...],
    "breakdowns": [...],
    "spare_parts": [...],
    "kpis": {...},
    "photos_attachments": [...],
    "timeline": [...]
  },
  "message": "تم جلب تاريخ الأصل بنجاح"
}
```

### Permissions

- `maintenance.project_assets.view_history`

---

## Header Information

Get asset header information (name, status, location, last visit date).

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/header
```

### Response

```json
{
  "data": {
    "asset_name": "AC Unit 001",
    "asset_code": "AC-001",
    "current_status": "operational",
    "status_label": "تشغيلي",
    "location": "Building A - Floor 2",
    "date_of_last_visit": "2024-01-15 10:30:00"
  }
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| asset_name | string | Name of the asset |
| asset_code | string | Unique code of the asset |
| current_status | string | Current status (operational, under_maintenance, inactive, damaged, decommissioned) |
| status_label | string | Localized status label |
| location | string | Asset location |
| date_of_last_visit | string | Date and time of the last completed visit (Y-m-d H:i:s format) |

---

## Overview (Basic Asset Data)

Get basic asset information and specifications.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/overview
```

### Response

```json
{
  "data": {
    "equipment_name": "Air Conditioning Unit",
    "location_building": "Building A - Floor 2",
    "code": "AC-001",
    "specifications": "3.5 Ton Split Unit",
    "model": "LG-3500",
    "serial_number": "SN123456789",
    "voltage": "220V",
    "frequency": "50Hz",
    "capacity_operating_pressure": "350 PSI",
    "manufacturer_address": "Seoul, South Korea",
    "internal_distributor": "ABC Distributors",
    "production_date": "2020-05-15",
    "delivery_installation_date": "2020-06-20",
    "manufacturer": "LG Electronics",
    "asset_type": "HVAC System"
  }
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| equipment_name | string | Name of the equipment |
| location_building | string | Location/building where asset is installed |
| code | string | Asset code |
| specifications | string | Technical specifications |
| model | string | Equipment model |
| serial_number | string | Serial number |
| voltage | string | Electrical voltage |
| frequency | string | Frequency |
| capacity_operating_pressure | string | Capacity or operating pressure |
| manufacturer_address | string | Manufacturer address |
| internal_distributor | string | Internal distributor name |
| production_date | string | Production date (Y-m-d format) |
| delivery_installation_date | string | Delivery and installation date (Y-m-d format) |
| manufacturer | string | Manufacturer name |
| asset_type | string | Type of asset |

---

## Maintenance History (Visits)

Get all maintenance visits associated with the asset.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/visits
```

### Response

```json
{
  "data": [
    {
      "visit_id": 123,
      "visit_number": "VIS-2024-001",
      "visit_type": "preventive",
      "visit_type_label": "صيانة وقائية",
      "visit_date": "2024-01-15 09:00:00",
      "completed_at": "2024-01-15 11:30:00",
      "technician": "Ahmed Ali, Mohammed Hassan",
      "technicians": [
        {
          "id": 5,
          "name": "Ahmed Ali"
        },
        {
          "id": 6,
          "name": "Mohammed Hassan"
        }
      ],
      "asset_condition_before": "Good condition, minor wear",
      "asset_condition_after": "Excellent condition after maintenance",
      "visit_report_number": 45,
      "report_status": "approved",
      "before_photos": [
        {
          "id": 101,
          "file_name": "before_001.jpg",
          "file_path": "/storage/reports/before_001.jpg",
          "file_type": "image"
        }
      ],
      "after_photos": [
        {
          "id": 102,
          "file_name": "after_001.jpg",
          "file_path": "/storage/reports/after_001.jpg",
          "file_type": "image"
        }
      ],
      "all_photos": [
        {
          "id": 101,
          "file_name": "before_001.jpg",
          "file_path": "/storage/reports/before_001.jpg",
          "file_type": "image",
          "attachment_type": "before"
        },
        {
          "id": 102,
          "file_name": "after_001.jpg",
          "file_path": "/storage/reports/after_001.jpg",
          "file_type": "image",
          "attachment_type": "after"
        }
      ]
    }
  ],
  "count": 15
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| visit_id | integer | Unique visit ID |
| visit_number | string | Visit number/identifier |
| visit_type | string | Type of visit (preventive, corrective, emergency, inspection) |
| visit_type_label | string | Localized visit type label |
| visit_date | string | Scheduled visit date (Y-m-d H:i:s format) |
| completed_at | string | Visit completion date (Y-m-d H:i:s format) |
| technician | string | Comma-separated list of technician names |
| technicians | array | Array of technician objects with id and name |
| asset_condition_before | string | Asset condition before the visit |
| asset_condition_after | string | Asset condition after the visit |
| visit_report_number | integer | Associated report ID |
| report_status | string | Report status (draft, submitted, approved, rejected) |
| before_photos | array | Array of before photos |
| after_photos | array | Array of after photos |
| all_photos | array | Array of all photos with attachment type |

---

## Breakdowns & Failures Log

Get all breakdowns and failures (emergency visits) for the asset.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/breakdowns
```

### Response

```json
{
  "data": [
    {
      "fault_date": "2024-01-10 14:30:00",
      "fault_type": "Compressor Failure",
      "fault_description": "Compressor stopped working, no cooling",
      "fault_cause": "Overheating due to blocked condenser",
      "repair_time": "2024-01-10 16:45:00",
      "visit_id": 120,
      "visit_number": "VIS-2024-EMG-001",
      "report_id": 42,
      "work_performed": "Replaced compressor, cleaned condenser, refilled refrigerant"
    }
  ],
  "count": 3
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| fault_date | string | Date and time of the fault (Y-m-d H:i:s format) |
| fault_type | string | Type of fault/failure |
| fault_description | string | Description of the fault |
| fault_cause | string | Root cause of the fault (if identified) |
| repair_time | string | Date and time when repair was completed (Y-m-d H:i:s format) |
| visit_id | integer | Associated visit ID |
| visit_number | string | Visit number |
| report_id | integer | Associated report ID |
| work_performed | string | Work performed to fix the issue |

### Notes

- This log is automatically generated from emergency visits
- Only visits with `visit_type = 'emergency'` are included

---

## Spare Parts Usage Log

Get all spare parts and materials used for the asset across all visits.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/spare-parts
```

### Response

```json
{
  "data": [
    {
      "id": 201,
      "item_name": "Compressor Oil",
      "category": "Consumable",
      "quantity": 2.5,
      "unit_of_measure": "Liters",
      "associated_visit": {
        "id": 123,
        "visit_number": "VIS-2024-001",
        "visit_date": "2024-01-15 09:00:00"
      },
      "is_within_contract": false,
      "cost": 150.00,
      "unit_price": 60.00,
      "supplier": null,
      "source": "purchase",
      "approval_status": "approved",
      "notes": "High-quality compressor oil"
    },
    {
      "id": 202,
      "item_name": "Air Filter",
      "category": "Spare Part",
      "quantity": 1,
      "unit_of_measure": "Piece",
      "associated_visit": {
        "id": 123,
        "visit_number": "VIS-2024-001",
        "visit_date": "2024-01-15 09:00:00"
      },
      "is_within_contract": true,
      "cost": 45.00,
      "unit_price": 45.00,
      "supplier": "ABC Suppliers",
      "source": "stock",
      "approval_status": "approved",
      "notes": null
    }
  ],
  "count": 25
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| id | integer | Spare part record ID |
| item_name | string | Name of the spare part/item |
| category | string | Category (Consumable or Spare Part) |
| quantity | float | Quantity used |
| unit_of_measure | string | Unit of measurement |
| associated_visit | object | Visit information where part was used |
| associated_visit.id | integer | Visit ID |
| associated_visit.visit_number | string | Visit number |
| associated_visit.visit_date | string | Visit date |
| is_within_contract | boolean | Whether the part is covered by contract |
| cost | float | Total cost |
| unit_price | float | Unit price |
| supplier | string | Supplier name (if available) |
| source | string | Source (stock, customer, purchase, warranty) |
| approval_status | string | Approval status (pending, approved, rejected, ordered) |
| notes | string | Additional notes |

---

## Asset KPIs

Get key performance indicators for the asset.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/kpis
```

### Response

```json
{
  "data": {
    "visits_performed": 12,
    "visits_remaining": 3,
    "total_visits": 15,
    "breakdowns_count": 2,
    "mtbf_days": 45.5,
    "total_maintenance_cost": 12500.00,
    "average_cost_per_visit": 1041.67
  }
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| visits_performed | integer | Number of completed visits |
| visits_remaining | integer | Number of scheduled/planned visits |
| total_visits | integer | Total number of visits |
| breakdowns_count | integer | Number of breakdowns (emergency visits) |
| mtbf_days | float\|null | Mean Time Between Failures in days (calculated if 2+ breakdowns) |
| total_maintenance_cost | float | Total maintenance cost across all visits |
| average_cost_per_visit | float | Average cost per completed visit |

### KPI Calculations

- **Visits Performed:** Count of visits with status = 'completed'
- **Visits Remaining:** Count of visits with status = 'scheduled' or 'in_progress'
- **Breakdowns Count:** Count of visits with visit_type = 'emergency'
- **MTBF (Mean Time Between Failures):** Average days between emergency visits (calculated if 2+ breakdowns exist)
- **Total Maintenance Cost:** Sum of total_cost from all visit reports
- **Average Cost Per Visit:** Total cost divided by number of completed visits

---

## Photos and Attachments

Get all photos and attachments organized by visit.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/photos
```

### Response

```json
{
  "data": [
    {
      "visit_id": 123,
      "visit_number": "VIS-2024-001",
      "visit_date": "2024-01-15 09:00:00",
      "attachments": [
        {
          "id": 101,
          "file_name": "before_001.jpg",
          "file_path": "/storage/reports/before_001.jpg",
          "file_type": "image",
          "mime_type": "image/jpeg",
          "file_size": 2048576,
          "attachment_type": "before",
          "uploaded_at": "2024-01-15 09:15:00"
        },
        {
          "id": 102,
          "file_name": "after_001.jpg",
          "file_path": "/storage/reports/after_001.jpg",
          "file_type": "image",
          "mime_type": "image/jpeg",
          "file_size": 2156432,
          "attachment_type": "after",
          "uploaded_at": "2024-01-15 11:20:00"
        }
      ],
      "before_photos": [
        {
          "id": 101,
          "file_name": "before_001.jpg",
          "file_path": "/storage/reports/before_001.jpg",
          "file_type": "image",
          "mime_type": "image/jpeg",
          "file_size": 2048576,
          "attachment_type": "before",
          "uploaded_at": "2024-01-15 09:15:00"
        }
      ],
      "after_photos": [
        {
          "id": 102,
          "file_name": "after_001.jpg",
          "file_path": "/storage/reports/after_001.jpg",
          "file_type": "image",
          "mime_type": "image/jpeg",
          "file_size": 2156432,
          "attachment_type": "after",
          "uploaded_at": "2024-01-15 11:20:00"
        }
      ]
    }
  ],
  "count": 5
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| visit_id | integer | Visit ID |
| visit_number | string | Visit number |
| visit_date | string | Visit date |
| attachments | array | All attachments for this visit |
| before_photos | array | Before photos (attachment_type = 'before') |
| after_photos | array | After photos (attachment_type = 'after') |

### Attachment Object Fields

| Field | Type | Description |
|-------|------|-------------|
| id | integer | Attachment ID |
| file_name | string | Original file name |
| file_path | string | Storage path to the file |
| file_type | string | File type (image, document, etc.) |
| mime_type | string | MIME type |
| file_size | integer | File size in bytes |
| attachment_type | string | Type (before, after, or other) |
| uploaded_at | string | Upload timestamp |

---

## Timeline

Get chronological timeline of all events related to the asset.

### Endpoint

```
GET /api/maintenance/projects/{projectId}/assets/{assetId}/history/timeline
```

### Response

```json
{
  "data": [
    {
      "event_type": "asset_created",
      "date": "2020-06-20 10:00:00",
      "description": "Asset created",
      "user": "Admin User",
      "user_id": 1
    },
    {
      "event_type": "status_change",
      "date": "2020-06-20 10:05:00",
      "description": "Status changed from inactive to operational",
      "details": {
        "old_status": "inactive",
        "new_status": "operational",
        "reason": "Initial setup completed"
      },
      "user": "Admin User",
      "user_id": 1
    },
    {
      "event_type": "visit_scheduled",
      "date": "2024-01-15 08:00:00",
      "description": "Visit #VIS-2024-001 scheduled (preventive)",
      "visit_id": 123,
      "visit_number": "VIS-2024-001"
    },
    {
      "event_type": "visit_started",
      "date": "2024-01-15 09:00:00",
      "description": "Visit #VIS-2024-001 started",
      "visit_id": 123,
      "visit_number": "VIS-2024-001"
    },
    {
      "event_type": "spare_part_used",
      "date": "2024-01-15 09:30:00",
      "description": "Spare part used: Compressor Oil (Qty: 2.5)",
      "visit_id": 123,
      "spare_part_id": 201
    },
    {
      "event_type": "attachment_uploaded",
      "date": "2024-01-15 09:15:00",
      "description": "Attachment uploaded: before_001.jpg",
      "visit_id": 123,
      "attachment_id": 101,
      "attachment_type": "before"
    },
    {
      "event_type": "visit_completed",
      "date": "2024-01-15 11:30:00",
      "description": "Visit #VIS-2024-001 completed",
      "visit_id": 123,
      "visit_number": "VIS-2024-001"
    },
    {
      "event_type": "report_submitted",
      "date": "2024-01-15 12:00:00",
      "description": "Report submitted for visit #VIS-2024-001",
      "visit_id": 123,
      "report_id": 45
    },
    {
      "event_type": "report_approved",
      "date": "2024-01-15 14:00:00",
      "description": "Report approved for visit #VIS-2024-001",
      "visit_id": 123,
      "report_id": 45,
      "user": "Manager Name",
      "user_id": 2
    }
  ],
  "count": 50
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| event_type | string | Type of event (see Event Types below) |
| date | string | Event date and time (Y-m-d H:i:s format) |
| description | string | Human-readable event description |
| user | string\|null | User who performed the action (if applicable) |
| user_id | integer\|null | User ID (if applicable) |
| details | object | Additional event details (for status_change events) |
| visit_id | integer\|null | Associated visit ID (if applicable) |
| visit_number | string\|null | Visit number (if applicable) |
| report_id | integer\|null | Associated report ID (if applicable) |
| attachment_id | integer\|null | Attachment ID (if applicable) |
| attachment_type | string\|null | Attachment type (if applicable) |
| spare_part_id | integer\|null | Spare part ID (if applicable) |

### Event Types

| Event Type | Description |
|------------|-------------|
| `asset_created` | Asset was created |
| `status_change` | Asset status was changed |
| `visit_scheduled` | A visit was scheduled |
| `visit_started` | A visit was started |
| `visit_completed` | A visit was completed |
| `report_submitted` | A visit report was submitted |
| `report_approved` | A visit report was approved |
| `spare_part_used` | A spare part was used in a visit |
| `attachment_uploaded` | An attachment was uploaded to a report |

### Timeline Ordering

Events are sorted chronologically in descending order (most recent first).

---

## Error Responses

All endpoints may return the following error responses:

### 404 Not Found

```json
{
  "message": "Asset not found in this project"
}
```

### 500 Internal Server Error

```json
{
  "message": "Error fetching [resource]",
  "error": "Detailed error message"
}
```

### 401 Unauthorized

```json
{
  "message": "Unauthenticated."
}
```

### 403 Forbidden

```json
{
  "message": "This action is unauthorized."
}
```

---

## Usage Examples

### Example 1: Get Complete Asset History

```bash
curl -X GET "https://api.example.com/api/maintenance/projects/1/assets/5/maintenance-history" \
  -H "Authorization: Bearer {token}" \
  -H "Accept: application/json"
```

### Example 2: Get Only Maintenance Visits

```bash
curl -X GET "https://api.example.com/api/maintenance/projects/1/assets/5/history/visits" \
  -H "Authorization: Bearer {token}" \
  -H "Accept: application/json"
```

### Example 3: Get Asset KPIs

```bash
curl -X GET "https://api.example.com/api/maintenance/projects/1/assets/5/history/kpis" \
  -H "Authorization: Bearer {token}" \
  -H "Accept: application/json"
```

### Example 4: Get Breakdowns Only

```bash
curl -X GET "https://api.example.com/api/maintenance/projects/1/assets/5/history/breakdowns" \
  -H "Authorization: Bearer {token}" \
  -H "Accept: application/json"
```

---

## Notes

1. **Performance:** The comprehensive history endpoint loads all data at once. For better performance, use individual endpoints when you only need specific data.

2. **Breakdowns:** The breakdown log is automatically generated from emergency visits. Ensure visits are properly marked as 'emergency' type.

3. **Photos:** Photos are organized by visit and can be filtered by `attachment_type` ('before' or 'after').

4. **Timeline:** The timeline includes all events related to the asset, sorted chronologically (most recent first).

5. **KPIs:** MTBF (Mean Time Between Failures) is only calculated if there are 2 or more breakdowns.

6. **Permissions:** All endpoints require the `maintenance.project_assets.view_history` permission.

---

## Support

For issues or questions, please contact the development team or refer to the main API documentation.

