# Alternative Store Movement Controller Documentation

**File**: `/controllers/otherstoremovementController.php`  
**Purpose**: Manages alternative inventory movements including transfers, adjustments, and special stock operations with comprehensive audit trails  
**Last Updated**: December 20, 2024  
**Total Functions**: 15+  
**Lines of Code**: ~27,869 (Large and complex controller)

---

## 📋 Overview

The Alternative Store Movement Controller handles specialized inventory operations that don't fit into the standard sales/purchase workflows. This includes:

- **Store-to-Store Transfers**: Moving inventory between warehouses
- **Inventory Adjustments**: Stock increases/decreases for corrections
- **Product Returns**: Processing returned merchandise
- **Stock Corrections**: Fixing quantity discrepancies
- **Serial Number Tracking**: Managing serialized products
- **Size/Color Variants**: Handling product variations
- **Daily Entry Integration**: Full accounting integration
- **Comprehensive Auditing**: Detailed movement tracking

### Primary Functions
- [x] Process inventory transfers between stores
- [x] Handle inventory adjustments (increases/decreases)
- [x] Manage product returns and exchanges
- [x] Track serial numbers for products
- [x] Handle size/color product variations
- [x] Generate accounting entries for movements
- [x] Support bulk operations on multiple items
- [x] Provide detailed movement audit trails
- [x] Integrate with user permission systems

### Related Controllers
- [storemovementController.php](#) - Standard store movements
- [storeController.php](#) - Store management
- [storedetailController.php](#) - Inventory tracking
- [sellbillController.php](sellbillController.md) - Sales operations
- [buyBillController.php](#) - Purchase operations

---

## 🗄️ Database Tables

### Primary Movement Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **otherstoremovement** | Alternative movement records | otherstoremovementid, productid, quantity, movementtype, fromstoreid, tostoreid, userid, movementdate |
| **storemovement** | Standard movement tracking | storemovementid, productid, fromstoreid, tostoreid, quantity, movementdate, conditions |
| **storereport** | Movement audit reports | storereportid, productid, storeid, quantity, reportdate, reporttype |

### Inventory Core Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storedetail** | Product inventory by store | storedetailid, storeid, productid, productquantity, productBuyPrice, productSellPrice |
| **store** | Store/warehouse master | storeId, storeName, storeLocation, conditions |
| **product** | Product master data | productid, productname, productcode, productcategory |

### Variation Tracking Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **sizecolorstoredetail** | Size/color variant tracking | sizecolorstoredetailid, storedetailid, size, color, quantity |
| **productserial** | Serial number tracking | productserialid, productid, serialnumber, sold, storeid |

### Supporting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **buypriceshistorybook** | Purchase price history | buypriceshistorybookid, productid, buyprice, quantity, buydate |
| **dailyentry** | Accounting entries | dailyentryid, entryComment, entryDate |
| **usergroup** | User permission groups | usergroupid, usergroupname, permissions |
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue |

---

## 🔑 Key Functions

### 1. **Default Action** - Movement Form Display
**Location**: Line 189  
**Purpose**: Display the movement creation form with store and product selections

**Process Flow**:
1. Check user permissions and authentication
2. Load store negative balance settings
3. Configure search parameters (single store vs multi-store)
4. Load product data based on user store access
5. Prepare form with necessary dropdown data
6. Display movement form template

**Key Features**:
- Store permission filtering based on user access
- Product search optimization settings
- Negative inventory control settings
- User group permission integration

---

### 2. **add** - Create New Movement
**Location**: Line [Multiple locations for different movement types]  
**Purpose**: Process new inventory movement transactions

**Movement Types Supported**:
- **Type 0**: Store-to-store transfer
- **Type 1**: Inventory adjustment (increase)
- **Type 2**: Inventory adjustment (decrease)
- **Type 3**: Product return processing
- **Type 4**: Special movement operations

**Process Flow**:
1. **Input Validation**: Validate movement parameters and permissions
2. **Inventory Checking**: Verify source store has sufficient quantity
3. **Transaction Processing**:
   - Update source store inventory (decrease)
   - Update destination store inventory (increase)
   - Handle size/color variants if applicable
   - Process serial numbers for tracked products
4. **Price History Updates**: Update purchase price history
5. **Movement Logging**: Create detailed audit records
6. **Accounting Integration**: Generate daily entries
7. **Report Generation**: Update movement reports

---

### 3. **show** - Display Movement History
**Location**: Line [Various show functions]  
**Purpose**: Display movement history with filtering and search capabilities

**Filter Options**:
- **Date Range**: From/to date filtering
- **Store**: Source and destination store filtering  
- **Product**: Specific product filtering
- **Movement Type**: Filter by operation type
- **User**: Filter by who performed the movement

**Display Features**:
- Paginated results for large datasets
- Sortable columns
- Detailed movement information
- Links to related transactions
- Export capabilities

---

### 4. **edit** - Modify Existing Movement
**Location**: Line [Edit functions]  
**Purpose**: Allow modification of movement records (with restrictions)

**Editable Fields**:
- Movement notes/comments
- Non-financial metadata
- User assignments

**Restrictions**:
- Financial amounts cannot be changed after commitment
- Movements with accounting entries have limited editing
- User permission checks for modification rights

---

### 5. **delete** / **tempdelete** - Remove Movements
**Location**: Line [Delete functions]  
**Purpose**: Reverse inventory movements with complete audit trail

**Deletion Types**:
- **Soft Delete**: Mark as deleted but preserve data
- **Hard Delete**: Remove from system (restricted)
- **Reverse Movement**: Create offsetting movement

**Process Flow**:
1. **Validation**: Check movement can be deleted
2. **Inventory Reversal**: Reverse all quantity changes
3. **Accounting Reversal**: Reverse daily entries
4. **Audit Trail**: Maintain deletion audit record
5. **Status Update**: Update movement status

---

### 6. **Serial Number Management Functions**
**Location**: Various locations throughout controller  
**Purpose**: Handle serialized product tracking

**Functions Include**:
- **assignSerial()**: Assign serial numbers to products
- **updateSerial()**: Update serial status
- **trackSerial()**: Track serial movements
- **validateSerial()**: Ensure serial uniqueness

---

### 7. **Size/Color Variant Functions**
**Location**: Multiple locations  
**Purpose**: Manage product variations with size and color attributes

**Functions Include**:
- **updateSizeColor()**: Update variant quantities
- **transferVariants()**: Move variants between stores
- **validateVariants()**: Ensure variant data integrity

---

### 8. **Price History Functions**
**Location**: Price history management sections  
**Purpose**: Maintain accurate purchase price tracking

**Functions Include**:
- **updateBuyPricesHistory()**: Record price changes
- **calculateAveragePrice()**: Calculate weighted averages
- **adjustPriceHistory()**: Handle price adjustments

---

## 🔄 Workflows

### Workflow 1: Store-to-Store Transfer
```
┌─────────────────────────────────────────────────────────────┐
│              START: Need to Transfer Inventory             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Transfer Parameters                              │
│     - Source store (must have inventory)                   │
│     - Destination store                                     │
│     - Product and quantity to transfer                     │
│     - Reason for transfer                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Validate Transfer Feasibility                          │
│     - Check source store has sufficient quantity           │
│     - Verify user has permission for both stores           │
│     - Validate product exists in source store              │
│     - Check negative inventory settings                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Inventory Updates                               │
│     SOURCE STORE:                                          │
│       ├─→ Reduce product quantity                          │
│       ├─→ Update size/color variants (if applicable)       │
│       └─→ Handle serial numbers (if tracked)               │
│     DESTINATION STORE:                                     │
│       ├─→ Increase product quantity                        │
│       ├─→ Create/update product record if needed           │
│       ├─→ Transfer size/color variants                     │
│       └─→ Update serial number locations                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update Price History                                    │
│     - Record buy price at destination store                │
│     - Update price history for transferred quantity        │
│     - Maintain weighted average calculations               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Create Movement Records                                 │
│     - Insert otherstoremovement record                     │
│     - Create storereport entry                             │
│     - Log detailed audit information                       │
│     - Link to user and timestamp                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Generate Accounting Entries                             │
│     IF accounting integration enabled:                     │
│       ├─→ Debit: Destination Store Inventory Account       │
│       └─→ Credit: Source Store Inventory Account           │
│     Create daily entry with movement details               │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Inventory Adjustment Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Stock Discrepancy Found                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Determine Adjustment Type                               │
│     ├─→ Physical Count Higher: Increase Adjustment         │
│     ├─→ Physical Count Lower: Decrease Adjustment          │
│     ├─→ Product Damaged: Write-off Adjustment              │
│     └─→ Data Correction: System Error Adjustment           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Document Adjustment Reason                              │
│     - Detailed explanation required                        │
│     - Supporting documentation (photos, reports)           │
│     - Authorization level verification                     │
│     - Adjustment amount and justification                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Quantity Adjustment                             │
│     INCREASE ADJUSTMENT:                                   │
│       ├─→ Add quantity to store inventory                  │
│       ├─→ Update size/color variants if applicable         │
│       └─→ Create "found" serial numbers if needed          │
│     DECREASE ADJUSTMENT:                                   │
│       ├─→ Reduce quantity from store inventory             │
│       ├─→ Update/remove variants as needed                 │
│       └─→ Mark serial numbers as "lost" or "damaged"       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update Financial Records                                │
│     - Calculate adjustment value (quantity × average cost) │
│     - Update inventory valuation                           │
│     - Adjust price history records                         │
│     - Update cost accounting                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Create Adjustment Entry                                 │
│     INCREASE: Dr: Inventory, Cr: Adjustment Income         │
│     DECREASE: Dr: Adjustment Expense, Cr: Inventory        │
│     Include detailed notes and authorization info          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Generate Audit Reports                                  │
│     - Adjustment summary report                            │
│     - Before/after inventory levels                        │
│     - Cost impact analysis                                 │
│     - Authorization trail documentation                    │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default | Display movement form |
| `do=add` | `add()` | Create new movement |
| `do=show` | `show()` | Display movement history |
| `do=edit` | `edit()` | Load movement for editing |
| `do=update` | `update()` | Update movement record |
| `do=delete` | `delete()` | Remove movement |
| `do=tempdelete` | `tempdelete()` | Soft delete movement |
| `do=executeOperation` | Batch operations | Process multiple movements |

### Required Parameters by Action

**Add Movement** (`do=add`):
- `productid` - Product to move
- `quantity` - Amount to move
- `fromstoreid` - Source store
- `tostoreid` - Destination store
- `movementtype` - Type of movement
- `comment` - Reason for movement

**Show Movements** (`do=show`):
- `from` - Start date filter (optional)
- `to` - End date filter (optional)
- `storeid` - Store filter (optional)
- `productid` - Product filter (optional)

---

## 🔧 Technical Features

### Concurrency Control
- User-based locking mechanisms
- Transaction isolation for critical updates
- Rollback capability for failed operations
- Optimistic locking for inventory quantities

### Data Validation
- Negative inventory prevention (configurable)
- Quantity range validation
- Store permission verification
- Product existence validation
- Serial number uniqueness checks

### Audit Trail Features
- Complete movement history tracking
- User action logging
- Before/after quantity snapshots
- Timestamp precision to seconds
- Linking to source transactions

### Performance Optimizations
- Indexed queries for common filters
- Batch processing for bulk operations
- Cached store and product data
- Optimized recursive calculations
- Background processing for large operations

---

## 🔒 Security & Permissions

### User Access Control
```php
// Store-based permission checking
if ($_SESSION['storeids'] == 0) {
    // User has access to all stores
} else {
    // Restrict to user's assigned stores only
    $allowedStores = explode(',', $_SESSION['storeids']);
}
```

### Operation Permissions
- **Movement Creation**: Requires specific user group permissions
- **Movement Deletion**: Higher permission level required
- **Cross-Store Transfers**: Must have access to both stores
- **Bulk Operations**: Administrative permission required

### Data Protection
- Transaction-level data integrity
- Audit trail preservation
- Secure parameter validation
- SQL injection prevention
- Session-based authentication

---

## 📊 Performance Considerations

### Query Optimization
1. **Store Filtering**: Index on `(storeid, movementdate)`
2. **Product Filtering**: Index on `(productid, movementdate)`  
3. **User Filtering**: Index on `(userid, movementdate)`
4. **Date Range Queries**: Proper date indexing

### Memory Management
- Large result set pagination
- Efficient array processing
- Memory cleanup for bulk operations
- Optimized recursive functions

### Scalability Factors
- Performance degrades with large movement history
- Complex size/color variants increase processing time
- Serial number tracking adds overhead
- Accounting integration creates additional load

### Recommended Optimizations
```sql
-- Key indexes for performance
CREATE INDEX idx_otherstoremovement_store_date ON otherstoremovement(fromstoreid, movementdate);
CREATE INDEX idx_otherstoremovement_product_date ON otherstoremovement(productid, movementdate);
CREATE INDEX idx_storedetail_store_product ON storedetail(storeid, productid);
CREATE INDEX idx_productserial_product ON productserial(productid, sold);
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Negative Inventory Errors**
**Issue**: System prevents movements that would create negative inventory  
**Cause**: Insufficient quantity in source store

**Solutions**:
- Check actual inventory levels
- Verify concurrent movements haven't reduced stock
- Review negative inventory settings
- Consider partial transfers

### 2. **Serial Number Conflicts**
**Issue**: Serial numbers show as duplicated or missing  
**Cause**: Improper serial tracking during movements

**Debug Steps**:
```sql
-- Check for duplicate serials
SELECT serialnumber, COUNT(*) 
FROM productserial 
GROUP BY serialnumber 
HAVING COUNT(*) > 1;

-- Verify serial ownership
SELECT ps.*, sd.storeid 
FROM productserial ps
JOIN storedetail sd ON ps.productid = sd.productid
WHERE ps.serialnumber = '[SERIAL]';
```

### 3. **Price History Inconsistencies**
**Issue**: Average costs appear incorrect after movements  
**Cause**: Price history not properly updated during transfers

**Verification**:
```sql
-- Check price history for product
SELECT * FROM buypriceshistorybook 
WHERE productid = [ID] 
ORDER BY buydate DESC;

-- Recalculate weighted average
SELECT 
    productid,
    SUM(quantity * buyprice) / SUM(quantity) as weighted_avg
FROM buypriceshistorybook 
WHERE productid = [ID]
GROUP BY productid;
```

### 4. **Performance Issues with Large Datasets**
**Issue**: Movement history queries take too long  
**Cause**: Large movement history without proper indexing

**Solutions**:
- Add proper indexes (see Performance section)
- Implement date range restrictions
- Use pagination for large results
- Archive old movement data

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Store Transfer
```
1. Create product in Store A with quantity 100
2. Transfer 50 units to Store B
3. Verify Store A quantity = 50
4. Verify Store B quantity = 50
5. Check movement audit record created
6. Confirm price history updated
```

### Test Case 2: Serial Number Tracking
```
1. Add serialized product with 5 units
2. Assign unique serial numbers to each unit
3. Transfer 2 units with serials to different store
4. Verify serials moved to correct store
5. Check remaining serials stay in original store
```

### Test Case 3: Size/Color Variants
```
1. Create product with size/color variants
2. Set different quantities per variant
3. Transfer specific variants to new store
4. Verify only selected variants moved
5. Check variant quantities accurate in both stores
```

### Test Case 4: Inventory Adjustment
```
1. Set initial product quantity to 100
2. Perform physical count showing 95
3. Create decrease adjustment for 5 units
4. Verify system quantity matches physical count
5. Check adjustment entry in accounting
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [Store Management Documentation](#) - Store setup and configuration
- [Inventory Tracking Guide](#) - Product and quantity management
- [Serial Number System](#) - Serialized product handling
- [Accounting Integration](#) - Daily entry system

---

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

**Note**: This controller is exceptionally large and complex. This documentation covers the major functions and workflows, but additional detailed analysis may be needed for specific advanced features.