# Production Execution Controller Documentation

**File**: `/controllers/productionExecutionController.php`  
**Purpose**: Manages manufacturing execution, BOM consumption, production output, and inventory updates  
**Last Updated**: December 19, 2024  
**Total Functions**: 17  
**Lines of Code**: ~1,881

---

## 📋 Overview

The Production Execution Controller is the core component for executing manufacturing processes in the ERP system. It handles:
- Production execution based on task orders
- Bill of Materials (BOM) consumption tracking
- Raw material inventory deduction during production
- Finished goods output tracking
- Waste/damaged product management during production
- Inventory updates with buy price history
- Production costing calculations
- Daily accounting entries for manufacturing

### Primary Functions
- [x] Execute production orders from task orders
- [x] Consume raw materials per BOM formulas
- [x] Track finished goods output
- [x] Manage production waste
- [x] Update inventory quantities
- [x] Calculate production costs
- [x] Generate accounting entries
- [x] Handle buy price history for FIFO/LIFO costing
- [x] Support size/color variants in production

### Related Controllers
- [productionOrderController.php](productionOrderController.md) - Production order management
- [taskOrderController.php](#) - Task order creation
- [productController.php](productController.md) - Product and BOM management
- [storeController.php](storeController.md) - Warehouse management
- [storedetailController.php](#) - Inventory management
- [simpleManufactureSettingsController.php](simpleManufactureSettingsController.md) - Manufacturing settings
- [productionEquationController.php](#) - BOM equations
- [dailyentryController.php](#) - Accounting entries

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `productionexecution` | Main production execution records | `id`, `taskorderid`, `num`, `notes`, `executiondate` |
| `productionexecutionproduct` | Raw materials consumed | `id`, `productionexecutionid`, `productid`, `quantity`, `actualquantity` |
| `productionexecutionoutput` | Finished goods produced | `id`, `productionexecutionid`, `productid`, `num` |
| `productionexecutionwaste` | Production waste/scrap | `id`, `productionexecutionid`, `productid`, `num` |
| `taskorder` | Source production orders | `taskorderid`, `name`, `num`, `startdate`, `enddate` |
| `taskorderproducts` | Task order materials list | `id`, `taskorderid`, `productid`, `quantity` |

### Related Tables (Inventory & Costing)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `storedetail` | Current inventory quantities | `storedetailid`, `storeid`, `productid`, `productquantity` |
| `storereport` | Inventory movement history | `storereportid`, `productid`, `storeid`, `productquantity`, `processname` |
| `buypriceshistorybook` | Purchase price tracking | `id`, `storeid`, `productid`, `buyprice`, `buyquantity`, `sellquantity` |
| `sizecolorstoredetail` | Size/color variant inventory | `id`, `productid`, `sizeid`, `colorid`, `quantity` |
| `productionrate` | BOM header | `productionRateId`, `ratename`, `finalproductid` |
| `productionrateproduct` | BOM line items | `id`, `productionRateId`, `productid`, `quantity` |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `product` | Product master data | `productId`, `productName`, `productBuyPrice`, `productSellPrice` |
| `store` | Warehouse/location master | `storeid`, `storeName` |
| `simplemanufacturesetting` | Manufacturing configuration | `id`, `storeid`, `reducestoreamount` |

---

## 🔧 Key Functions

### 1. **add() - Create Production Execution**
**Line**: 549  
**Purpose**: Creates a new production execution record from task order

**Parameters**:
- `$_POST['taskorderid']` - Source task order ID
- `$_POST['executiondate']` - Production execution date
- `$_POST['notes']` - Production notes
- `$_POST['storeid']` - Target warehouse for production

**Process Flow**:
```
┌─ Start Production Execution ─┐
│                               │
▼                               │
Insert productionexecution      │
│                               │
▼                               │
Get task order materials ───────┘
│
▼
For each raw material:
├─ Calculate consumption qty
├─ Reduce inventory
├─ Update buy price history
└─ Create storereport entry
│
▼
End
```

**Return**: Redirects to success/error page

---

### 2. **executeAdd() - Process Material Consumption**
**Line**: 702  
**Purpose**: Handles raw material deduction from inventory during production execution

**Parameters**:
- Task order materials from database
- Production quantity from form
- Store ID for inventory updates

**Process Flow**:
```
┌─ Material Consumption ─┐
│                        │
▼                        │
Get BOM formula ─────────┘
│
▼
For each BOM item:
├─ Calculate required qty = (production qty × BOM qty)
├─ Check inventory availability
├─ Reduce store inventory
├─ Update buy price history (FIFO)
├─ Create production execution product record
└─ Generate storereport entry
│
▼
Update mean buy prices
│
▼
Create daily accounting entry
```

**Code Example**:
```php
// Calculate material consumption based on BOM
$requiredQty = $productionQty * $bomQty * $conversionFactor;

// Reduce inventory
$newInventory = decreaseProductQuantity($storeDetailId, $currentQty, $requiredQty);

// Update buy price history for costing
getBuyPriceFromAndHandleBuyPricesHistoryBook($storeId, $productId, $sizeId, $colorId, $buyPrice, $requiredQty, 0);
```

---

### 3. **execute() - Complete Production Process**
**Line**: 1074  
**Purpose**: Completes production by adding finished goods to inventory

**Parameters**:
- `$_POST['productionexecutionid']` - Production execution ID
- `$_POST['output_*']` - Output quantities for each product
- `$_POST['waste_*']` - Waste quantities for each product

**Process Flow**:
```
┌─ Complete Production ─┐
│                       │
▼                       │
Get production execution ┘
│
▼
For each output product:
├─ Create productionexecutionoutput record
├─ Increase finished goods inventory
├─ Update storereport with addition
└─ Calculate new mean buy price
│
▼
For each waste product:
├─ Create productionexecutionwaste record
└─ Record waste in system
│
▼
Generate inventory daily entry
```

---

### 4. **update() - Modify Production Execution**
**Line**: 926  
**Purpose**: Updates existing production execution with new quantities

**Process Flow**:
```
┌─ Update Production ─┐
│                     │
▼                     │
Reverse previous transactions ┘
│
▼
Calculate quantity differences
│
▼
Apply new consumption quantities
│
▼
Update inventory accordingly
```

---

### 5. **delete() - Remove Production Execution**
**Line**: 1442  
**Purpose**: Deletes production execution and reverses all inventory effects

**Process Flow**:
```
┌─ Delete Production ─┐
│                     │
▼                     │
Get all consumption records ──┘
│
▼
For each consumed material:
├─ Reverse inventory reduction
├─ Return materials to stock
├─ Update buy price history
└─ Create reversal storereport
│
▼
Delete production records
```

---

### 6. **getBuyPriceFromAndHandleBuyPricesHistoryBook() - FIFO Costing**
**Line**: 1746  
**Purpose**: Manages buy price history for FIFO/LIFO inventory costing

**Parameters**:
- `$storeId` - Warehouse ID
- `$productid` - Product ID
- `$sizeid`, `$colorid` - Variant identifiers
- `$productBuyPrice` - Current buy price
- `$soldQuantity` - Quantity being consumed
- `$type` - 0=consumption, 1=return

**Process Flow**:
```
┌─ FIFO Costing Process ─┐
│                        │
▼                        │
Get oldest purchase records ──┘
│
▼
For each purchase lot:
├─ Calculate consumption from this lot
├─ Update remaining quantity
├─ Track weighted average cost
└─ Remove fully consumed lots
│
▼
Return: cost of goods consumed
```

---

### 7. **doInventoryDailyEntry() - Accounting Integration**
**Line**: 1849  
**Purpose**: Creates daily accounting entries for production costs

**Parameters**:
- `$productionExecution` - Production execution object

**Process Flow**:
```
┌─ Accounting Entry ─┐
│                    │
▼                    │
Calculate total production cost ─┘
│
▼
Debit: Work in Process Inventory
│
▼
Credit: Raw Materials Inventory
│
▼
Create dailyentry record
```

---

## 🔄 Business Logic Flow

### Production Execution Workflow

```
┌─ Task Order Created ─┐
│                      │
▼                      │
Production Execution ──┘
│
▼
┌─ Material Consumption Phase ─┐
│ 1. Get BOM for product       │
│ 2. Calculate required materials │
│ 3. Check inventory availability │
│ 4. Reduce raw material stock   │
│ 5. Update buy price history    │
│ 6. Record consumption          │
└─────────────────────────────┘
│
▼
┌─ Production Phase ─┐
│ 1. Execute manufacturing │
│ 2. Record actual output   │
│ 3. Track waste/scrap      │
│ 4. Quality control check  │
└─────────────────────────┘
│
▼
┌─ Output Recording Phase ─┐
│ 1. Add finished goods to inventory │
│ 2. Calculate production cost       │
│ 3. Update product mean buy price   │
│ 4. Generate accounting entries     │
└──────────────────────────────────┘
```

### BOM Consumption Formula

```
Required Quantity = Production Qty × BOM Qty × Unit Conversion Factor

Example:
- Produce 100 units of Product A
- BOM requires 2.5kg Material X per unit
- Material X stored in grams (conversion factor = 1000)
- Required = 100 × 2.5 × 1000 = 250,000 grams
```

---

## ⚠️ Common Issues

### 1. **Inventory Shortage During Production**
**Symptoms**: Production fails with insufficient stock error
**Causes**:
- BOM consumption exceeds available inventory
- Incorrect unit conversion factors
- Concurrent production orders

**Solutions**:
- Implement inventory reservation system
- Add stock validation before production start
- Verify unit conversion in product setup

### 2. **Buy Price History Inconsistencies**
**Symptoms**: Incorrect cost calculations, negative inventory values
**Causes**:
- FIFO queue corruption during concurrent operations
- Manual inventory adjustments without price history updates

**Solutions**:
- Add database transactions for atomic operations
- Rebuild buy price history after manual adjustments
- Implement inventory locking during production

### 3. **BOM Formula Calculation Errors**
**Symptoms**: Wrong material consumption amounts
**Causes**:
- Missing or incorrect production rate equations
- Unit conversion factor mismatches
- Formula version control issues

**Solutions**:
- Validate BOM formulas before production
- Add audit trail for BOM changes
- Implement formula testing environment

---

## 🔗 Dependencies

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

### Required DAOs
- `ProductionexecutionDAO` - Production execution data
- `TaskorderDAO` - Source task orders
- `ProductionrateDAO` - BOM formulas
- `StoredetailDAO` - Inventory management
- `BuypriceshistorybookDAO` - Costing history
- `StorereportDAO` - Inventory audit trail

### Required Session Variables
- `$_SESSION['userid']` - Current user ID
- `$_SESSION['storenegative']` - Allow negative inventory flag

### External Dependencies
- Smarty templating engine
- Daily entry accounting system
- Inventory management system
- Product variant (size/color) system

---

## 🧮 Manufacturing Formulas

### Cost Calculation
```php
// Weighted average cost per unit
$newMeanPrice = (($oldQuantity × $oldMeanPrice) + ($newQuantity × $newPrice)) / ($oldQuantity + $newQuantity);

// Total production cost
$totalCost = $materialCost + $laborCost + $overheadCost;

// Unit production cost  
$unitCost = $totalCost / $outputQuantity;
```

### Inventory Valuation Methods
- **FIFO (First In, First Out)**: Oldest purchase prices used first for consumption
- **Weighted Average**: Recalculated after each purchase/production
- **Standard Cost**: Predetermined costs updated periodically

---

**Manufacturing Concepts Covered**: Production Execution, BOM Management, Material Consumption, FIFO Costing, Inventory Valuation, Production Costing, Waste Tracking, Quality Control Integration, Accounting Integration