# Damaged Product Controller Documentation

**File**: `/controllers/damagedProductController.php`  
**Purpose**: Manages damaged product tracking in manufacturing operations with automatic inventory adjustments  
**Last Updated**: December 20, 2024  
**Total Functions**: 12+  
**Lines of Code**: ~569

---

## 📋 Overview

The Damaged Product Controller handles tracking of damaged products during manufacturing processes. It manages:
- Damaged product registration and tracking
- Automatic raw material deduction from inventory
- Production order integration
- Store quantity management
- Cost tracking and reporting
- Manufacturing rate calculations
- Store movement reporting
- Multi-unit product handling

### Primary Functions
- [x] Register damaged products during production
- [x] Automatically deduct raw materials from inventory
- [x] Track production order relationships
- [x] Manage store quantity adjustments
- [x] Calculate production rates and costs
- [x] Generate inventory movement reports
- [x] Handle multi-unit product conversions
- [x] Maintain audit trails for all changes
- [x] Edit and update damaged product records
- [x] Delete damaged product entries

### Related Controllers
- [productionOrderController.php](#) - Manufacturing orders
- [storeController.php](#) - Inventory management
- [productController.php](#) - Product management
- [storereportController.php](#) - Inventory reporting

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **damagedproduct** | Damaged product records | damagedProductId, productId, measurUnitId, productQuantity, storeId, cost, operationDate, userID, productionOrderId |
| **storedetail** | Store inventory levels | storedetailid, storeid, productid, productquantity, userid, storedetaildate |
| **storereport** | Inventory movement log | productid, storeid, productquantity, productbefore, productafter, storereporttype, storereportmodelid, processname, tablename |

### Production Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **productionorder** | Manufacturing orders | productionOrderId, productId, quantity, status |
| **productionrate** | Production recipes/rates | productionRateId, finalProductId, rateName |
| **productionrateproduct** | Recipe components | productId, productionRateId, quantity, unitId |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **store** | Warehouse locations | storeid, storename, description |
| **product** | Product master data | productid, productname, productcode |
| **unit** | Measurement units | unitid, unitname, unitcode |
| **productunit** | Product-unit conversions | productid, unitid, productnumber |
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue |

---

## 🔑 Key Functions

### 1. **Default Action (empty $do)** - Add Damaged Product Form
**Location**: Line 154  
**Purpose**: Display form for registering new damaged products

**Process Flow**:
1. Load program settings and stores
2. Get production order data by ID
3. Load production order details with product names
4. Display add form template

**Template Variables**:
- `$allStores` - Available warehouses
- `$productionOrderData` - Current production order
- `$orderName` - Final product being manufactured

---

### 2. **add()** - Register Damaged Product
**Location**: Line 302  
**Purpose**: Create damaged product record and adjust inventory automatically

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

**Process Flow**:
1. Extract form data (product, unit, quantity, store, cost)
2. Create damaged product record
3. **Critical**: Load production rate for the product
4. **For each raw material component**:
   - Calculate required raw material quantity
   - Get current store inventory levels
   - Deduct materials from inventory
   - Create store movement reports

**Key Calculations**:
```php
// Convert damaged quantity to base units
$productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
$myproductNumber = $productunitData->productnumber;

// Calculate raw material deduction
$storeValue = $quantity * $productQuantity * $myproductNumber;

// Update inventory
$newQt = $productquantityBefore - $storeValue;
updateQuantityOfProduct($store, $productId, $newQt);
```

**Automatic Inventory Adjustments**:
- Loads production rate/recipe for damaged product
- Calculates raw material requirements
- Deducts proportional raw materials from inventory
- Creates audit trail in store reports

---

### 3. **show** - Display Damaged Products
**Location**: Line 198  
**Purpose**: List all damaged products with store information

**Features**:
- Join with store names for readable display
- Historical damaged product tracking
- Cost calculations and totals

---

### 4. **edit()** - Load Product for Editing
**Location**: Line 515  
**Purpose**: Retrieve damaged product data for modification

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

**Returns**: Damaged product object with all fields

---

### 5. **update()** - Update Damaged Product
**Location**: Line 529  
**Purpose**: Modify existing damaged product record

**Process Flow**:
1. Extract updated form data
2. Update damaged product properties
3. Save changes to database

**Note**: Does not re-calculate inventory adjustments

---

### 6. **delete()** - Remove Damaged Product
**Location**: Line 560  
**Purpose**: Delete damaged product record

**Warning**: Physical deletion without inventory reversal

---

## 🔄 Core Business Logic Functions

### 7. **decreaseProductQuantity()** - Inventory Reduction
**Location**: Line 413  
**Purpose**: Reduce product quantity in store inventory

**Function Signature**:
```php
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount)
```

---

### 8. **increaseProductQuantity()** - Inventory Addition
**Location**: Line 481  
**Purpose**: Increase product quantity (for reversals)

---

### 9. **updateQuantityOfProduct()** - Direct Store Update
**Location**: Line 436  
**Purpose**: Update store quantity directly via Extended DAO

---

### 10. **insertStorereport()** - Movement Tracking
**Location**: Line 444  
**Purpose**: Create audit trail for inventory movements

**Function Signature**:
```php
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename)
```

**Parameters**:
- `$storereporttype`: 1 = Decrease, 0 = Increase
- `$storereportmodelid`: Reference to damaged product ID
- `$processname`: Description in Arabic
- `$tablename`: Source controller name

---

### 11. **getStoredetailData()** - Inventory Query
**Location**: Line 464  
**Purpose**: Retrieve current inventory levels for product/store combination

**Returns**: Array with store detail object, ID, and current quantity

---

### 12. **loadProductUnitWithProductAndUnit()** - Unit Conversion
**Location**: Line 503  
**Purpose**: Get conversion factor between different product units

---

## 🔄 Workflows

### Workflow 1: Register Damaged Product
```
┌─────────────────────────────────────────────────────────────┐
│          START: Production Order → Damaged Product         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Production Order Context                           │
│     - Get production order details                          │
│     - Load available stores                                 │
│     - Display add form                                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Enters Damaged Product Data                        │
│     - Product and unit selection                            │
│     - Damaged quantity                                      │
│     - Store location                                        │
│     - Cost information                                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Damaged Product Record                           │
│     - Insert into damagedproduct table                      │
│     - Link to production order                              │
│     - Set audit fields                                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Process Raw Material Deductions                         │
│     FOR EACH raw material in production rate:               │
│       │                                                     │
│       ├─→ Calculate required quantity                      │
│       │                                                     │
│       ├─→ Convert units if needed                          │
│       │                                                     │
│       ├─→ Get current inventory level                      │
│       │                                                     │
│       ├─→ Deduct from store inventory                      │
│       │                                                     │
│       └─→ Create inventory movement report                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Return to Production Order                              │
│     - Redirect to production order receive page             │
│     - Update production status if needed                    │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Inventory Impact Calculation
```
┌─────────────────────────────────────────────────────────────┐
│               START: Damaged Product Entry                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Production Recipe                                  │
│     - Get production rate by final product                  │
│     - Load all raw material components                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Calculate Material Requirements                         │
│     FOR EACH raw material:                                  │
│       │                                                     │
│       ├─→ Base quantity per unit produced                   │
│       │                                                     │
│       ├─→ × Damaged quantity entered                       │
│       │                                                     │
│       ├─→ × Unit conversion factor                         │
│       │                                                     │
│       └─→ = Total raw material to deduct                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Execute Inventory Updates                               │
│     - Get current store quantities                          │
│     - Calculate new quantities after deduction              │
│     - Update storedetail records                            │
│     - Create storereport audit entries                      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Show add damaged product form |
| `do=add` | `add()` | Register new damaged product |
| `do=show` | - | Display all damaged products |
| `do=edit` | `edit()` | Load product for editing |
| `do=update` | `update()` | Save product changes |
| `do=delete` | `delete()` | Remove damaged product |

### Required Parameters
**Add Form**: `id` - Production order ID  
**Edit**: `id` - Damaged product ID  
**Add Action**: `productId`, `unitId`, `productQuantity`, `store`, `cost`, `id`

---

## 🧮 Critical Calculations

### Raw Material Deduction Formula
```php
// For each raw material in production rate:
$quantity = $Productionrateproduct[$i]->quantity;          // Base quantity per unit
$productQuantity = $_POST['productQuantity'];               // Damaged quantity
$myproductNumber = $productunitData->productnumber;        // Unit conversion
$storeValue = $quantity * $productQuantity * $myproductNumber;

// Update inventory
$newQt = $productquantityBefore - $storeValue;
```

### Unit Conversion Logic
```php
$productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
$productnumber = $productunitData->productnumber;
$finalquantity = $productQuantity * $productnumber;
```

---

## 🔒 Security & Business Rules

### Data Integrity
- Automatic inventory adjustments prevent manual errors
- Audit trails track all inventory movements
- Production order linkage maintains traceability

### Validation Points
- Production order must exist
- Sufficient inventory must be available
- Valid product-unit combinations required
- Store locations must be valid

---

## 📊 Performance Considerations

### Database Impact
- Multiple inventory updates per damaged product
- Extensive DAO operations for complex calculations
- Production rate queries for each operation

### Optimization Opportunities
1. Batch inventory updates for multiple materials
2. Cache production rates during session
3. Pre-calculate unit conversions

---

## 🐛 Common Issues & Troubleshooting

### 1. **Inventory Goes Negative**
**Issue**: Raw material quantities become negative after damaged product entry  
**Cause**: Insufficient raw materials in inventory
**Solution**: Validate inventory availability before processing

### 2. **Missing Production Rates**
**Issue**: Error when no production rate exists for product  
**Cause**: Production rate not configured for manufactured item
**Solution**: Create production rate or handle gracefully

### 3. **Unit Conversion Errors**
**Issue**: Incorrect quantity calculations  
**Cause**: Missing or incorrect productunit records
**Debug**: Verify productunit table has conversion factors

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Damaged Product Entry
```
1. Create production order for known product
2. Enter damaged product with valid quantity
3. Verify damaged product record created
4. Check raw material deductions occurred
5. Validate store report entries created
```

### Test Case 2: Unit Conversion Testing
```
1. Use product with multiple units (kg, g, piece)
2. Enter damaged quantity in non-base unit
3. Verify correct conversion applied
4. Check inventory deducted correctly
```

### Test Case 3: Production Rate Integration
```
1. Configure production rate with multiple materials
2. Enter damaged product
3. Verify each raw material deducted proportionally
4. Check all materials have store reports
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [productionOrderController.php](#) - Manufacturing operations
- [storeController.php](#) - Inventory management
- [storereportController.php](#) - Inventory reporting

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur