Maintenances Controller Documentation
File: /controllers/maintenances.php
Purpose: Manages maintenance requests, tracking products sent for repair/warranty service
Last Updated: December 20, 2024
Total Functions: 13
Lines of Code: ~491
---
๐ Overview
The Maintenances Controller manages the complete lifecycle of maintenance requests for products under warranty or repair. It handles:
- โข Creation and tracking of maintenance cases
- โข Product fault reporting and documentation
- โข Maintenance center and branch management
- โข Customer communication through comments
- โข Status tracking (warranty vs. repair)
- โข Integration with supplier warranty services
- โข Receipt and case management workflow
Primary Functions
- โ Create and manage maintenance requests
- โ Track maintenance cases and statuses
- โ Manage maintenance centers
- โ Handle branch operations
- โ Customer comment system
- โ Dynamic data entry with AJAX
- โ Status change tracking
- โ Product defect documentation
- โ Cost estimation and prepayment handling
- โ Invoice and purchase date tracking
Related Controllers
- โข maintenancesends.php - Shipment tracking
- โข maintenancesuppliers.php - Supplier management
- โข maintennanceArchiveController.php - Archive management
- โข supplierController.php - Supplier data
- โข clientController.php - Customer management
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **maintenances** | Main maintenance records | id, clientid, supplierid, branchid, productid, maintenancecenterid, maintenancecaseid, receiptnumber, defect, accessories, estimatedcost, prepaid, conditions, userid | |
| **maintenancecomments** | Comments on maintenance cases | id, maintenanceid, comments, userid, maintenancecommentdate, conditions | |
| **maintenancecases** | Maintenance case types | id, casename, maintenancecasedate, userid, conditions | |
| **maintenancecenters** | Service centers | id, centername, centerphone, centermobile, centeraddress, administrator, administratorphone, administratordebt, conditions |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer information | clientid, clientname, clientphone | |
| **supplier** | Supplier/manufacturer data | supplierid, suppliername | |
| **branch** | Branch locations | branchId, branchName, branchAddress, phone, mobile | |
| **product** | Product catalog | productId, productName | |
| **user** | System users | userid, employeename |
๐ Key Functions
1. Default Action - Add New Maintenance
Location: Lines 21-26
Purpose: Display form for creating new maintenance requests
Process Flow:
1. Assign current date and time to template
2. Set maintenance module flag for navigation
3. Display add form template
---
2. show() - Display All Maintenance Records
Location: Lines 26-36
Purpose: Show maintenance listing with filtering and search capabilities
Features:
- โข Authentication required
- โข Load all active maintenance cases for dropdown
- โข YouTube tutorial links integration
- โข DataTables AJAX integration via
showajax()
---
3. edit() - Edit Maintenance Record
Location: Lines 37-58
Purpose: Edit existing maintenance record with comments
Function Signature:
$id = filter_input(INPUT_GET, 'id');
$del = filter_input(INPUT_GET, 'del');
Process Flow:
1. Load maintenance data by ID
2. Get employee name from user table
3. Parse datetime for separate date/time fields
4. Load associated comments with employee names
5. Assign data to edit template
---
4. savedata() - Save/Update Maintenance Record
Location: Lines 213-298
Purpose: Main function for saving maintenance requests with comments
Function Signature:
function savedata()
Process Flow:
1. Validate and sanitize all input fields
2. Create new maintenance record or update existing
3. Set default maintenance case ID and policy ID
4. Loop through comments and save each one
5. Return JSON response with record ID
Key Fields Handled:
- โข Product ID, Supplier ID, Branch ID, Client ID
- โข Maintenance center and case assignments
- โข Receipt number and date/time
- โข Defect description and accessories
- โข Estimated cost and prepaid amount
- โข Purchase date, invoice number, and date
- โข Warranty vs. repair flag (
maintorguar)
Comment Handling:
for ($i = 1; $i <= $commentitr; $i++) {
$maintenancecommentid = filter_input(INPUT_POST, 'maintenancecommentid_' . $i);
$comments = filter_input(INPUT_POST, 'comments_' . $i);
// Save each comment with maintenance ID
}
---
5. savecomment() - Individual Comment Management
Location: Lines 86-112
Purpose: Save or update individual comments via AJAX
Function Signature:
function savecomment()
Process Flow:
1. Get comment data and maintenance ID
2. Create new comment or update existing
3. Return JSON with comment ID and selection data
---
6. savecase() - Maintenance Case Management
Location: Lines 114-137
Purpose: Create or update maintenance case types
Function Signature:
function savecase()
Process Flow:
1. Validate case name input
2. Create new case or update existing
3. Return JSON response for dynamic dropdown updates
---
7. savebranch() - Branch Management
Location: Lines 140-167
Purpose: Manage branch information for maintenance services
Function Signature:
function savebranch()
Process Flow:
1. Collect branch details (name, phone, mobile, address)
2. Insert new branch or update existing via raw SQL
3. Return JSON with branch data for dropdown
Database Operation:
R::exec("INSERT INTO `branch`(`branchName`, `branchDate`, `phone`, `mobile`, `branchNo`, `branchAddress`)
VALUES ('$branchName','$date','$phone','$mobile','$branchNo','$branchAddress')");
---
8. savecenter() - Maintenance Center Management
Location: Lines 170-210
Purpose: Manage maintenance service centers
Function Signature:
function savecenter()
Process Flow:
1. Collect center information and administrator details
2. Create or update maintenance center record
3. Optionally link to specific maintenance request
4. Return JSON response
Center Data Fields:
- โข Center name, phone, mobile, address
- โข Administrator name, phone, debt tracking
---
9. showajax() - DataTables AJAX Handler
Location: Lines 301-436
Purpose: Provide server-side processing for maintenance listing table
Function Signature:
function showajax()
Filter Parameters:
- โข
start_date/end_date- Date range filtering - โข
del- Show deleted records - โข
data1- Supplier ID filter - โข
data2- Client ID filter - โข
data3- Branch ID filter - โข
data4- Warranty/repair type filter - โข
data5- Case ID filter
Process Flow:
1. Build dynamic WHERE clause based on filters
2. Add search functionality across multiple columns
3. Apply sorting and pagination
4. Join with related tables for display data
5. Generate action buttons based on record status
SQL Query Structure:
SELECT maintenances.*, employeename, clientname, suppliername, branchName, centername
FROM maintenances
LEFT JOIN user ON maintenances.userid = user.userid
LEFT JOIN client ON maintenances.clientid = client.clientid
LEFT JOIN supplier ON maintenances.supplierid = supplier.supplierid
LEFT JOIN branch ON maintenances.branchid = branch.branchId
LEFT JOIN maintenancecenters ON maintenances.maintenancecenterid = maintenancecenters.id
Special Features:
- โข Product name concatenation for multiple products
- โข Dynamic maintenance center assignment interface
- โข Conditional action buttons based on warranty type
- โข Comment editing interface in table cells
---
10. changecase() - Update Maintenance Case
Location: Lines 440-451
Purpose: Change maintenance case status via AJAX
Function Signature:
function changecase()
---
11. changecenter() - Update Maintenance Center
Location: Lines 454-465
Purpose: Assign maintenance center to request
Function Signature:
function changecenter()
---
12. updatecomment() - Update Comment Content
Location: Lines 467-486
Purpose: Update comment text via inline editing
Function Signature:
function updatecomment()
---
๐ Workflows
Workflow 1: New Maintenance Request Creation
---
Workflow 2: Maintenance Case Management
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) | Default action | Display add maintenance form | |
| `do=show` | show() | Display maintenance listing | |
| `do=edit` | edit() | Edit maintenance record | |
| `do=savedata` | savedata() | Save/update maintenance | |
| `do=showajax` | showajax() | DataTables AJAX data | |
| `do=savecomment` | savecomment() | Save individual comment | |
| `do=savecase` | savecase() | Save maintenance case type | |
| `do=savebranch` | savebranch() | Save branch information | |
| `do=savecenter` | savecenter() | Save maintenance center | |
| `do=changecase` | changecase() | Update case status | |
| `do=changecenter` | changecenter() | Update center assignment | |
| `do=updatecomment` | updatecomment() | Update comment text | |
| `do=appentcomment` | append template | Append comment form |
๐งฎ Calculation Methods
Cost Tracking
// Estimated cost calculation
$estimatedcost = filter_input(INPUT_POST, 'estimatedcost');
$prepaid = filter_input(INPUT_POST, 'prepaid');
// Remaining cost calculation (done on frontend)
$remaining = $estimatedcost - $prepaid;
Maintenance Center Debt
// Center administrator debt tracking
$administratordebt = filter_input(INPUT_POST, 'administratordebt');
// Stored for accounting purposes
---
๐ Security & Permissions
Input Sanitization
// All inputs properly filtered
$productId = filter_input(INPUT_POST, 'product');
$supplierid = filter_input(INPUT_POST, 'supplier');
$receiptnumber = filter_input(INPUT_POST, 'receiptnumber');
Authentication
- โข All modification actions require authentication
- โข Session-based user tracking
- โข User ID stored with all records
Data Validation
- โข Required field validation on frontend
- โข Exception handling for database operations
- โข Conditional logic based on user permissions
---
๐ Performance Considerations
Database Optimization
1. Indexes Needed:
- maintenances(clientid, maintenancedate)
- maintenances(supplierid, conditions)
- maintenancecomments(maintenanceid, conditions)
2. Query Optimization:
- JOINs limited to necessary tables
- Date filtering with proper indexing
- Conditional loading of comments
AJAX Performance
- โข Server-side pagination for large datasets
- โข Dynamic loading of related data
- โข Efficient search across multiple columns
---
๐ Common Issues & Troubleshooting
1. Maintenance Center Assignment Issues
Issue: Cannot assign center to warranty items
Cause: Logic prevents center assignment when maintorguar = 0
Solution: Check warranty flag before attempting assignment
2. Comment Update Problems
Issue: Comments not saving properly
Cause: Missing CSRF validation or session expiry
Debug:
SELECT * FROM maintenancecomments WHERE maintenanceid = [ID] ORDER BY id DESC;
3. Product Display Issues
Issue: Product names not showing correctly
Cause: Multiple product IDs stored as comma-separated string
Fix: Ensure proper parsing of product ID string:
$products = R::getAll("SELECT productName FROM product WHERE productId in (".$row['productid'].")");
4. Date/Time Handling
Issue: DateTime splitting errors
Cause: Inconsistent datetime format
Fix: Validate datetime before splitting:
$new_time = explode(" ", $maintenancedata['dateatime']);
if (count($new_time) >= 2) {
$smarty->assign('get_date', $new_time[0]);
$smarty->assign('get_time', $new_time[1]);
}
---
๐งช Testing Scenarios
Test Case 1: Basic Maintenance Creation
1. Create new maintenance request with all required fields
2. Verify record saved with proper user ID and timestamp
3. Check maintenance case assignment
4. Confirm comment association
Test Case 2: Warranty vs. Repair Workflow
1. Create warranty maintenance (maintorguar = 0)
2. Verify center assignment is disabled
3. Create repair maintenance (maintorguar = 1)
4. Verify center assignment interface appears
Test Case 3: Comment System
1. Add multiple comments to maintenance record
2. Edit existing comment via inline editing
3. Verify user tracking and timestamps
4. Test comment deletion (soft delete)
Test Case 4: AJAX Filtering
1. Test date range filtering
2. Filter by supplier, client, branch
3. Test search functionality
4. Verify pagination works correctly
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข maintenancesends.php - Shipment tracking
- โข Database Schema Documentation - Table relationships
- โข API Documentation - AJAX endpoints
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur