# Store Detail Controller Documentation

**File**: `/controllers/storedetailController.php`  
**Purpose**: Manages inventory reports, stock levels, and warehouse inventory analysis across stores  
**Last Updated**: December 19, 2024  
**Total Functions**: 13  
**Lines of Code**: 2,576

---

## 📋 Overview

The Store Detail Controller is the primary inventory management and reporting interface for the ERP system. It provides:
- Real-time inventory reports across all warehouses
- Stock level analysis by product and category
- Multi-store inventory comparisons
- Size and color variant inventory tracking
- Product cost analysis with different evaluation methods
- Inventory valuation reports
- Stock movement history
- Product categorization and filtering
- Barcode and batch tracking integration

### Primary Functions
- [x] Display inventory by store and product
- [x] Multi-store inventory reports
- [x] Product category-based filtering
- [x] Size and color variant tracking
- [x] Real-time stock level monitoring
- [x] Cost evaluation using different methods
- [x] Inventory valuation reports
- [x] Product search and filtering
- [x] Stock movement analysis
- [x] Export capabilities
- [x] Barcode integration
- [x] YouTube product link management

### Related Controllers
- [storeController.php](storeController.md) - Store management
- [productController.php](productController.md) - Product management
- [buyBillController.php](buyBillController.md) - Purchase operations
- [sellbillController.php](sellbillController.md) - Sales operations
- [storemovementController.php](storemovementController.md) - Stock transfers
- [returnBuyBillController.php](returnBuyBillController.md) - Purchase returns
- [returnSellBillController.php](returnSellBillController.md) - Sales returns

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storedetail** | Main inventory records | storedetailid, storeid, productid, productquantity, productquantityotherunit, unittype |
| **sizecolorstoredetail** | Size/color variant inventory | sizecolorstoredetailid, storedetailid, sizeid, colorid, productquantity |
| **storereport** | Stock movement history | storereportid, productid, storeid, storereporttype, storereportmodelid |

### Product Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **product** | Product master data | storedetail.productid |
| **productcat** | Product categories | product.productCatId |
| **productunit** | Units of measurement | product.productunitid |
| **productingredients** | Product ingredients/components | For composite products |
| **youtubelink** | Product video links | product.productid |

### Store Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **store** | Store/warehouse master | storedetail.storeid |

### Purchase History Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **buybilldetail** | Purchase history | For cost calculations |
| **returnbuybilldetail** | Return history | For cost adjustments |
| **buypriceshistorybook** | Price history | For inventory evaluation |

### Reference Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **programsettings** | System configuration | Inventory evaluation methods |
| **usergroup** | User permissions | Access control |

---

## 🔧 Key Functions

### 1. show()
**Purpose**: Main inventory display with filtering and search capabilities  
**Called By**: Default action `?do=show` or empty `$do`  
**Line**: 178

**Parameters** (via $_POST/$_REQUEST):
- `search` - Search type and criteria
- `productId` - Specific product filter
- `storeId` - Specific store filter
- `categoryIds` - Product category filters
- `unittype` - Unit type filter

**Business Logic Flow**:
```
┌─────────────────┐
│ Load store      │
│ permissions     │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Load product    │
│ categories      │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Apply search    │
│ filters         │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Calculate       │
│ inventory costs │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Format data     │
│ for display     │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Render inventory│
│ report template │
└─────────────────┘
```

**Database Operations**:
- SELECT from `storedetail` with complex joins
- SELECT from `product`, `productcat`, `store`
- Calculate costs using `buypriceshistorybook`
- Apply inventory evaluation methods

### 2. showunittype($unittype)
**Purpose**: Display inventory filtered by specific unit type  
**Parameters**: `$unittype` - Unit type (1=main unit, 2=secondary unit)  
**Line**: 886

**Business Logic**: Complex inventory calculation supporting multiple unit types and cost evaluation methods including:
- FIFO (First In, First Out)
- LIFO (Last In, First Out)
- Average cost method
- Last price method
- Tax-inclusive pricing
- Discount-adjusted pricing

### 3. showStoreSizeAndColor()
**Purpose**: Display inventory with size and color variant breakdown  
**Called By**: `?do=showsizeandcolor`  
**Line**: 1618

**Database Operations**:
- JOIN `storedetail` with `sizecolorstoredetail`
- SELECT size and color information
- Calculate variant-specific quantities and costs

### 4. getAllSubCat($catid)
**Purpose**: Recursively get all subcategories for filtering  
**Parameters**: `$catid` - Parent category ID  
**Line**: 2174

**Returns**: Array of all subcategory IDs including nested levels

### 5. showByProductNameAndStore()
**Purpose**: Filter inventory by product name and store  
**Line**: 2200

**Parameters** (via $_POST):
- `productname` - Product name search term
- `storeid` - Store filter
- `catids` - Category filter array

### 6. showBystoreName()
**Purpose**: Filter inventory by store name  
**Line**: 2284

**Parameters**: Store name search criteria

### 7. showByProductCatNameAndStoreId()
**Purpose**: Filter inventory by product category and store  
**Line**: 2369

**Parameters**:
- Product category criteria
- Store ID filter

### 8. showAll()
**Purpose**: Display complete inventory without filters  
**Line**: 2455

**Business Logic**: Loads all inventory records with full product and store information

### 9. loadProducts()
**Purpose**: Load product master data for dropdowns  
**Line**: 529

**Returns**: Array of products with IDs and names

### 10. loadStore()
**Purpose**: Load store master data based on user permissions  
**Line**: 540

**Returns**: Array of stores accessible to current user

### 11. loadProductCategories()
**Purpose**: Load hierarchical product category structure  
**Line**: 550

**Returns**: Nested array of product categories

### 12. loadProductUnitWithProductAndUnit($productId, $unitId)
**Purpose**: Load product unit conversion information  
**Line**: 2528

**Parameters**:
- `$productId` - Product identifier
- `$unitId` - Unit identifier

**Returns**: Unit conversion data for calculations

### 13. CURL_IT2($data_arr, $url)
**Purpose**: Handle external API communications  
**Line**: 2539

**Parameters**:
- `$data_arr` - Data to send
- `$url` - Target URL

---

## 🔄 Business Logic Flow

### Inventory Cost Calculation Flow
```
┌─────────────────┐
│ Product in      │
│ Inventory       │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Get Purchase    │
│ History         │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Apply Inventory │
│ Evaluation      │
│ Method          │
└─────────┬───────┘
          ▼
┌─────────────────────┬───────────────────┬─────────────────┐
│    FIFO Method      │   Average Method  │   LIFO Method   │
│ (First In First Out)│   (Average Cost)  │(Last In First Out│
└─────────┬───────────┴───────────┬───────┴─────────┬───────┘
          ▼                       ▼                 ▼
┌─────────────────┐    ┌─────────────────┐   ┌─────────────────┐
│ Use oldest      │    │ Calculate       │   │ Use newest      │
│ purchase prices │    │ weighted average│   │ purchase prices │
└─────────┬───────┘    └─────────┬───────┘   └─────────┬───────┘
          ▼                      ▼                     ▼
          └──────────────────────┬─────────────────────┘
                                 ▼
                   ┌─────────────────┐
                   │ Apply Discounts │
                   │ and Taxes       │
                   └─────────┬───────┘
                             ▼
                   ┌─────────────────┐
                   │ Final Unit Cost │
                   │ Calculation     │
                   └─────────────────┘
```

### Multi-Store Inventory Workflow
```
┌─────────────────┐
│ User selects    │
│ search criteria │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Check user      │
│ store permissions│
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Load allowed    │
│ stores list     │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Apply product   │
│ category filters│
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Query inventory │
│ across stores   │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Calculate costs │
│ per store       │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Format results  │
│ for display     │
└─────────────────┘
```

**Files Involved**:
- View: `/views/default/storedetail/storedetail_show.html`
- Model: `/models/dto/Storedetail.class.php`
- DAO: `/models/mysql/StoredetailMySqlDAO.class.php`
- Language: `/views/languages/[lang]/storedetail/storedetail.php`

---

## ⚠️ Common Issues

### Issue 1: Performance with Large Inventories
**Problem**: Slow loading when displaying thousands of products  
**Cause**: Complex cost calculations and joins  
**Fix**: Implement pagination and indexing optimization  

### Issue 2: Inventory Evaluation Method Complexity
**Problem**: Different cost calculation methods producing varying results  
**Cause**: Complex business rules for FIFO, LIFO, and average costing  
**Fix**: Clear method selection and consistent application  

### Issue 3: Multi-Unit Conversions
**Problem**: Incorrect quantity calculations with unit conversions  
**Cause**: Complex unit relationship calculations  
**Fix**: Proper unit conversion handling in `loadProductUnitWithProductAndUnit()`  

### Issue 4: Size/Color Variant Tracking
**Problem**: Inventory discrepancies with product variants  
**Cause**: Complex variant relationship management  
**Fix**: Proper handling in `showStoreSizeAndColor()`  

---

## 🔗 Dependencies

### Includes
```php
include("../public/impOpreation.php");
include_once("../public/config.php");
include_once("../public/reportfunctions.php");
include("../public/include_dao.php");
```

### Required DAOs
- `StoredetailDAO` - Inventory operations
- `StoreDAO` - Store management
- `ProductDAO` - Product information
- `ProductcatDAO` - Category management
- `BuybilldetailDAO` - Purchase history
- `ReturnbuybilldetailDAO` - Return history
- `ProductunitDAO` - Unit conversions
- `SizecolorstoredetailDAO` - Variant tracking
- `ProductingredientsDAO` - Component tracking
- `YoutubeLinkDAO` - Product media

### Related Views
- `/views/default/storedetail/storedetail_show.html` - Main inventory view
- `/views/default/storedetail/storedetail_sizecolor.html` - Variant view

### JavaScript Files
- `/views/default/assets/js/storedetail.js` - Inventory functionality
- `/views/default/assets/js/reports.js` - Report generation

---

## 🎯 URL Routes & Actions

| Action (`?do=`) | Method | Description | View Template |
|-----------------|--------|-------------|---------------|
| show (default) | GET/POST | Display inventory report | storedetail_show.html |
| showsizeandcolor | GET | Show size/color variants | storedetail_sizecolor.html |

---

## 📊 Inventory Evaluation Methods

### Cost Calculation Methods
The system supports multiple inventory evaluation methods configured in `programsettings`:

1. **FIFO (First In, First Out)**
   - Uses oldest purchase prices first
   - Best for perishable goods
   - More accurate during inflation

2. **LIFO (Last In, First Out)**  
   - Uses newest purchase prices first
   - Better tax benefits during inflation
   - May not reflect actual flow

3. **Average Cost Method**
   - Weighted average of all purchases
   - Smooths price fluctuations
   - Simple and consistent

4. **Last Price Method**
   - Uses most recent purchase price
   - Quick calculation
   - May not be representative

5. **Tax-Inclusive Methods**
   - Includes taxes in cost calculations
   - Better for tax reporting
   - More complex calculations

---

## 🔐 Permissions & Security

### Required Permissions
- Inventory viewing rights
- Store access permissions (user can only see assigned stores)
- Product category access

### Security Checks
```php
include_once("../public/authentication.php");
```

### Store-Level Security
```php
if ($_SESSION['storeids'] == 0) {
    // User can access all stores
} else {
    // Restrict to user's assigned stores
    $condition = 'store.storeId in (' . $_SESSION['storeids'] . ')';
}
```

---

## 📝 Notes

### Important Considerations
- Inventory calculations are real-time and can be resource-intensive
- Cost evaluation method affects all inventory valuations
- Multi-store permissions are strictly enforced
- Size/color variants require separate tracking
- Unit conversions must be accurate for proper reporting
- YouTube links provide product enhancement capabilities

### Future Improvements
- [ ] Add inventory forecasting
- [ ] Implement low stock alerts
- [ ] Add ABC analysis reporting
- [ ] Implement inventory aging reports
- [ ] Add barcode scanning integration
- [ ] Optimize performance for large datasets
- [ ] Add inventory audit capabilities

---

## 📚 Related Documentation
- [Store Management](storeController.md)
- [Product Management](productController.md)
- [Stock Movements](storemovementController.md)
- [Inventory Reports](../reports/inventory.md)
- [Cost Accounting Methods](../accounting/inventory-evaluation.md)