# Setting Operation Controller Documentation

**File**: `/controllers/settingOperationController.php`  
**Purpose**: Manages manufacturing operation settings including workstations, assets, and worker configurations  
**Last Updated**: December 20, 2024  
**Total Functions**: 8 main functions + 6 utility functions  
**Lines of Code**: ~400

---

## 📋 Overview

The Setting Operation Controller is a comprehensive manufacturing management module that handles the configuration of production operations. It manages:

- Manufacturing operation definitions and settings
- Workstation assignments and configurations
- Asset allocation to operations
- Worker count management per operation
- Real-time tracking of operation durations
- Operation start/stop controls
- Integration between workstations, workers, and assets

### Primary Functions
- [x] Create and manage manufacturing operations
- [x] Assign workstations to operations
- [x] Allocate assets to specific operations
- [x] Configure worker requirements per operation
- [x] Set standard operation times
- [x] Start/stop operation tracking
- [x] Edit and update operation configurations
- [x] Delete operations with dependency checks

### Related Controllers
- [workstationController.php](#) - Workstation management
- [assetController.php](assetController.md) - Asset management
- [employeeController.php](employeeController.md) - Employee management
- [productionOrderController.php](productionOrderController.md) - Production planning
- [productionExecutionController.php](productionExecutionController.md) - Production tracking

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **settingoperation** | Manufacturing operation configurations | settingOperationID, settingOperationName, workStationID, assetesID, workersNo, realTime, conditions, operationType |
| **workstation** | Manufacturing workstations | workStationID, workStationName |
| **workstationworker** | Worker assignments to workstations | workstationworkerid, workstationid, workerid |
| **assets** | Manufacturing assets/equipment | assetsID, assetsName |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, username |
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |

### Key Relationships
```sql
-- Operation settings
settingoperation.workStationID -> workstation.workStationID
settingoperation.assetesID -> assets.assetsID
settingoperation.userID -> user.userid

-- Worker assignments
workstationworker.workstationid -> workstation.workStationID
```

---

## 🔑 Key Functions

### 1. **Default Action (empty $do)** - Add Form Display
**Location**: Lines 112-131  
**Purpose**: Display form for creating new manufacturing operations

**Process Flow**:
1. Check user authentication
2. Load all workstations via `getWorkStation()`
3. Get worker count via `getworkersNo()`
4. Load all assets via `getAsetesName()`
5. Display add form with all reference data

**Template Variables**:
- `$allWorkStation` - Available workstations
- `$workerNumber` - Worker count for selected workstation
- `$allAsetes` - Available assets

---

### 2. **add ($do == "add")** - Create Operation
**Location**: Lines 134-145 (function at 281-311)  
**Purpose**: Create new manufacturing operation with all configurations

**Function Signature**:
```php
function add()
```

**Process Flow**:
1. Extract form data from POST
2. Set operation defaults (conditions = 0, operationType = 1)
3. Set current user and date
4. Insert operation via DAO
5. Redirect to success page

**Form Fields**:
- `settingOperationName1` - Operation name
- `workstationid` - Assigned workstation ID
- `realTime1` - Standard operation time
- `assetesID1` - Required asset ID
- `workersNo1` - Number of workers needed

**Database Operation**:
```php
$settingOperation->settingOperationName = $settingOperationName;
$settingOperation->workStationID = $workStationID;
$settingOperation->realTime = $realTime;
$settingOperation->assetesID = $assetesID;
$settingOperation->workersNo = $workersNo;
$settingOperation->operationType = 1;
$settingOperation->conditions = 0;
$settingOperation->userID = $_SESSION['userid'];
$settingOperation->operationDate = date('Y-m-d');

$settingOperationDAO->insert($settingOperation);
```

---

### 3. **show ($do == "show")** - Display Operations List
**Location**: Lines 148-162 (function at 315-323)  
**Purpose**: Display all manufacturing operations with workstation details

**Function Signature**:
```php
function showAllDatat()
```

**Process Flow**:
1. Load YouTube tutorial links
2. Query all operations with workstation join via `queryAllWithWorkstation()`
3. Display operations list with edit/delete options

**Template Variables**:
- `$youtubes` - Tutorial video links
- `$all` - Operations data with workstation information

---

### 4. **edit ($do == "edit")** - Edit Form Display
**Location**: Lines 165-186 (function at 325-336)  
**Purpose**: Display edit form for existing operation

**Parameters**:
- `id` - Operation ID to edit

**Process Flow**:
1. Load workstations and assets for dropdowns
2. Load operation data via `load($id)`
3. Display edit form with pre-filled data

**Function Signature**:
```php
function edit()
```

---

### 5. **update ($do == "update")** - Update Operation
**Location**: Lines 189-200 (function at 338-369)  
**Purpose**: Update existing manufacturing operation

**Function Signature**:
```php
function update()
```

**Process Flow**:
1. Extract form data including operation ID
2. Load existing operation object
3. Update all fields except ID
4. Save updated operation
5. Redirect to success

**Form Fields**:
- `settingOperationID` - Operation ID (hidden)
- `settingOperationName` - Updated operation name
- `workStationID` - Updated workstation assignment
- `workersNo` - Updated worker count
- `assetesID` - Updated asset assignment
- `realTime` - Updated standard time

---

### 6. **stop ($do == "stop")** - Toggle Operation Status
**Location**: Lines 201-209 (function at 371-387)  
**Purpose**: Start or stop operation (toggle active status)

**Parameters**:
- `id` - Operation ID to toggle

**Function Signature**:
```php
function stopOperation()
```

**Process Flow**:
1. Load operation by ID
2. Toggle conditions field (0 ↔ 1)
3. Update operation status
4. Redirect to success

**Status Logic**:
```php
if ($settingOperation->conditions == 0) {
    $settingOperation->conditions = 1; // Stop operation
} elseif ($settingOperation->conditions == 1) {
    $settingOperation->conditions = 0; // Start operation
}
```

---

### 7. **delete ($do == "delete")** - Delete Operation
**Location**: Lines 212-225 (function at 389-398)  
**Purpose**: Permanently delete manufacturing operation

**Parameters**:
- `id` - Operation ID to delete

**Function Signature**:
```php
function delete()
```

**Process Flow**:
1. Check user authentication
2. Delete operation via DAO
3. Redirect to success page

---

## 🔄 Workflows

### Workflow 1: Manufacturing Operation Creation
```
┌─────────────────────────────────────────────────────────────┐
│             START: Create Manufacturing Operation          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Reference Data                                     │
│     ├─→ Load all workstations                               │
│     ├─→ Get worker counts per workstation                   │
│     └─→ Load all available assets                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Creation Form                                   │
│     ├─→ Show workstation dropdown                           │
│     ├─→ Show asset selection                                │
│     ├─→ Input fields for operation details                  │
│     └─→ Worker count and time inputs                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Form Submission                                 │
│     ├─→ Validate required fields                            │
│     ├─→ Set operation defaults                              │
│     ├─→ Assign current user and date                        │
│     └─→ Insert into settingoperation table                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Confirmation                                            │
│     └─→ Redirect to success page                            │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Operation Management
```
┌─────────────────────────────────────────────────────────────┐
│                START: Manage Operations                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Operations List                                 │
│     ├─→ Query operations with workstation details           │
│     ├─→ Show operation name and configuration               │
│     ├─→ Display status (active/stopped)                    │
│     └─→ Provide action buttons (edit/stop/delete)          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Handle User Actions                                     │
│     │                                                       │
│     ├─→ EDIT: Load operation data and show edit form       │
│     │                                                       │
│     ├─→ STOP/START: Toggle operation conditions field      │
│     │                                                       │
│     └─→ DELETE: Remove operation from system               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Database                                         │
│     ├─→ Apply changes via DAO layer                         │
│     ├─→ Update audit fields (user, date)                   │
│     └─→ Maintain data integrity                             │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display operation creation form |
| `do=add` | `add()` | Create new manufacturing operation |
| `do=show` | `showAllDatat()` | Display list of all operations |
| `do=edit` | `edit()` | Display edit form for operation |
| `do=update` | `update()` | Update existing operation |
| `do=stop` | `stopOperation()` | Toggle operation start/stop status |
| `do=delete` | `delete()` | Delete operation permanently |

### Required Parameters by Action

**Edit Operation** (`do=edit`):
- `id` - Operation ID to edit

**Update Operation** (`do=update`):
- `settingOperationID` - Operation ID
- `settingOperationName` - Operation name
- `workStationID` - Workstation assignment
- `workersNo` - Worker count
- `assetesID` - Asset assignment
- `realTime` - Standard operation time

**Stop/Start Operation** (`do=stop`):
- `id` - Operation ID to toggle

**Delete Operation** (`do=delete`):
- `id` - Operation ID to delete

---

## 🧮 Calculation Methods

### Worker Count Calculation
```php
function getworkersNo() {
    global $workstationworkerEX;
    
    $allworkerhours = $workstationworkerEX->queryByWorkstationid($dropval);
    $workersNo = count($allworkerhours);
    return $workersNo;
}
```

### Operation Status Toggle
```php
// Toggle between active (0) and stopped (1)
if ($settingOperation->conditions == 0) {
    $settingOperation->conditions = 1; // Stop
} elseif ($settingOperation->conditions == 1) {
    $settingOperation->conditions = 0; // Start
}
```

### Standard Time Tracking
```php
// Store standard operation time for planning
$settingOperation->realTime = $realTime; // Duration in minutes/hours
```

---

## 🔒 Security & Permissions

### Access Control
```php
// Authentication required for all actions
include_once("../public/authentication.php");
```

### User Tracking
```php
// Track user who creates/modifies operations
$settingOperation->userID = $_SESSION['userid'];
$settingOperation->operationDate = date('Y-m-d');
```

### Input Sanitization
- **POST data validation**: All form inputs processed through PHP superglobals
- **SQL injection protection**: DAO layer handles parameterized queries
- **Session validation**: User session checked before database operations

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Recommended**:
   ```sql
   CREATE INDEX idx_settingop_workstation ON settingoperation(workStationID);
   CREATE INDEX idx_settingop_asset ON settingoperation(assetesID);
   CREATE INDEX idx_settingop_conditions ON settingoperation(conditions);
   CREATE INDEX idx_workstationworker_station ON workstationworker(workstationid);
   ```

2. **Query Performance**:
   - Use of extended DAO for JOIN queries (`queryAllWithWorkstation()`)
   - Efficient foreign key relationships
   - Minimal data loading per operation

3. **Memory Management**:
   - Lightweight operations list
   - Reference data loaded once per form display
   - No complex calculations or large datasets

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Reference Data**
**Issue**: Dropdowns show empty or incomplete data  
**Cause**: No workstations, assets, or workers configured

**Debug**:
```sql
-- Check workstations
SELECT * FROM workstation;

-- Check assets
SELECT * FROM assets;

-- Check worker assignments
SELECT w.*, ws.workStationName 
FROM workstationworker w
JOIN workstation ws ON w.workstationid = ws.workStationID;
```

### 2. **Operation Creation Fails**
**Issue**: Add operation returns error  
**Cause**: Missing required fields or invalid foreign key references

**Fix**:
```php
// Validate required fields before insert
if (empty($settingOperationName) || empty($workStationID)) {
    throw new Exception("Missing required fields");
}

// Verify foreign key exists
$workStation = $workStationDAO->load($workStationID);
if (!$workStation) {
    throw new Exception("Invalid workstation ID");
}
```

### 3. **Worker Count Not Updating**
**Issue**: Worker number shows old value  
**Cause**: `getworkersNo()` function not called with correct workstation ID

**Debug**:
```sql
-- Check worker assignments for workstation
SELECT COUNT(*) as worker_count 
FROM workstationworker 
WHERE workstationid = [WORKSTATION_ID];
```

### 4. **Operation Status Issues**
**Issue**: Start/stop operation not working  
**Cause**: Conditions field not properly toggled

**Fix**:
```php
// Ensure proper status handling
$operation = $settingOperationDAO->load($id);
if ($operation) {
    $operation->conditions = ($operation->conditions == 0) ? 1 : 0;
    $settingOperationDAO->update($operation);
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Complete Operation Setup
```
1. Create test workstation
2. Create test assets
3. Assign workers to workstation
4. Create new manufacturing operation
5. Verify all relationships are correct
6. Test operation start/stop functionality
```

### Test Case 2: Operation Management
```
1. Create multiple operations
2. Edit operation details
3. Change workstation assignments
4. Update worker requirements
5. Test delete functionality
6. Verify data consistency
```

### Test Case 3: Reference Data Validation
```
1. Create operation with invalid workstation ID
2. Test with missing assets
3. Verify error handling
4. Check foreign key constraints
5. Test with empty worker assignments
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [workstationController.php](#) - Workstation management
- [assetController.md](assetController.md) - Asset management
- [productionOrderController.md](productionOrderController.md) - Production planning
- [Database Schema Documentation](#) - Table relationships

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When manufacturing requirements change