# Store Movement Controller Documentation

**File**: `/controllers/storemovementController.php`  
**Purpose**: Manages inventory transfers between warehouses, stock movements, and inter-store logistics  
**Last Updated**: December 19, 2024  
**Total Functions**: 34  
**Lines of Code**: 3,697

---

## 📋 Overview

The Store Movement Controller handles all operations related to transferring inventory between different warehouses/stores. It manages:
- Inter-store inventory transfers
- Stock movement tracking and approval workflows
- Temporary transfer operations (pending confirmations)
- Bulk product transfers between stores
- Serial number transfers for tracked products
- Daily accounting entries for transfers
- Transfer operation reversals
- Cost center allocations for movements
- Barcode-based transfer operations
- Multi-user approval workflows

### Primary Functions
- [x] Create stock transfer orders
- [x] Process inter-store transfers
- [x] Manage temporary transfers (pending)
- [x] Bulk transfer operations
- [x] Track serial numbers in transfers
- [x] Generate daily accounting entries
- [x] Reverse/cancel transfers
- [x] Handle transfer approvals
- [x] Process transfer receipts
- [x] Cost-based transfer pricing
- [x] Barcode scanning integration
- [x] Multi-store permissions

### Related Controllers
- [storeController.php](storeController.md) - Store management
- [storedetailController.php](storedetailController.md) - Inventory details
- [productController.php](productController.md) - Product management
- [buyBillController.php](buyBillController.md) - Purchase operations
- [sellbillController.php](sellbillController.md) - Sales operations
- [returnBuyBillController.php](returnBuyBillController.md) - Purchase returns
- [returnSellBillController.php](returnSellBillController.md) - Sales returns
- [dailyentryController.php](#) - Accounting entries

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storemovement** | Main transfer records | storemovementid, operationnum, storemovementfrom, storemovementto, storemovementproductid, storemovementquantity, storemovementdate |
| **otherstoremovement** | Alternative movement tracking | otherstoremovementid, operationnum, storeid, productid, quantity, operationtype |

### Inventory Tables (Updated)
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **storedetail** | Stock levels by store | Updated for from/to stores |
| **sizecolorstoredetail** | Variant-specific stock | For size/color transfers |
| **storereport** | Stock movement audit | Complete audit trail |
| **buypriceshistorybook** | Cost tracking | Cost-based transfers |
| **productserial** | Serial number tracking | For serialized transfers |

### Reference Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **store** | Store/warehouse master | storemovement.storemovementfrom/to |
| **product** | Product master data | storemovement.storemovementproductid |
| **programsettings** | System configuration | Cost calculation methods |
| **user** | User management | Transfer authorization |
| **usergroup** | Permission groups | Access control |

### Financial Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **dailyentry** | Accounting journal | Auto-generated entries |
| **costcenter** | Cost center tracking | Cost allocation |

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Create new stock transfer between stores  
**Called By**: Form submission with `?do=add`  
**Line**: 1139

**Parameters** (via $_POST):
- `operation` - Operation type (1=delete, 2=add)
- `manyParcodesstoreidfrom` - Source store ID
- `manyParcodesstoreidto` - Destination store ID
- `manyParcodesbatchdata` - Batch transfer data
- `selectedProducts` - Products to transfer
- `quantities` - Transfer quantities
- `serialNumbers` - Serial numbers (if applicable)

**Business Logic Flow**:
```
┌─────────────────┐
│ User initiates  │
│ transfer request│
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Validate stores │
│ and permissions │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Check source    │
│ store inventory │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Generate        │
│ operation number│
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Create transfer │
│ records         │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Update source   │
│ inventory (-qty)│
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Create pending  │
│ receipt records │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Generate daily  │
│ entry record    │
└─────────────────┘
```

### 2. addAllStoreProducts()
**Purpose**: Bulk transfer of all products from one store to another  
**Line**: 1432

**Parameters**:
- Source store ID
- Destination store ID
- Transfer all available inventory

**Database Operations**:
- SELECT all products from source store
- CREATE transfer records for each product
- UPDATE inventory levels
- INSERT audit trails

### 3. executeOperation()
**Purpose**: Finalize pending transfer operations  
**Called By**: `?do=executeOperation`  
**Line**: 2958

**Business Logic**: Converts pending transfers to completed transfers by:
- Updating destination store inventory
- Finalizing transfer records
- Creating accounting entries
- Updating serial number ownership

### 4. showAll()
**Purpose**: Display list of all transfer operations  
**Line**: 1929

**Returns**: Formatted list with:
- Transfer operation numbers
- Source and destination stores
- Transfer dates and statuses
- Product details
- Action buttons

### 5. showByDate($startDate, $endDate, $storeId)
**Purpose**: Filter transfers by date range and store  
**Line**: 1942

**Parameters**:
- `$startDate` - Start of date range
- `$endDate` - End of date range
- `$storeId` - Optional store filter

### 6. tempdelete($transferproductId)
**Purpose**: Temporarily delete/cancel a pending transfer item  
**Line**: 2376

**Parameters**: `$transferproductId` - Transfer item to cancel

**Database Operations**:
- Restore source store inventory
- DELETE transfer record
- INSERT reversal audit record

### 7. returndelete($transferproductId)
**Purpose**: Reverse a completed transfer operation  
**Line**: 2642

**Parameters**: `$transferproductId` - Transfer to reverse

**Business Logic**: Complex reversal process including:
- Restore source store inventory
- Remove destination store inventory
- Reverse accounting entries
- Update serial number ownership

### 8. getStoredetailData($storeid, $productid, $sizeColorStoreDetailId, $sizeId, $colorId)
**Purpose**: Retrieve current inventory levels for transfer validation  
**Line**: 2996

**Parameters**:
- `$storeid` - Store identifier
- `$productid` - Product identifier
- `$sizeColorStoreDetailId` - Variant ID
- `$sizeId`, `$colorId` - Variant dimensions

### 9. increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId, $movementRow)
**Purpose**: Increase inventory in destination store  
**Line**: 3045

**Database Operations**:
- UPDATE `storedetail` SET quantity = quantity + amount
- UPDATE `sizecolorstoredetail` for variants
- INSERT `storereport` audit record

### 10. decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId, $movementRow)
**Purpose**: Decrease inventory in source store  
**Line**: 3109

**Business Logic**: Validates sufficient inventory before decreasing

### 11. makeStoreMovementDailyEntry($mainData, $detailArr, $type)
**Purpose**: Create accounting entries for transfers  
**Line**: 3556

**Parameters**:
- `$mainData` - Main transfer information
- `$detailArr` - Detail records
- `$type` - Entry type (0=full cycle, 1=from only, 2=to only)

**Accounting Logic**: Creates proper debit/credit entries based on cost center configuration

### 12. decreaseFromHandleBuyPricesHistoryBook($storemovement, $soldQuantity)
**Purpose**: Handle cost tracking when transferring inventory  
**Line**: 3231

**Business Logic**: Updates purchase price history for accurate costing

### 13. increaseHandleBuyPricesHistoryBook($storemovement)
**Purpose**: Handle cost tracking when receiving transferred inventory  
**Line**: 3296

### 14. decreaseProductParcodeSerialQuantity($moveRow, $storeId)
**Purpose**: Handle serial number transfers for barcoded products  
**Line**: 3418

**Business Logic**: Complex serial number management including:
- Find available serial numbers
- Update serial quantities
- Track serial ownership transfers
- Handle barcode product variants

---

## 🔄 Business Logic Flow

### Complete Transfer Workflow
```
┌─────────────────┐
│ Request Transfer│
│ (add operation) │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Generate Op Num │
│ & Validate      │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Decrease Source │
│ Store Inventory │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Create Pending  │
│ Transfer Record │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Goods in Transit│
│ (Physical Move) │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Receive at      │
│ Destination     │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Execute         │
│ Operation       │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Increase Dest   │
│ Store Inventory │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Complete Daily  │
│ Entry Record    │
└─────────────────┘
```

### Transfer Cancellation Workflow
```
┌─────────────────┐
│ Pending Transfer│
│ Record Exists   │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ User Requests   │
│ Cancellation    │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Restore Source  │
│ Store Inventory │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Delete Transfer │
│ Records         │
└─────────┬───────┘
          ▼
┌─────────────────┐
│ Create Audit    │
│ Trail Entry     │
└─────────────────┘
```

**Files Involved**:
- View: `/views/default/storemovement/storemovement_add.html`
- Model: `/models/dto/Storemovement.class.php`
- DAO: `/models/mysql/StoremovementMySqlDAO.class.php`
- Daily Entry: `/controllers/dailyentryfun.php`

---

## ⚠️ Common Issues

### Issue 1: Insufficient Inventory
**Problem**: Attempting to transfer more inventory than available  
**Cause**: Concurrent operations or data inconsistency  
**Fix**: Real-time inventory validation before transfer  
**Files**: Various quantity check functions

### Issue 2: Serial Number Tracking
**Problem**: Serial numbers getting lost or duplicated in transfers  
**Cause**: Complex barcode and serial number relationships  
**Fix**: Comprehensive tracking in `decreaseProductParcodeSerialQuantity()`  
**Line**: 3418

### Issue 3: Daily Entry Generation
**Problem**: Incorrect accounting entries for transfers  
**Cause**: Complex cost center and account mapping  
**Fix**: Proper configuration in `makeStoreMovementDailyEntry()`  
**Line**: 3556

### Issue 4: Permission Violations
**Problem**: Users transferring between unauthorized stores  
**Cause**: Insufficient permission checking  
**Fix**: Store-level permission validation throughout

---

## 🔗 Dependencies

### Includes
```php
include_once("../models/sql/Transaction.class.php");
include("../public/impOpreation.php");
include_once("../public/config.php");
include("../public/include_dao.php");
include_once("dailyentryfun.php");
```

### Required DAOs
- `StoremovementDAO` - Transfer operations
- `StorereportDAO` - Audit trail
- `StoredetailDAO` - Inventory management
- `StoreDAO` - Store information
- `ProductDAO` - Product data
- `OtherstoremovementDAO` - Alternative tracking
- `SizecolorstoredetailDAO` - Variant tracking
- `BuypriceshistorybookDAO` - Cost tracking
- `ProductserialDAO` - Serial numbers
- `UsergroupDAO` - Permissions

### Related Views
- `/views/default/storemovement/storemovement_add.html` - Transfer form
- `/views/default/storemovement/storemovement_show.html` - Transfer list
- `/views/default/storemovement/storemovement_edit.html` - Edit transfers

### JavaScript Files
- `/views/default/assets/js/storemovement.js` - Transfer functionality
- `/views/default/assets/js/barcode.js` - Barcode scanning

---

## 🎯 URL Routes & Actions

| Action (`?do=`) | Method | Description | View Template |
|-----------------|--------|-------------|---------------|
| (empty) | GET | Display transfer form | storemovement_add.html |
| add | POST | Create transfer | - |
| addAllStoreProducts | POST | Bulk transfer all products | - |
| show | GET | Display transfers list | storemovement_show.html |
| showdetails | GET | Show transfer details | storemovement_details.html |
| edit | GET/POST | Edit transfer | storemovement_edit.html |
| editshow | GET | Show edit form | storemovement_edit.html |
| executeOperation | POST | Finalize transfers | - |
| tempdelete | POST | Cancel pending transfer | - |
| returndelete | POST | Reverse completed transfer | - |
| recieve | POST | Receive transfer | - |
| prepare | POST | Prepare transfer | - |

---

## 📊 Transfer Operation Types

### Operation Categories
1. **Standard Transfers (operation=2)**
   - Normal store-to-store transfers
   - Full workflow with approval

2. **Deletion/Reversal (operation=1)**
   - Cancel pending transfers
   - Reverse completed transfers

3. **Bulk Operations**
   - Transfer all products from store
   - Category-based transfers

4. **Serial Number Transfers**
   - Tracked product movements
   - Barcode-based operations

---

## 🔐 Permissions & Security

### Required Permissions
- Store movement creation rights
- Source store access
- Destination store access
- Product management permissions

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

### Operation Authorization
```php
// Store supervisor permissions
$userData->storeSupervisorStores = explode(',', $userData->storeSupervisorStores);
```

---

## 📝 Notes

### Important Considerations
- All transfers must maintain accurate inventory levels
- Serial numbers require careful tracking across stores
- Daily entries must be properly generated for accounting
- Cost center allocations affect financial reporting
- Pending transfers can be cancelled; completed transfers require reversal
- Bulk operations can significantly impact performance

### Future Improvements
- [ ] Add transfer approval workflows
- [ ] Implement transfer scheduling
- [ ] Add GPS tracking for physical movements
- [ ] Implement transfer cost optimization
- [ ] Add mobile app for warehouse operations
- [ ] Implement automated transfer suggestions
- [ ] Add transfer performance analytics

---

## 📚 Related Documentation
- [Store Management](storeController.md)
- [Inventory Details](storedetailController.md)
- [Daily Entries](../accounting/dailyentry.md)
- [Warehouse Operations](../operations/warehouse.md)
- [Cost Center Accounting](../accounting/costcenter.md)