# Product Store Controller Documentation

**File**: `/controllers/productstore.php`  
**Purpose**: Manages product store limits and inventory thresholds across multiple stores  
**Last Updated**: December 20, 2024  
**Total Functions**: 10+  
**Lines of Code**: ~466

---

## 📋 Overview

The Product Store Controller manages product inventory limits and thresholds across different stores. Features:
- Product store limit management
- Automated missing row creation
- AJAX-based limit updates
- Category-based product filtering
- Store-specific inventory thresholds
- Products below limit reporting

### Primary Functions
- [x] Product store limit management
- [x] Automated inventory setup
- [x] AJAX limit updates  
- [x] Category filtering
- [x] Below-limit product reporting
- [x] Bulk operations

---

## 🗄️ Database Tables

### Primary Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **productstore** | Product store limits | id, productid, storeid, productcatid, limitamount, prostorelimitamount |
| **product** | Product master | productId, productName, productCatId, limitamount |
| **store** | Store master | storeId, storeName |
| **storedetail** | Current inventory | storeid, productid, productquantity |

---

## 🔑 Key Functions

### 1. **addAllOrMissingRows()** - Auto-Setup
**Location**: Line 444  
**Purpose**: Automatically create missing product-store combinations

**Process**:
```php
// Create unique constraint
ALTER TABLE productstore ADD UNIQUE `productstoreunique` (`productid`, `storeid`)

// Insert missing combinations
INSERT IGNORE INTO productstore (productid, storeid, productcatid, limitamount, prostorelimitamount)
SELECT product.productId, storedetail.storeid, product.productCatId, 
       product.limitamount, product.limitamount
FROM storedetail
JOIN product ON (product.productId = storedetail.productid AND product.conditions=0)
```

### 2. **showajax()** - DataTables Display  
**Location**: Line 251  
**Purpose**: AJAX-powered product store limits display with filtering

**Features**:
- Server-side pagination
- Search functionality
- Store/category filtering
- Inline limit editing
- Permission-based store filtering

### 3. **productBelowLimitInStoreAjax()** - Alert System
**Location**: Line 367  
**Purpose**: Display products below inventory limits for specific store

```php
$searchQuery = " and productstore.storeid = $userStore 
                 and storedetail.productquantity < productstore.prostorelimitamount ";
```

### 4. **updateAjax()** - Live Updates
**Location**: Line 158  
**Purpose**: Update product store limits via AJAX

```php
$id = (int) filter_input(INPUT_POST, 'id');
$prostorelimitamount = (float) filter_input(INPUT_POST, 'val');
$productstore = R::load('productstore', $id);
$productstore->prostorelimitamount = $prostorelimitamount;
R::store($productstore);
```

---

## 🔄 Workflows

### Workflow: Inventory Limit Management
```
┌─────────────────────────────────────────┐
│     START: Limit Management             │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  1. Auto-Setup Missing Records         │
│     - Create unique constraints        │
│     - Insert missing combinations      │
│     - Set default limits              │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  2. Display Current Limits             │
│     - Apply store filtering            │
│     - Show pagination controls         │
│     - Enable inline editing           │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  3. Process Updates                     │
│     - Handle AJAX updates              │
│     - Validate limit values            │
│     - Update database records          │
└─────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default | Display interface |
| `do=showajax` | `showajax()` | AJAX data display |
| `do=updateAjax` | `updateAjax()` | Update limits |
| `do=productBelowLimitInStoreAjax` | Alert function | Below-limit products |

---

## 🧮 Calculation Methods

### Automatic Limit Assignment
```php
$productstore->limitamount = $product['limitamount'];        // Product default
$productstore->prostorelimitamount = $product['limitamount']; // Store-specific
```

### Below-Limit Detection
```php
WHERE storedetail.productquantity < productstore.prostorelimitamount
```

---

## 🔒 Security & Permissions

### Store Access Control
```php
if ($_SESSION['searchinonestore'] == 0) {
    if ($_SESSION['storeids'] != 0) {
        $searchQuery .= 'and productstore.storeid in (' . $_SESSION['storeids'] . ') ';
    }
} else {
    $searchQuery .= " and productstore.storeid = " . $_SESSION['storeid'] . " ";
}
```

### Input Validation
```php
$id = (int) filter_input(INPUT_POST, 'id');
$prostorelimitamount = (float) filter_input(INPUT_POST, 'val');
```

---

## 📊 Performance Considerations

### Database Optimizations
- Unique constraints prevent duplicates
- Bulk INSERT IGNORE operations
- Efficient AJAX pagination
- Proper indexing on composite keys

### Memory Management
- Server-side DataTables processing
- Efficient RedBeanPHP queries
- Minimal object instantiation

---

## 🧪 Testing Scenarios

### Test Case 1: Auto-Setup
```
1. Add new products and stores
2. Run addAllOrMissingRows()
3. Verify missing combinations created
4. Check default limit assignments
```

### Test Case 2: Below-Limit Alerts
```
1. Set product limits
2. Reduce inventory below limits
3. Check alert system
4. Verify filtering accuracy
```

---

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