Store Controller Documentation
File: /controllers/storeController.php
Purpose: Manages warehouse/store operations, inventory evaluation, and store configurations
Last Updated: December 19, 2024
Total Functions: 9
Lines of Code: 643
---
๐ Overview
The Store Controller is responsible for managing warehouse/store operations in the ERP system. It handles:
- โข Creating and editing store/warehouse records
- โข Managing store inventory evaluation
- โข Store visibility and permissions
- โข Inventory value calculations with different pricing methods
- โข Store location and branch associations
- โข Store operations (hide/show/delete)
Primary Functions
- โ Create new stores/warehouses
- โ Edit existing stores
- โ Delete stores (with validation)
- โ View store inventory with evaluation
- โ Hide/show stores (soft delete)
- โ Calculate store inventory values
- โ Batch operations on stores
- โ Store branch management
- โ Inventory pricing evaluation
Related Controllers
- โข buyBillController.php - Purchase operations
- โข sellbillController.php - Sales operations
- โข productController.php - Product management
- โข storedetailController.php - Store inventory details
- โข storemovementController.php - Stock transfers between stores
- โข storereportController.php - Store reports and valuations
- โข branchController.php - Branch management
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **store** | Main store records | storeId, storeName, storeDescription, conditions, branchId, userId | |
| **storedetail** | Store inventory details | storedetailid, storeid, productid, quantity, buyprice |
| Table Name | Purpose | Usage | |
|---|---|---|---|
| **branch** | Store branches | Links stores to branches | |
| **accountstree** | Accounting integration | Store accounts (treeId, treeIdBetween) | |
| **programsetting** | System settings | Inventory evaluation method | |
| **youtubelink** | Help videos | Store management tutorials |
| Table Name | Usage | |
|---|---|---|
| **user** | Store creation/modification tracking | |
| **product** | Products stored in warehouses |
๐ง Key Functions
1. add() - Create New Store
Signature: add(): void
Purpose: Creates a new store/warehouse with accounting integration
Parameters: Gets data from $_POST array
Process Flow:
Key Logic:
- โข Validates store name and details
- โข Creates accounting tree elements (main + intermediate)
- โข Sets creation date and user
- โข Stores branch association
- โข Creates API integration ID
SQL Operations:
INSERT INTO store (storeName, storeDescription, branchId, storeDate, userId, ...)
SELECT * FROM accountstree WHERE id = ?
UPDATE store SET treeId = ?, treeIdBetween = ? WHERE storeId = ?
2. show() - Display Store Inventory
Signature: show(): array
Purpose: Retrieves and calculates store inventory with evaluation pricing
Returns: Array of store data with calculated values
Process Flow:
Pricing Evaluation Methods:
- โข first: First purchase price
- โข last: Last purchase price
- โข mean: Average purchase price
- โข last_discount: Last price with discount
- โข mean_discount: Average price with discount
- โข generalPrice: Overall average price
- โข tax: Last price with tax
- โข mean_tax: Average price with tax
Key Logic:
foreach ($storeData as $story) {
switch ($Programsettingdata->Inventoryevaluation) {
case "first":
$totQtyPrice = (float) $story->tot_productBuyPrice;
break;
case "last":
$totQtyPrice = (float) $story->tot_lastbuyprice;
break;
// ... other methods
}
$story->totQtyPrice2 = $totQtyPrice;
}
3. delete($storeId) - Delete Store
Signature: delete($storeId): array
Purpose: Safely deletes a store after validation
Parameters:
- โข
$storeId(int): Store ID to delete
Returns: Array [message, status_code]
Process Flow:
Validation Logic:
- โข Checks if store has products in storedetail table
- โข Prevents deletion if dependencies exist
- โข Removes accounting tree elements
- โข Returns appropriate status code
4. edit() - Load Store for Editing
Signature: edit(): object
Purpose: Retrieves store data for editing form
Parameters: Gets storeId from $_GET
Returns: Store object with all properties
5. update() - Update Store
Signature: update(): void
Purpose: Updates existing store record with new data
Parameters: Gets data from $_POST array
Process Flow:
Key Logic:
- โข Updates both main and intermediate tree element names
- โข Preserves accounting integration
- โข Updates modification user and date
6. executeOperation() - Batch Operations
Signature: executeOperation(): void
Purpose: Performs batch operations on selected stores
Parameters: Gets operation type and selected items from $_POST
Supported Operations:
1. Hide Stores (1): Soft delete multiple stores
2. Show Stores (2): Restore hidden stores
3. Delete Stores (3): Permanently delete stores
Process Flow:
7. tempdelete($storeId) - Hide Store
Signature: tempdelete($storeId): string
Purpose: Hides store (soft delete) by setting conditions = 1
Parameters:
- โข
$storeId(int): Store ID to hide
Returns: Success or error message
8. returndelete($storeId) - Restore Store
Signature: returndelete($storeId): string
Purpose: Restores hidden store by setting conditions = 0
Parameters:
- โข
$storeId(int): Store ID to restore
Returns: Success or error message
---
๐ Workflows
Store Creation Workflow
Inventory Evaluation Workflow
Store Deletion Workflow
---
๐ URL Routes & Actions
| Route | Action | Purpose | Authentication | |
|---|---|---|---|---|
| `storeController.php` | Default (empty do) | Show add store form | Required | |
| `?do=add` | `add()` | Process store creation | Required | |
| `?do=show` | `show()` | Display store list with inventory | Required | |
| `?do=edit&storeId={id}` | `edit()` | Show edit store form | Required | |
| `?do=update` | `update()` | Process store update | Required | |
| `?do=delete&storeId={id}` | `delete()` | Delete store permanently | Required | |
| `?do=tempdelete&storeId={id}` | `tempdelete()` | Hide store (soft delete) | Required | |
| `?do=returndelete&storeId={id}` | `returndelete()` | Restore hidden store | Required | |
| `?do=executeOperation` | `executeOperation()` | Batch operations | Required | |
| `?do=success` | N/A | Show success message | None | |
| `?do=error` | N/A | Show error message | None |
All main actions support CURL requests by setting $_POST['curlpost'] = 1:
- โข Returns JSON responses instead of redirects
- โข Includes status codes and messages
- โข Arabic and English error messages
---
๐ Known Issues & Fixes
1. Store Deletion Validation
Issue: Need to check for inventory before deletion
Fix: Validates storedetail records before allowing deletion
Code Fix:
$storedetailData = $myStoredetailRecord->queryByStoreid($storeId);
if (count($storedetailData) <= 0) {
// Safe to delete
} else {
// Cannot delete - has inventory
}
2. Inventory Evaluation Performance
Issue: Multiple pricing calculations can be slow
Fix: Use appropriate database indexes and optimize queries
3. Tree Element Cleanup
Issue: Orphaned tree elements when deletion fails
Fix: Proper transaction handling and rollback
Code Fix:
try {
delTreeElementById($oldStore->treeId);
delTreeElementById($oldStore->treeIdBetween);
$myStoreRecord->delete($storeId);
} catch (Exception $e) {
// Rollback tree deletions
}
---
๐ Security & Permissions
Authentication Requirements
- โข All operations require valid user session
- โข Authentication checked via
../public/authentication.php - โข User ID tracked in all operations
Data Validation
- โข Store name validation (required, not empty)
- โข Store ID validation for operations
- โข Branch ID validation against existing branches
- โข User permission checks for store access
SQL Injection Prevention
- โข Uses DAO pattern with prepared statements
- โข Input sanitization for all user data
- โข Parameter binding for all queries
---
๐งช Testing & Debugging
Test Cases
Store Creation
1. Valid Store Creation
- Input: Valid store name, description, branch
- Expected: Store created, tree elements added, success response
2. Duplicate Store Name
- Input: Existing store name
- Expected: Validation error, no database changes
3. Invalid Branch
- Input: Non-existent branch ID
- Expected: Foreign key constraint error
Store Deletion
1. Empty Store Deletion
- Input: Store with no inventory
- Expected: Store and tree elements deleted, success response
2. Store with Inventory
- Input: Store with existing storedetail records
- Expected: Deletion prevented, error message
3. Invalid Store ID
- Input: Non-existent store ID
- Expected: Error response, no database changes
Debugging Tips
1. Check Tree Integration:
SELECT * FROM accountstree WHERE id IN (SELECT treeId FROM store WHERE storeId = ?)
2. Verify Store Dependencies:
SELECT COUNT(*) FROM storedetail WHERE storeid = ?
3. Monitor Inventory Values:
SELECT * FROM store_evaluation_view WHERE storeId = ?
---
โก Performance Considerations
Query Optimization
- โข Store List: Use pagination for large datasets
- โข Inventory Evaluation: Consider caching calculated values
- โข Tree Operations: Batch tree updates when possible
Indexing Recommendations
-- Store table indexes
CREATE INDEX idx_store_conditions ON store(conditions);
CREATE INDEX idx_store_branch ON store(branchId);
CREATE INDEX idx_store_user ON store(userId);
-- Store detail indexes
CREATE INDEX idx_storedetail_store ON storedetail(storeid);
Memory Management
- โข Avoid loading all store data at once
- โข Use streaming for large inventory reports
- โข Implement proper result set pagination
Caching Strategy
- โข Cache program settings for inventory evaluation
- โข Store calculated inventory values temporarily
- โข Use session caching for user store permissions
---
๐ Related Documentation
- โข Product Controller - Product management
- โข Buy Bill Controller - Purchase operations affecting store inventory
- โข Sell Bill Controller - Sales operations affecting store inventory
- โข Store Detail Controller - Detailed inventory operations
- โข Branch Controller - Branch management for store assignments
- โข Accounting Integration - Tree element management for stores
---
Last Updated: December 19, 2024
Version: 1.0
Maintainer: ERP Development Team