# Store Housing Controller Documentation

**File**: `/controllers/storeHousingController.php`  
**Purpose**: Inventory management system for product quantity adjustments and store housing operations  
**Last Updated**: December 21, 2024  
**Total Functions**: 6  
**Lines of Code**: ~375

---

## 📋 Overview

The Store Housing Controller is an inventory management module that handles product quantity adjustments and store housing operations. It provides:
- Bulk inventory quantity adjustments across products
- Size and color variant inventory management
- Store-level inventory control with permissions
- Audit trail creation for all inventory changes
- Product category-based inventory organization
- Multi-unit product handling
- Real-time inventory synchronization
- Daily entry integration for accounting

### Primary Functions
- [x] Bulk inventory quantity updates
- [x] Size/color variant inventory tracking
- [x] Store permission-based access control
- [x] Inventory change audit logging
- [x] Category-based product organization
- [x] Multi-unit product conversions
- [x] Real-time sync with accounting system
- [x] Negative inventory validation

### Related Controllers
- [inventoryController.php](#) - Core inventory operations
- [storedetailController.php](#) - Store detail management
- [productController.php](#) - Product management
- [storereportController.php](#) - Store reporting

---

## 🗄️ Database Tables

### Primary Inventory Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storedetail** | Store inventory levels | storedetailid, productid, storeid, productquantity, userid, storedetaildate |
| **storereport** | Inventory change audit | storereportid, productid, storeid, productquantity, productbefore, productafter, processname, userid |
| **sizecolorstoredetail** | Size/color variants | sizecolorstoredetailid, productid, storeid, sizeid, colorid, quantity, userid |

### Product Organization Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **product** | Product master data | productId, productName, productCatId, limitamount |
| **productcat** | Product categories | productCatId, productCatName, productCatParent |
| **productunit** | Product units | productunitid, productid, productnumber |
| **store** | Store information | storeId, storeName |

### System Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default Action / show** - Inventory Interface
**Location**: Line 139  
**Purpose**: Displays the main inventory adjustment interface

**Process Flow**:
1. Load authentication and permissions
2. Load YouTube tutorial links
3. Load category hierarchy for product selection
4. Set up store selection based on user permissions
5. Load program settings for negative inventory rules
6. Display inventory adjustment form

**Key Features**:
- Multi-store support with permission checking
- Category hierarchy for product organization
- Negative inventory control settings
- Tutorial integration

---

### 2. **add()** - Process Inventory Adjustments
**Location**: Line 277  
**Purpose**: Core function that processes bulk inventory quantity updates

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

**Process Flow**:
1. Loop through submitted inventory adjustments (based on itr count)
2. For each product adjustment:
   - Check if it's size/color variant or regular product
   - Update appropriate inventory table
   - Create audit trail in storereport
   - Sync with accounting system
3. Handle different adjustment types (increase, decrease, no change)
4. Generate process descriptions for audit trail

**Key Variables**:
- `$itr` - Number of inventory items being processed
- `$newQty` - New quantity being set
- `$oldQty` - Previous quantity for comparison
- `$productId` - Product being adjusted (may include size/color info)

---

### 3. **getCategoryChilds()** - Category Hierarchy Loading
**Location**: Line 220  
**Purpose**: Loads product category hierarchy for organization

**Function Signature**:
```php
function getCategoryChilds($parentid = 0)
```

**Returns**: Array containing parent object and children array for category trees

---

### 4. **getProductCatsForShow()** - Product Category Display
**Location**: Line 230  
**Purpose**: Prepares product categories for display in inventory interface

**Process Flow**:
1. Load all products
2. For each product, fetch recursive category path
3. Build hierarchical display structure
4. Assign to Smarty template variables

---

### 5. **fetch_recursive()** - Category Path Builder
**Location**: Line 252  
**Purpose**: Recursively builds category path strings for display

**Function Signature**:
```php
function fetch_recursive($parentid, $categories)
```

**Returns**: Complete category path string (e.g., "Electronics/Computers/Laptops")

---

### 6. **getStores()** - Store Data Loading
**Location**: Line 270  
**Purpose**: Loads available stores for inventory operations

---

## 🔄 Workflows

### Workflow 1: Bulk Inventory Adjustment Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Load Inventory Interface               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Check User Permissions                                  │
│     - Verify inventory adjustment rights                   │
│     - Load accessible stores for user                      │
│     - Apply store-level restrictions                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Load Product Organization Data                          │
│     - Load category hierarchy                              │
│     - Build product selection interface                    │
│     - Load store configuration                             │
│     - Check negative inventory settings                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Display Inventory Adjustment Form                      │
│     - Show products by category                            │
│     - Display current quantities                           │
│     - Provide quantity input fields                        │
│     - Include store selection options                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. User Submits Quantity Changes                          │
│     - Validate new quantities                              │
│     - Check negative inventory rules                       │
│     - Prepare for bulk processing                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Process Each Inventory Adjustment                      │
│     FOR EACH product with quantity change:                 │
│       │                                                     │
│       ├─→ Check if size/color variant                      │
│       │   YES: Update sizecolorstoredetail table          │
│       │   NO:  Update storedetail table                   │
│       │                                                     │
│       ├─→ Calculate change type                            │
│       │   ├─ Increase (oldQty < newQty)                   │
│       │   ├─ Decrease (oldQty > newQty)                   │
│       │   └─ No Change (oldQty == newQty)                 │
│       │                                                     │
│       ├─→ Update inventory quantities                      │
│       │                                                     │
│       ├─→ Create audit trail entry                        │
│       │   ├─ Record old and new quantities                │
│       │   ├─ Document change reason                       │
│       │   └─ Log user and timestamp                       │
│       │                                                     │
│       └─→ Sync with accounting system                     │
│           └─ Call onlineTempStoreDetailFunc2()            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Handle Size/Color Variant Updates                      │
│     IF product has size/color variants:                    │
│       │                                                     │
│       ├─→ Update variant-specific quantities               │
│       │                                                     │
│       ├─→ Recalculate parent product totals                │
│       │   └─ Call updateQuantityWithSumChild()            │
│       │                                                     │
│       └─→ Sync variant data with accounting                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  7. Complete Processing                                     │
│     - Generate success/error messages                      │
│     - Redirect to appropriate page                         │
│     - Log completion status                                │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Default action | Display inventory adjustment interface |
| `do=add` | `add()` | Process submitted inventory adjustments |

### Required Parameters for Add Action
- `itr` - Number of inventory items being processed
- `newQty{N}` - New quantity for item N
- `productId{N}` - Product ID for item N (may include size/color encoding)
- `oldQty{N}` - Previous quantity for comparison
- `storeid{N}` - Store ID for item N
- `storedetailid{N}` - Store detail record ID

### Optional Parameters
- `Inv_byCode` - Inventory by barcode mode flag

---

## 🧮 Calculation Methods

### Size/Color Variant Processing
```php
// Check if product has size/color variants
if (strpos($productId, "hasSizeColor") !== false) {
    // Parse complex product ID
    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
    $productId = $productIdComplex[0];
    $sizeId = $productIdComplex[1];
    $colorId = $productIdComplex[2];
    
    // Load size/color specific record
    $sizecolorstoredetail = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX2(
        $productId, $storeid, $sizeId, $colorId
    );
    
    // Update variant quantity
    $sizecolorstoredetail->quantity = $newQty;
    $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
    
    // Update parent product total
    $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $storeid, 0);
    $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, 
        $_SESSION['userid'], date("Y-m-d"), 0, $storeid, $productId);
}
```

### Change Type Detection
```php
// Determine change type and calculate difference
if ($oldQty > $newQty) {
    $status = "بالنقص";  // Decrease
    $actualQty = $oldQty - $newQty;
    $type = 1;  // Decrease type
} else if ($oldQty < $newQty) {
    $status = "بالزيادة";  // Increase  
    $actualQty = $newQty - $oldQty;
    $type = 0;  // Increase type
} else {
    $status = "لم يتغير";  // No change
    $actualQty = $newQty;
    $type = 0;
}
```

### Audit Trail Creation
```php
// Create detailed audit record
$storeReport->processname = "تم إعادة جرد المنتج بالقيمة الحالية " . $status;
$storeReport->productafter = $newQty;
$storeReport->productbefore = $oldQty;
$storeReport->productid = $productId;
$storeReport->productquantity = $actualQty;
$storeReport->storeid = $storeid;
$storeReport->storereportdate = $today;
$storeReport->storereporttype = $type;
$storeReport->tablename = "inventoryController.php";
$storeReport->userid = $_SESSION['userid'];
$storeReport->sizeid = $sizeId;
$storeReport->colorid = $colorId;
```

---

## 🔒 Security & Permissions

### Store Access Control
```php
// Multi-store vs single-store users
if ($_SESSION['searchinonestore'] == 0) {
    // Multi-store user
    if ($_SESSION['storeids'] == 0) {
        $stores = $myStoreEx->queryByConditions();  // All stores
    } else {
        $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
    }
} else {
    // Single store user - restricted to assigned store
    $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid']);
}
```

### Negative Inventory Control
```php
// Check program settings for negative inventory rules
$programsettingsdata = $ProgramsettingDAO->load(1);
$smarty->assign("programsettingsdata", $programsettingsdata);

// Session-based negative inventory control
$smarty->assign("storenegative", $_SESSION['storenegative']);
```

### User Activity Logging
```php
// All changes logged with user ID and timestamp
$storeReport->userid = $_SESSION['userid'];
$storeReport->storereportdate = $today;
$storeDetail->userid = $_SESSION['userid'];
$storeDetail->storedetaildate = $today;
```

---

## 📊 Performance Considerations

### Batch Processing Optimization
1. **Efficient Looping**:
   - Processes multiple items in single transaction
   - Minimizes database round trips
   - Bulk audit trail creation

2. **Memory Management**:
   - Streams inventory updates rather than loading all at once
   - Efficient category hierarchy loading
   - Minimal template variable usage

3. **Database Considerations**:
   - Uses proper transactions for consistency
   - Indexes needed on storedetail(productid, storeid)
   - Size/color queries benefit from composite indexes

### Performance Monitoring
```php
// Monitor processing time for large inventories
$start_time = microtime(true);
for ($i = 1; $i <= $itr; $i++) {
    // Process inventory item
}
$end_time = microtime(true);
$processing_time = $end_time - $start_time;
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Size/Color Variant Issues**
**Issue**: Variant quantities not updating correctly  
**Cause**: Complex product ID parsing problems

**Debug**:
```php
// Check product ID format
if (strpos($productId, "hasSizeColor") !== false) {
    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
    echo "Original ID: " . $productId . "<br>";
    echo "Parsed Product: " . $productIdComplex[0] . "<br>";
    echo "Size ID: " . $productIdComplex[1] . "<br>";
    echo "Color ID: " . $productIdComplex[2] . "<br>";
}
```

### 2. **Inventory Sync Issues**
**Issue**: Inventory changes not reflecting in other modules  
**Cause**: Failed onlineTempStoreDetailFunc2() calls

**Fix**:
```php
// Verify sync function calls
$syncResult = onlineTempStoreDetailFunc2($storeid, $productId, $sizeId, $colorId, $newQty, 1);
if (!$syncResult) {
    error_log("Inventory sync failed for product: " . $productId);
}
```

### 3. **Negative Inventory Violations**
**Issue**: System allows negative quantities when it shouldn't  
**Cause**: Negative inventory settings not properly checked

**Debug**:
```php
// Check negative inventory settings
echo "Store Negative Setting: " . $_SESSION['storenegative'] . "<br>";
$settings = $ProgramsettingDAO->load(1);
echo "Program Settings: " . print_r($settings, true);
```

---

## 🧪 Testing Scenarios

### Test Case 1: Bulk Inventory Update
```
1. Select multiple products from different categories
2. Set various quantity adjustments (increases, decreases)
3. Submit bulk update
4. Verify all quantities updated correctly
5. Check audit trail entries created
6. Confirm accounting sync completed
```

### Test Case 2: Size/Color Variant Handling
```
1. Select products with size/color variants
2. Update specific variant quantities
3. Verify parent product totals recalculated
4. Check variant-specific audit trails
5. Confirm variant data properly synced
```

### Test Case 3: Permission Enforcement
```
1. Login as single-store user
2. Attempt to access other stores' inventory
3. Verify only assigned store visible
4. Test multi-store user permissions
5. Check store restriction enforcement
```

### Test Case 4: Negative Inventory Control
```
1. Configure negative inventory settings
2. Attempt to set quantities below zero
3. Verify validation based on settings
4. Test override capabilities for authorized users
5. Check warning messages display correctly
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [inventoryController.md](#) - Core inventory operations
- [storedetailController.md](#) - Store detail management
- [dailyentry.php](#) - Accounting integration
- [Database Schema Documentation](#) - Table relationships

---

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