# Store Report Controller Documentation

**File**: `/controllers/storereportController.php`  
**Purpose**: Manages inventory reports, stock movements, and warehouse analytics  
**Last Updated**: December 19, 2024  
**Total Functions**: 11  
**Lines of Code**: 1,069

---

## 📋 Overview

The Store Report Controller provides comprehensive inventory reporting and stock movement analysis for the ERP system. It handles:
- Stock movement reports by product, store, and date ranges
- Inventory level tracking and analysis
- Credit and debit transaction summaries
- Product movement history tracking
- Size and color variant inventory reporting
- Multi-store inventory comparisons
- Detailed transaction audit trails
- Real-time stock position monitoring
- Category-based inventory analysis
- Integration with buy/sell transaction details

### Primary Functions
- [x] Generate stock movement reports
- [x] Track inventory levels by store
- [x] Monitor product movement history
- [x] Analyze credit/debit transactions
- [x] Support size/color variant tracking
- [x] Filter reports by date ranges
- [x] Compare multi-store inventory
- [x] Generate audit trails
- [x] Calculate stock summaries
- [x] Handle category-based reporting

### Related Controllers
- [sellbillController.php](sellbillController.md) - Sales transaction impact
- [buyBillController.php](buyBillController.md) - Purchase transaction impact
- [productController.php](productController.md) - Product master data
- [storeController.php](storeController.md) - Store/warehouse management
- [balancereportController.php](balancereportController.md) - Financial inventory valuation
- [FinancialPositionController.php](FinancialPositionController.md) - Asset valuation
- [FaidaController.php](FaidaController.md) - Profit analysis

---

## 🗄️ Database Tables

### Core Reporting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `storereport` | Stock movements | storereportid, productid, storeid, productquantity, productbefore, productafter, processname, tablename, storereportdate |
| `storedetail` | Current inventory | storedetailid, storeid, productid, productquantity, storedetaildate |
| `sizecolorstoredetail` | Size/color inventory | id, storeid, productid, sizeid, colorid, quantity |

### Transaction Detail Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `sellbilldetail` | Sales transactions | sellbilldetailid, sellbilldetailproductid, sellbilldetailquantity, sellbillid |
| `returnsellbilldetail` | Sales returns | returnsellbilldetailid, returnsellbilldetailproductid, returnsellbilldetailquantity |
| `buybilldetail` | Purchase transactions | buybilldetailid, buybilldetailproductid, buybilldetailquantity, buybillid |
| `returnbuybilldetail` | Purchase returns | returnbuybilldetailid, returnbuybilldetailproductid, returnbuybilldetailquantity |

### Master Data Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `store` | Store/warehouse master | storeid, storename, storeaddress, conditions |
| `product` | Product catalog | productId, productName, productcode, productcatid |
| `productcat` | Product categories | productcatid, productcatname, productcatparent |
| `sizecolor` | Size/color definitions | sizecolorid, sizecolorname, sizecolortype |

---

## 🔧 Key Functions

### Core Display Functions

#### Main Report Display (Lines 197-277)
**Purpose**: Main entry point for store reports with filtering options
**Parameters**: 
- `$_GET['storeId']` - Filter by store
- `$_GET['productId']` - Filter by product
- `$_GET['startDate']`, `$_GET['endDate']` - Date range

**Process Flow**:
```
┌─ Load Filters ─────┐
│ Store, Product    │
├─ Apply Filters ─┤
│ Date, Category   │
├─ Query Data ─────┤
│ Based on filters │
├─ Calculate Sums ─┤
│ Credit, Debit    │
└─ Display Report ─┘
```

### Summary Calculation Functions

#### `sumCredit()` (Lines 289-335)
**Purpose**: Calculates total credit transactions (increases in inventory)
**Returns**: Total credit amount across all stores and products

**Process Flow**:
```
┌─ Query Credits ────┐
│ storereporttype=0  │
├─ Filter Conditions┤
│ Active records     │
├─ Sum Quantities ─┤
│ Credit amounts     │
└─ Return Total ────┘
```

#### `sumCreditByStoreId($StoreId)` (Lines 336-385)
**Purpose**: Calculates credit transactions for a specific store
**Parameters**: `$StoreId` - Store identifier
**Returns**: Total credit amount for the specified store

#### `sumCreditByProductId($ProductId)` (Lines 386-435)
**Purpose**: Calculates credit transactions for a specific product
**Parameters**: `$ProductId` - Product identifier
**Returns**: Total credit amount for the specified product

#### `sumCreditByProductIdAndStoreId($ProductId, $storeId)` (Lines 436-527)
**Purpose**: Calculates credit transactions for specific product and store combination
**Parameters**: `$ProductId`, `$storeId`
**Returns**: Total credit amount for the product-store combination

### Report Generation Functions

#### `showByProductName($productid)` (Lines 528-536)
**Purpose**: Generates report filtered by product
**Parameters**: `$productid` - Product identifier
**Returns**: Store report data for the specific product

#### `showBystoreName($storeid)` (Lines 537-545)
**Purpose**: Generates report filtered by store
**Parameters**: `$storeid` - Store identifier
**Returns**: Store report data for the specific store

#### `showByDate($startDate, $endDate)` (Lines 546-554)
**Purpose**: Generates report filtered by date range
**Parameters**: `$startDate`, `$endDate` - Date range
**Returns**: Store report data for the date range

#### `showByStoreAndProductAndDate($productid, $storeid, $startDate, $endDate, $order, $bure)` (Lines 555-1044)
**Purpose**: Comprehensive report with multiple filters
**Parameters**: 
- `$productid` - Product filter
- `$storeid` - Store filter
- `$startDate`, `$endDate` - Date range
- `$order` - Sort order
- `$bure` - Additional filter parameter

**Process Flow**:
```
┌─ Build Query ──────┐
│ Multiple filters   │
├─ Apply Conditions ┤
│ Product, Store, Date│
├─ Sort Results ───┤
│ By specified order │
├─ Enrich Data ────┤
│ Product, Store names│
└─ Return Report ───┘
```

**Detailed Logic**:
- Builds complex WHERE clauses based on provided filters
- Handles category hierarchy for product filtering
- Supports both product and store filtering simultaneously
- Enriches results with product names, store names, and user information
- Calculates running totals and balances

### Utility Functions

#### `loadStore()` (Lines 280-288)
**Purpose**: Loads all active stores for dropdown selection
**Returns**: Array of store data

#### `getProductPath_recursive($parentid, $categories)` (Lines 1045-1061)
**Purpose**: Recursively builds product category hierarchy path
**Parameters**: `$parentid`, `$categories` - Category data
**Returns**: Category path string

#### `showAll()` (Lines 1062-1069)
**Purpose**: Displays all store report data without filters
**Returns**: Complete unfiltered store report data

---

## 🔄 Business Logic Flow

### Store Report Generation Process

```
User Request → Load UI Filters → Validate Parameters
     ↓
Build Query Conditions → Execute Database Query → Process Results
     ↓
Calculate Summaries → Enrich Data → Format Display → Return Report
```

### Inventory Movement Tracking

```
Transaction Occurs → Store Report Created → Movement Recorded
     ↓
├─ Credit Transactions (Inventory Increase)
│  ├─ Purchase receipts
│  ├─ Sales returns
│  ├─ Transfer in
│  └─ Adjustments positive
└─ Debit Transactions (Inventory Decrease)
   ├─ Sales shipments
   ├─ Purchase returns
   ├─ Transfer out
   └─ Adjustments negative
```

### Report Filtering Logic

```
All Data → Apply Store Filter → Apply Product Filter → Apply Date Range
    ↓
Category Filter → Size/Color Filter → User Permissions → Final Results
```

---

## ⚠️ Common Issues

### Performance Issues
1. **Large date ranges**: Extensive periods may cause slow report generation
2. **Complex filtering**: Multiple simultaneous filters can impact query performance
3. **No pagination**: Large result sets may cause memory issues

### Data Accuracy Issues
1. **Real-time consistency**: Reports may show slight delays during high transaction periods
2. **Category hierarchy**: Deep category structures may cause recursive lookup delays
3. **Size/color variants**: Additional complexity in inventory calculations

### Business Logic Warnings
1. **Permission checks**: Some reports may show unauthorized data
2. **Negative inventory**: No validation for impossible negative stock levels
3. **Date validation**: No validation for future dates in historical reports

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/include_dao.php` - All DAO includes
- `../public/config.php` - Database configuration
- `../public/authentication.php` - User authentication

### Database Dependencies
- Complete transaction history for accurate movement tracking
- Proper foreign key relationships between tables
- User group permissions for data access control
- Product category hierarchy structure

### External Dependencies
- Smarty templating engine for report display
- User session management for permissions
- Date/time utilities for range filtering
- YouTube integration for help videos

### Related Controllers
- Transaction controllers for movement source data
- Product management for master data
- Store management for warehouse information
- User management for permissions and audit trails

---

**Inventory Tracking Notes**:
- **Stock Movements** are tracked in real-time through storereport table
- **Credit Transactions** increase inventory (purchases, returns to inventory)
- **Debit Transactions** decrease inventory (sales, returns from inventory)  
- **Size/Color Variants** require separate tracking through sizecolorstoredetail
- **Audit Trail** maintains complete movement history with user and timestamp
- **Category Hierarchy** supports multi-level product categorization for reporting