# Maintenance Archive Controller Documentation

**File**: `/controllers/maintennanceArchiveController.php`  
**Purpose**: Displays archived maintenance records with filtering and search capabilities  
**Last Updated**: December 20, 2024  
**Total Functions**: 1  
**Lines of Code**: ~122

---

## 📋 Overview

The Maintenance Archive Controller provides a read-only interface for viewing completed maintenance records. It handles:
- Display of archived maintenance data
- Advanced filtering by receipt serial, client, and internal serial
- Integration with maintenance receipt system
- Branch-specific data filtering based on user session
- Complex data relationships for archive display

### Primary Functions
- [x] Display archived maintenance records
- [x] Filter by receipt serial numbers
- [x] Filter by internal serial numbers
- [x] Client-based filtering
- [x] Branch-specific data access control
- [x] Complex JOIN queries for data relationships

### Related Controllers
- [maintenances.php](maintenances.md) - Active maintenance requests
- [maintenancesends.php](maintenancesends.md) - Shipment tracking
- [maintenancesuppliers.php](maintenancesuppliers.md) - Supplier management

---

## 🗄️ Database Tables

### Primary Tables (Archive Data)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **m_comreceipt** | Maintenance receipt headers | receiptserial, branchid |
| **m_comreceiptdetail** | Maintenance receipt details | id, receiptserial, ourserial, clientid, branchid |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer information | clientid, clientname |
| **branch** | Branch information | branchId, branchName |
| **user** | System users | userid, employeename |

---

## 🔑 Key Functions

### 1. **Default Action (show)** - Archive Display
**Location**: Lines 58-116  
**Purpose**: Main archive viewing interface with filtering capabilities

**Function Signature**:
```php
if (empty($do)||$do=="all")
```

**Process Flow**:
1. Load dropdown data for filters (serials, clients)
2. Process filter parameters from POST request
3. Build dynamic query string based on filters
4. Execute complex JOIN query if filters applied
5. Display results via archive template

**Filter Parameters**:
- `receiptSerial` - Filter by maintenance receipt serial
- `ourserial` - Filter by internal tracking serial
- `clientid` - Filter by specific client

**Data Loading Process**:
```php
// Load all receipt serials for dropdown
$allReceiptSerials = $MComreceiptDetailEX->getRecitSerialsByBranchEX($_SESSION['branchId']);

// Load all internal serials for dropdown
$serials = $MComreceiptDetailEX->getSerialsByBranchEX($_SESSION['branchId']);

// Load all clients for dropdown
$clients = $MComreceiptDetailEX->getClientsByBranchEX($_SESSION['branchId']);
```

**Dynamic Query Building**:
```php
$queryString = '';

if(isset($receiptSerial) && $receiptSerial != -1) {
    $queryString .= ' AND  m_comreceipt.receiptserial = '.$receiptSerial;
}

if(isset($ourserial) && $ourserial != -1) {
    $queryString .= ' AND  m_comreceiptdetail.ourserial = "'.$ourserial.'"';
}

if(isset($clientid) && $clientid != -1) {
    $queryString .= ' AND  client.clientid = '.$clientid;
}

// Always filter by current branch
if($queryString != '') {
    $queryString .= ' AND  m_comreceiptdetail.branchid = '.$_SESSION['branchId'];
    $archiveData = $MComreceiptDetailEX->queryByBranchInDetailEX3($queryString);
}
```

---

## 🔄 Workflows

### Workflow 1: Archive Data Filtering
```
┌─────────────────────────────────────────────────────────────┐
│                START: View Archive Data                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Filter Options                                     │
│     - Get all receipt serials for branch                    │
│     - Load internal serials for branch                     │
│     - Fetch client list for branch                         │
│     - Populate filter dropdowns                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Apply User Filters                                      │
│     IF receiptSerial selected:                              │
│       └─→ Add receipt serial filter                        │
│     IF ourserial selected:                                  │
│       └─→ Add internal serial filter                       │
│     IF clientid selected:                                   │
│       └─→ Add client filter                                │
│     ALWAYS: Add branch filter from session                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Execute Archive Query                                   │
│     IF filters applied:                                     │
│       ├─→ Build complex JOIN query                         │
│       ├─→ Execute via Extended DAO method                  │
│       └─→ Return filtered archive data                     │
│     ELSE:                                                   │
│       └─→ Display empty archive interface                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Display Results                                         │
│     - Show filtered archive records                         │
│     - Maintain filter selections                           │
│     - Provide export/print options                         │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display archive interface |
| `do=all` | Default action | Same as empty - display archive |

### Filter Parameters (POST)
| Parameter | Type | Description |
|-----------|------|-------------|
| `receiptSerial` | Integer | Maintenance receipt serial number |
| `ourserial` | String | Internal tracking serial |
| `clientid` | Integer | Client ID for customer filter |

---

## 🔒 Security & Permissions

### Branch-Level Security
```php
// All data filtered by user's branch
$queryString .= ' AND  m_comreceiptdetail.branchid = '.$_SESSION['branchId'];
```

### Session-Based Access Control
- Archive data restricted to user's assigned branch
- Session validation required for data access
- No modification capabilities (read-only archive)

### Data Protection
- No update or delete operations available
- Historical data integrity maintained
- Branch isolation ensures data security

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Needed**:
   - `m_comreceiptdetail(branchid, receiptserial)`
   - `m_comreceiptdetail(branchid, ourserial)`
   - `m_comreceiptdetail(branchid, clientid)`
   - `m_comreceipt(receiptserial)`

2. **Query Performance**:
   - Complex JOINs may be slow with large datasets
   - Branch filtering reduces data volume
   - Consider pagination for large result sets

### Extended DAO Methods
```php
// Utilizes optimized Extended DAO methods
$allReceiptSerials = $MComreceiptDetailEX->getRecitSerialsByBranchEX($_SESSION['branchId']);
$archiveData = $MComreceiptDetailEX->queryByBranchInDetailEX3($queryString);
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Empty Archive Display**
**Issue**: No data shows even with valid filters  
**Cause**: Branch session not set or invalid branch ID

**Debug**:
```php
// Check session branch
echo "Current Branch: " . $_SESSION['branchId'];

// Verify branch has archive data
SELECT COUNT(*) FROM m_comreceiptdetail WHERE branchid = [branch_id];
```

### 2. **Slow Query Performance**
**Issue**: Archive queries taking too long  
**Cause**: Missing indexes on filter columns

**Fix**: Add compound indexes:
```sql
CREATE INDEX idx_receipt_branch ON m_comreceiptdetail(branchid, receiptserial);
CREATE INDEX idx_serial_branch ON m_comreceiptdetail(branchid, ourserial);
CREATE INDEX idx_client_branch ON m_comreceiptdetail(branchid, clientid);
```

### 3. **Filter Dropdown Issues**
**Issue**: Filter dropdowns not populating  
**Cause**: Extended DAO methods not returning data

**Debug**:
```php
// Check if Extended DAO methods exist and work
$testSerials = $MComreceiptDetailEX->getRecitSerialsByBranchEX($_SESSION['branchId']);
var_dump($testSerials);
```

### 4. **Cross-Branch Data Leakage**
**Issue**: Users seeing data from other branches  
**Cause**: Missing or incorrect branch filtering

**Fix**: Always verify branch filter is applied:
```php
if(!isset($_SESSION['branchId'])) {
    throw new Exception("Branch session not set");
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Archive Access
```
1. Login with valid branch assignment
2. Navigate to archive controller
3. Verify filter dropdowns populate with branch data
4. Confirm no data from other branches visible
```

### Test Case 2: Filter Functionality
```
1. Select receipt serial filter
2. Verify results match selected serial
3. Add client filter to receipt serial filter
4. Confirm combined filtering works correctly
```

### Test Case 3: Branch Isolation
```
1. Login as user from Branch A
2. Check available archive data
3. Login as user from Branch B
4. Verify different data set appears
```

### Test Case 4: Performance Testing
```
1. Load archive with large dataset
2. Apply various filter combinations
3. Measure query execution times
4. Verify acceptable performance levels
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [maintenances.php](maintenances.md) - Active maintenance management
- [Extended DAO Documentation](#) - Custom DAO method reference
- [Archive Data Structure](#) - Database schema for archive tables

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When performance optimization needed