# Production Order Controller Documentation

**File**: `/controllers/productionOrderController.php`  
**Purpose**: Manages production orders, work orders, manufacturing schedules, and production planning  
**Last Updated**: December 19, 2024  
**Total Functions**: 23  
**Lines of Code**: ~1,517

---

## 📋 Overview

The Production Order Controller is responsible for managing production orders and work orders in the ERP system. It handles:
- Creating and managing production orders (work orders)
- Production planning and scheduling
- Stage-based manufacturing workflows
- Raw material requirement planning (MRP)
- Production order lifecycle management
- Production cost estimation and tracking
- Damage/waste tracking during production
- YouTube training video integration
- Production order reports and analytics

### Primary Functions
- [x] Create new production orders
- [x] Edit and update production orders  
- [x] Delete production orders with inventory reversal
- [x] View production order details and costs
- [x] Generate production reports by date range
- [x] Manage production stages and workflows
- [x] Track raw material consumption requirements
- [x] Handle damaged products during production
- [x] Calculate production costs and profitability
- [x] Integrate with inventory management

### Related Controllers
- [productionExecutionController.php](productionExecutionController.md) - Manufacturing execution
- [taskOrderController.php](#) - Task order management  
- [productController.php](productController.md) - Product and BOM management
- [storeController.php](storeController.md) - Warehouse management
- [stageController.php](#) - Manufacturing stages
- [workstationController.php](#) - Workstation management
- [employeeController.php](employeeController.md) - Worker assignment
- [assetController.php](assetController.md) - Machine/equipment tracking
- [damagedProductController.php](#) - Damage tracking

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `productionorder` | Main production orders | `productionOrderid`, `name`, `orderDate`, `startDate`, `endDate`, `outQuantity`, `orderStatus` |
| `productionrate` | Production formulas/BOM | `productionRateId`, `ratename`, `finalproductid` |
| `productionrateproduct` | BOM line items | `id`, `productionRateId`, `productid`, `quantity`, `productBuyPrice` |
| `damagedproduct` | Production waste/damage | `damagedProductId`, `productionOrderId`, `productId`, `productQuantity` |

### Related Tables (Workflow & Resources)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `stage` | Manufacturing stages | `stageid`, `stagename` |
| `stagestep` | Stage operations | `id`, `stageId`, `operationId` |
| `workstation` | Production workstations | `workstationid`, `workstationname` |
| `workstationworker` | Worker assignments | `id`, `workstationid`, `employeeid`, `Hourlyrate` |
| `workstationassets` | Machine assignments | `id`, `workstationid`, `assetsId`, `Hourlyrate` |
| `settingoperation` | Operation time settings | `id`, `operationid`, `workStationID`, `realTime` |

### Inventory Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `storedetail` | Current inventory | `storedetailid`, `storeid`, `productid`, `productquantity` |
| `storereport` | Inventory movements | `storereportid`, `productid`, `processname`, `productbefore`, `productafter` |
| `productunit` | Unit conversions | `productunitid`, `productid`, `unitid`, `productnumber` |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `product` | Product master data | `productId`, `productName`, `productBuyPrice` |
| `store` | Warehouse locations | `storeid`, `storeName` |
| `employee` | Workers | `employeeid`, `employeename`, `Hourlyrate` |
| `assets` | Equipment/machines | `assetsId`, `assetsName`, `Hourlyrate` |

---

## 🔧 Key Functions

### 1. **add() - Create Production Order**
**Line**: 779  
**Purpose**: Creates a new production order and reserves raw materials

**Parameters**:
- `$_POST['orderName']` - Production order name
- `$_POST['productId']` - Final product to manufacture  
- `$_POST['outQuantity']` - Quantity to produce
- `$_POST['from']`, `$_POST['to']` - Start and end dates
- `$_POST['stage']` - Manufacturing stage ID
- `$_POST['store']` - Source warehouse ID

**Process Flow**:
```
┌─ Create Production Order ─┐
│                           │
▼                           │
Insert production order record ──┘
│
▼
Get BOM for final product
│
▼
For each raw material:
├─ Calculate required quantity
├─ Check inventory availability
├─ Reserve/reduce inventory
├─ Create storereport entry
└─ Update material costs
│
▼
Set order status to "In Progress"
```

**Code Example**:
```php
// Calculate required raw material quantity
$finalquantity = $_POST["outQuantity"] * $productnumber * $Finalproductnumber * $Productionrateproduct[$i]->quantity;

// Reduce inventory
if (count($allStoredetailData) > 0) {
    $productquantityAfter = decreaseProductQuantity($storedetailId, $productquantityBefore, $finalquantity);
    insertStorereport($productId, $_POST["store"], $finalquantity, $productquantityBefore, $productquantityAfter, 1, $productionOrderId, "تصنيع", "productionOrderController.php");
}
```

---

### 2. **update() - Modify Production Order**
**Line**: 887  
**Purpose**: Updates production order quantities and adjusts material reservations

**Parameters**:
- `$_POST['productionOrderid']` - Order ID to update
- `$_POST['outQuantity']` - New production quantity
- `$_POST['oldOutQuantity']` - Previous quantity

**Process Flow**:
```
┌─ Update Production Order ─┐
│                           │
▼                           │
Validate quantity increase only ──┘
│
▼
Calculate quantity difference
│
▼
For each raw material:
├─ Calculate additional requirement
├─ Reduce additional inventory
└─ Create adjustment storereport
│
▼
Update production order record
```

**Business Rule**: Only allows quantity increases to prevent inventory complications

---

### 3. **recievedone() - Complete Production Order**
**Line**: 1005  
**Purpose**: Completes production by adding finished goods to inventory

**Process Flow**:
```
┌─ Complete Production ─┐
│                       │
▼                       │
Get production order details ──┘
│
▼
Calculate finished goods quantity
│
▼
Add to finished goods inventory
│
▼
Create positive storereport entry
│
▼
Update order status to "Completed"
```

---

### 4. **details() - Production Cost Analysis**
**Line**: 336  
**Purpose**: Displays detailed production cost breakdown

**Process Flow**:
```
┌─ Cost Analysis ─┐
│                 │
▼                 │
Get raw material costs ─┘
│
▼
Get damaged product costs
│
▼
Calculate worker costs:
├─ Get stage operations
├─ Get workstation assignments  
├─ Calculate labor hours × rates
└─ Sum total labor cost
│
▼
Calculate machine costs:
├─ Get equipment assignments
├─ Calculate machine hours × rates
└─ Sum total equipment cost
│
▼
Total Cost = Material + Damage + Labor + Equipment
│
▼
Unit Cost = Total Cost ÷ Output Quantity
```

---

### 5. **getRawMaterialsAndTotalCostOfIt() - BOM Costing**
**Line**: 1240  
**Purpose**: Calculates raw material requirements and costs for production

**Parameters**:
- `$myfinalProductId` - Final product ID
- `$myunitId` - Unit of measure ID
- `$myOutQuantity` - Production quantity

**Process Flow**:
```
┌─ BOM Costing ─┐
│               │
▼               │
Get production rate formula ──┘
│
▼
For each BOM component:
├─ Get unit conversion factor
├─ Calculate: Required = Prod_Qty × BOM_Qty × Conversion
├─ Calculate: Cost = Required × Unit_Cost × Conversion  
├─ Add to total material cost
└─ Store component details
│
▼
Return: [Component_Array, Total_Cost]
```

**Formula**:
```
Required Quantity = Output Quantity × BOM Quantity × Unit Conversion Factor
Component Cost = Required Quantity × Buy Price × Unit Factor  
Total Material Cost = Σ(Component Costs)
```

---

### 6. **addDamageProduct() - Track Production Waste**
**Line**: 1052  
**Purpose**: Records damaged/waste products during production

**Parameters**:
- `$_POST['productId']` - Damaged product ID
- `$_POST['productQuantity']` - Waste quantity
- `$_POST['cost']` - Waste cost

**Process Flow**:
```
┌─ Record Production Waste ─┐
│                           │
▼                           │
Insert damaged product record ──┘
│
▼
Get BOM for damaged product
│
▼
For each raw material component:
├─ Calculate waste material cost
├─ Reduce inventory for wasted materials
├─ Create negative storereport entry
└─ Track waste in costing
```

---

### 7. **getuniqueArrayAndTotal() - Resource Aggregation**
**Line**: 1295  
**Purpose**: Aggregates worker/machine time and costs across production stages

**Parameters**:
- `$OnelevelArray` - Array of resource assignments
- `$type` - 1=workers, 2=assets, 3=materials

**Process Flow**:
```
┌─ Resource Aggregation ─┐
│                        │
▼                        │
For each resource record: ──┘
├─ Check if already in unique list
├─ If new: Add to unique list
├─ If exists: Add time/quantity to existing
└─ Calculate total cost
│
▼
Return: [Unique_Resources, Total_Cost]
```

---

### 8. **delete() - Remove Production Order**
**Line**: 1183  
**Purpose**: Deletes production order and reverses all inventory effects

**Process Flow**:
```
┌─ Delete Production Order ─┐
│                           │
▼                           │
Get all material reservations ──┘
│
▼
For each reserved material:
├─ Return materials to inventory
├─ Create positive storereport entry
└─ Reverse material costs
│
▼
Delete production order record
```

---

## 🔄 Business Logic Flow

### Production Order Lifecycle

```
┌─ Production Planning ─┐
│                       │
▼                       │
Create Production Order ──┘
│ • Define product & quantity
│ • Set schedule dates  
│ • Select manufacturing stage
│ • Choose source warehouse
▼
┌─ Material Reservation ─┐
│ • Calculate BOM requirements │
│ • Check inventory availability │
│ • Reserve raw materials        │
│ • Update inventory records     │
└─────────────────────────────┘
│
▼
┌─ Production Execution ─┐
│ • Assign workers & machines │
│ • Execute manufacturing     │
│ • Track actual consumption  │
│ • Record waste/damage       │
└─────────────────────────────┘
│
▼
┌─ Production Completion ─┐
│ • Add finished goods to stock │
│ • Calculate actual costs       │
│ • Update order status         │
│ • Generate cost reports       │
└───────────────────────────────┘
```

### Stage-Based Manufacturing

```
Stage 1: Preparation
├─ Material preparation
├─ Workstation setup
└─ Worker assignment

Stage 2: Processing  
├─ Raw material consumption
├─ Manufacturing operations
└─ Quality control checks

Stage 3: Assembly
├─ Component assembly
├─ Finishing operations
└─ Final inspection

Stage 4: Packaging
├─ Product packaging
├─ Labeling
└─ Transfer to finished goods
```

---

## ⚠️ Common Issues

### 1. **Insufficient Raw Material Inventory**
**Symptoms**: Production order creation fails with inventory shortage
**Causes**:
- BOM requirements exceed available stock
- Concurrent production orders consuming same materials
- Incorrect unit conversions in BOM

**Solutions**:
- Implement material requirement planning (MRP)
- Add inventory reservation system
- Validate BOM unit conversions

### 2. **Production Cost Calculation Errors**
**Symptoms**: Incorrect unit costs, negative costs
**Causes**:
- Missing or incorrect worker/machine hourly rates
- BOM formula errors
- Unit conversion mismatches

**Solutions**:
- Validate all rate data before production
- Add formula testing for BOM equations
- Implement cost validation rules

### 3. **Production Order Status Inconsistencies**
**Symptoms**: Orders stuck in "In Progress" status
**Causes**:
- Incomplete production execution
- Manual database modifications
- System errors during completion

**Solutions**:
- Add automated status tracking
- Implement production milestone checkpoints
- Create order status audit trail

---

## 🔗 Dependencies

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

### Required DAOs
- `ProductionorderDAO` - Production order data
- `ProductionrateDAO` - BOM formulas
- `StageDAO` - Manufacturing stages
- `StoredetailDAO` - Inventory management
- `EmployeeDAO` - Worker information
- `AssetDAO` - Equipment data

### Session Variables
- `$_SESSION['userid']` - Current user ID for audit trail
- `$_SESSION['erp_lang']` - Language settings

### External Systems
- Inventory management system
- Cost accounting system
- Stage/workflow management
- Employee scheduling system

---

## 📊 Production Formulas

### Material Requirement Calculation
```php
// Basic BOM calculation
$requiredQuantity = $outputQuantity × $bomQuantity × $unitConversionFactor;

// Multi-level BOM (recursive)
function calculateTotalRequirement($finalProduct, $quantity, $level = 0) {
    $totalRequirements = [];
    $bom = getBOMForProduct($finalProduct);
    
    foreach ($bom as $component) {
        $required = $quantity × $component->quantity;
        if (hasSubBOM($component->productId)) {
            $subRequirements = calculateTotalRequirement($component->productId, $required, $level + 1);
            $totalRequirements = array_merge($totalRequirements, $subRequirements);
        } else {
            $totalRequirements[] = ['product' => $component->productId, 'quantity' => $required];
        }
    }
    return $totalRequirements;
}
```

### Production Cost Formula
```php
// Total production cost calculation
$materialCost = Σ(component_quantity × component_unit_cost);
$laborCost = Σ(worker_hours × hourly_rate);
$equipmentCost = Σ(machine_hours × hourly_rate);
$wasteCost = Σ(waste_quantity × waste_unit_cost);

$totalProductionCost = $materialCost + $laborCost + $equipmentCost + $wasteCost;
$unitProductionCost = $totalProductionCost / $outputQuantity;
```

### Efficiency Metrics
```php
// Material yield efficiency
$materialYield = ($outputQuantity × standardMaterialPerUnit) / $actualMaterialUsed × 100;

// Labor efficiency  
$laborEfficiency = $standardLaborHours / $actualLaborHours × 100;

// Overall Equipment Effectiveness (OEE)
$oee = $availability × $performance × $quality;
```

---

**Manufacturing Concepts Covered**: Production Orders, Work Order Management, Bill of Materials (BOM), Material Requirements Planning (MRP), Stage-Based Manufacturing, Production Costing, Resource Planning, Waste Tracking, Production Scheduling, Inventory Reservation