# Simple Manufacture Settings Controller Documentation

**File**: `/controllers/simpleManufactureSettingsController.php`  
**Purpose**: Manages manufacturing configuration, system settings, and production parameters  
**Last Updated**: December 19, 2024  
**Total Functions**: 4  
**Lines of Code**: ~217

---

## 📋 Overview

The Simple Manufacture Settings Controller manages core manufacturing configuration and system settings. It handles:
- Manufacturing system configuration
- Production warehouse settings
- Inventory reduction policies
- Manufacturing equation settings
- Order client configuration
- Pricing alert thresholds
- Task order naming conventions
- Database column precision for manufacturing quantities
- Menu property updates based on settings
- Production system parameters

### Primary Functions
- [x] Configure default manufacturing warehouse
- [x] Set inventory reduction policies
- [x] Enable/disable manufacturing equations
- [x] Configure order client settings
- [x] Set price alert thresholds
- [x] Customize task order terminology
- [x] Adjust database precision for quantities
- [x] Update system menu properties
- [x] Manage production parameters

### Related Controllers
- [productionExecutionController.php](productionExecutionController.md) - Manufacturing execution
- [productionOrderController.php](productionOrderController.md) - Production orders
- [taskOrderController.php](#) - Task order management
- [storeController.php](storeController.md) - Warehouse management
- [productController.php](productController.md) - Product configuration
- [programsettingsController.php](#) - General system settings
- [propertiesController.php](#) - System properties management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `simplemanufacturesetting` | Manufacturing configuration | `id`, `storeid`, `reducestoreamount`, `productsproductionequation`, `orderclient`, `lowOutPriceAlert`, `taskOrderName` |

### Related Tables (System Configuration)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `properties` | System menu properties | `propertyid`, `propertyname`, `propertyvalue` |
| `store` | Available warehouses | `storeid`, `storeName` |

### Affected Manufacturing Tables (Precision Updates)
| Table Name | Purpose | Precision Fields |
|------------|---------|------------------|
| `productionrateproduct` | BOM quantities | `quantity` |
| `taskorder` | Task order quantities | `num` |
| `taskorderproducts` | Task order materials | `quantity` |
| `productionexecution` | Production quantities | `num` |
| `productionexecutionoutput` | Output quantities | `num` |
| `productionexecutionproduct` | Material consumption | `quantity`, `actualquantity` |
| `productionexecutionwaste` | Waste quantities | `num` |
| `storemovement` | Inventory transfers | `transferproductamount` |
| `storedetail` | Inventory quantities | `productquantity` |
| `sizecolorstoredetail` | Variant inventory | `quantity` |
| `storereport` | Inventory history | `productquantity`, `productbefore`, `productafter` |
| `restaurantrawdestruction` | Restaurant waste | `quantity` |

---

## 🔧 Key Functions

### 1. **Default Display - Show Settings Form**
**Line**: 116  
**Purpose**: Displays the manufacturing settings configuration form

**Process Flow**:
```
┌─ Load Settings Form ─┐
│                      │
▼                      │
Get current settings ──┘
│ • Load simplemanufacturesetting record
│ • Get available warehouses
│ • Load YouTube training links
▼
Display settings form
│ • Manufacturing warehouse
│ • Inventory reduction setting
│ • Production equation setting
│ • Order client configuration
│ • Price alert threshold
│ • Task order naming
```

---

### 2. **update() - Save Manufacturing Settings**
**Line**: 131  
**Purpose**: Updates manufacturing settings and applies database changes

**Parameters**:
- `$_POST['storeid']` - Default manufacturing warehouse
- `$_POST['reducestoreamount']` - Allow inventory reduction (0/1)
- `$_POST['manufacturing']` - Enable production equations (0/1)
- `$_POST['orderclient']` - Order client setting
- `$_POST['lowOutPriceAlert']` - Low price alert threshold
- `$_POST['taskOrderName']` - Task order terminology (1=Order, 0=Work Order)
- `$_POST['holePartNoOfDigits']` - Whole number digits for precision
- `$_POST['fractionPartNoOfDigits']` - Decimal digits for precision

**Process Flow**:
```
┌─ Update Settings ─┐
│                   │
▼                   │
Check task order name change ──┘
│
▼
Update menu properties if changed
│ • Change "طلبية" (Order) to "أمر شغل" (Work Order)
│ • Clear cached header
▼
Save manufacturing settings
│ • Update simplemanufacturesetting record
│ • Save all configuration values
▼
Apply database precision changes
│ • Calculate DECIMAL column specification
│ • ALTER TABLE statements for all manufacturing tables
│ • Update quantity field precisions
```

**Code Example**:
```php
// Update task order terminology
if ($simplesetting->taskOrderName != $taskOrderName) {
    $myProperities = $myProperitiesRecord->load(309);
    switch ($taskOrderName) {
        case 1:
            $myProperities->propertyname = "طلبية";  // Order
            break;
        default:
            $myProperities->propertyname = "أمر شغل";  // Work Order
            break;
    }
    $myProperitiesRecord->update($myProperities);
    
    // Clear cached header
    $fh = fopen('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html', 'w');
    fclose($fh);
}
```

---

### 3. **Database Precision Update**
**Line**: 172-198  
**Purpose**: Updates database column precision for manufacturing quantities

**Process Flow**:
```
┌─ Database Precision Update ─┐
│                             │
▼                             │
Validate precision parameters ──┘
│ • Ensure positive values
│ • Set defaults if empty
▼
Calculate column specification
│ • Total digits = whole + fraction
│ • Format: DECIMAL(total, fraction)
▼
Execute ALTER TABLE statements
│ • Production tables
│ • Store/inventory tables  
│ • Execution tables
│ • Report tables
```

**SQL Examples**:
```sql
-- Example with 8 whole digits, 2 fraction digits = DECIMAL(10,2)
ALTER TABLE `productionrateproduct` CHANGE `quantity` `quantity` DECIMAL(10,2) NOT NULL;
ALTER TABLE `storedetail` CHANGE `productquantity` `productquantity` DECIMAL(10,2) NOT NULL;
ALTER TABLE `productionexecution` CHANGE `num` `num` DECIMAL(10,2) NOT NULL;
```

---

### 4. **Menu Property Management**
**Line**: 143-156  
**Purpose**: Updates system menu properties based on manufacturing settings

**Process Flow**:
```
┌─ Menu Property Update ─┐
│                        │
▼                        │
Check if task order name changed ──┘
│
▼
Update properties table
│ • Property ID 309 = Task order menu text
│ • Value 1 = "طلبية" (Order)
│ • Value 0 = "أمر شغل" (Work Order)
▼
Clear user header cache
│ • Force menu regeneration
│ • Update user interface
```

---

## 🔄 Business Logic Flow

### Manufacturing Configuration Workflow

```
┌─ System Setup ─┐
│                │
▼                │
Manufacturing Settings ──┘
│ • Select default warehouse
│ • Configure inventory policies
│ • Set production parameters
│ • Define quantity precisions
▼
┌─ Menu Customization ─┐
│ • Set task order terminology │
│ • Update user interface       │
│ • Apply language preferences  │
└────────────────────────────────┘
│
▼
┌─ Database Optimization ─┐
│ • Set quantity precision     │
│ • Optimize storage space     │
│ • Ensure calculation accuracy │
└─────────────────────────────────┘
│
▼
┌─ Production Ready ─┐
│ • All settings configured │
│ • Database optimized      │
│ • User interface updated  │
└───────────────────────────┘
```

### Configuration Dependencies

```
Manufacturing Settings
├── Warehouse Configuration
│   ├── Default production warehouse
│   └── Inventory reduction policies
├── Production Parameters
│   ├── Enable production equations
│   ├── Order client settings
│   └── Price alert thresholds
├── User Interface
│   ├── Task order terminology
│   └── Menu properties
└── Database Schema
    ├── Quantity precision
    └── Column specifications
```

---

## ⚠️ Common Issues

### 1. **Database Precision Changes Fail**
**Symptoms**: ALTER TABLE statements fail during precision update
**Causes**:
- Existing data exceeds new precision limits
- Database permissions insufficient
- Concurrent transactions in progress

**Solutions**:
- Validate existing data before precision changes
- Ensure adequate database privileges
- Perform changes during maintenance windows

### 2. **Menu Cache Not Clearing**
**Symptoms**: Menu terminology doesn't update after settings change
**Causes**:
- Cache file permissions
- Web server write access issues
- Session-specific cache conflicts

**Solutions**:
- Verify cache directory permissions
- Clear all user cache files
- Restart web server if needed

### 3. **Settings Not Saving**
**Symptoms**: Configuration changes don't persist
**Causes**:
- Database connection issues
- Missing required fields
- Validation errors

**Solutions**:
- Check database connectivity
- Validate all required parameters
- Add error logging for diagnostics

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Database configuration
- `../public/include_dao.php` - Data access objects

### Required DAOs
- `SimplemanufacturesettingDAO` - Settings data access
- `PropertiesDAO` - Menu properties management
- `StoreDAO` - Warehouse information

### File System Dependencies
- Cache directory: `../temp__cashedheader/`
- Cache file pattern: `cashedheader_{dbname}_{userid}.html`
- Write permissions required for cache management

### Session Variables
- `$_SESSION['dbname']` - Database name for cache file naming
- `$_SESSION['userid']` - User ID for personalized cache

---

## ⚙️ Configuration Options

### Manufacturing Settings
| Setting | Purpose | Values |
|---------|---------|--------|
| `storeid` | Default production warehouse | Store ID from stores table |
| `reducestoreamount` | Allow negative inventory | 0=No, 1=Yes |
| `productsproductionequation` | Enable production equations | 0=Disabled, 1=Enabled |
| `orderclient` | Order client configuration | Client handling mode |
| `lowOutPriceAlert` | Low price alert threshold | Numeric threshold value |
| `taskOrderName` | Task order terminology | 0=Work Order, 1=Order |

### Database Precision Settings
| Field | Purpose | Default | Range |
|-------|---------|---------|-------|
| `holePartNoOfDigits` | Whole number digits | 8 | 1-15 |
| `fractionPartNoOfDigits` | Decimal digits | 2 | 0-8 |

### Precision Impact
```
Precision Setting: 8,2 → DECIMAL(10,2)
- Maximum value: 99999999.99
- Storage: 5 bytes per value
- Calculation accuracy: 2 decimal places

Precision Setting: 10,4 → DECIMAL(14,4)  
- Maximum value: 9999999999.9999
- Storage: 7 bytes per value
- Calculation accuracy: 4 decimal places
```

---

## 🎛️ System Integration Points

### Menu System Integration
- Property ID 309: Task order menu text
- Dynamic menu generation based on settings
- Localized terminology support
- User-specific cache management

### Manufacturing System Integration
- Default warehouse for production orders
- Inventory policy enforcement
- Production equation availability
- Quantity precision standardization

### Database Schema Management
- Dynamic column specification updates
- Cross-table precision consistency
- Storage optimization based on business needs
- Backwards compatibility maintenance

---

**Manufacturing Concepts Covered**: Manufacturing Configuration, System Settings Management, Database Precision Control, Menu Customization, Inventory Policy Configuration, Production Parameter Management, User Interface Customization, Schema Optimization