# Store Transfer Request Controller Documentation

**File**: `/controllers/storetransferrequestController.php`  
**Purpose**: Manages inter-store product transfers with delivery tracking, approvals, and inventory management  
**Last Updated**: December 21, 2024  
**Total Functions**: 29  
**Lines of Code**: ~2816

---

## 📋 Overview

The Store Transfer Request Controller is a comprehensive inventory transfer management system that handles product movement between stores with sophisticated approval workflows, delivery tracking, and financial integration. This is one of the most complex controllers in the system, providing:

- Inter-store product transfer requests and approvals
- Two-step transfer process (send request → receive confirmation)
- Delivery driver assignment and tracking
- Size/color product variant support
- Operation numbering for batch tracking
- Comprehensive inventory quantity management
- Financial integration with daily entries (accounting)
- Store report generation for audit trails
- Complex approval workflows with user permissions
- Rollback functionality for failed transfers
- Product expiry date tracking for perishables

### Primary Functions
- [x] Create transfer requests between stores
- [x] Approve/receive transfers with delivery tracking
- [x] Manage inventory quantities across stores
- [x] Track delivery status and driver assignments
- [x] Handle size/color product variants
- [x] Generate operation numbers for batching
- [x] Create comprehensive audit trails
- [x] Integrate with accounting system
- [x] Support rollback operations
- [x] Manage product serial numbers and expiry dates

### Related Controllers
- [storemovementController.php](#) - Store movement operations
- [storedetailController.php](#) - Store inventory details
- [productController.php](#) - Product management
- [dailyentryController.php](#) - Accounting integration

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storemovement** | Transfer records | transferproductid, storeidfrom, storeidto, productid, transferproductamount, operationnum, recieveType |
| **storedetail** | Store inventory | storedetailid, productid, storeid, productquantity |
| **storereport** | Audit trail | storereportid, productid, storeid, productquantity, tablename, processname |

### Product Management
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **product** | Product master | productId, productName, productCatId |
| **sizecolorstoredetail** | Size/color variants | sizeid, colorid, productid, storeid, quantity |
| **productserial** | Serial tracking | productserailid, productid, serialnumber, expireDate |

### System Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **store** | Store master | storeId, storeName |
| **user** | System users | userid, employeename, usergroupid |
| **programsettings** | System config | programsettingsid, workerbetweenstores |

---

## 🔑 Key Functions

### Core Transfer Operations

### 1. **Default Action** - Transfer Interface
**Location**: Line 179  
**Purpose**: Display the transfer request interface with store and driver selection

### 2. **add()** - Create Transfer Request
**Location**: Line 577  
**Purpose**: Create transfer requests with inventory validation and operation numbering

**Process Flow**:
1. Validate inventory availability at source store
2. Create transfer records with unique operation number
3. Update source store inventory (decrease)
4. Update destination store inventory (increase) - if immediate mode
5. Create store reports for audit trail
6. Generate daily accounting entries

### 3. **addDealWithStoreFromOnly()** - Source Store Only Processing
**Location**: Line 823  
**Purpose**: Handle transfers where only source store is processed immediately

### 4. **addDealWithStoreToOnly()** - Destination Store Processing  
**Location**: Line 524  
**Purpose**: Process destination store updates when transfers are received

### Approval and Receiving

### 5. **recieveproduct** - Product Receiving
**Location**: Line 508  
**Purpose**: Handle product receiving at destination stores with delivery confirmation

**Process Flow**:
1. Load transfer record
2. Validate receiving permissions
3. Update delivery information (driver, date)
4. Process destination store inventory updates
5. Create accounting entries for received goods

### Display and Reporting

### 6. **show** - Transfer Display Interface
**Location**: Line 256  
**Purpose**: Display transfer records with filtering options

### 7. **showByoperationnum()** - Operation-Based Display
**Location**: Multiple locations  
**Purpose**: Display transfers grouped by operation number

### 8. **showByDate()** - Date-Based Display
**Purpose**: Display transfers within date ranges

### Deletion and Rollback

### 9. **returndelete()** - Single Transfer Reversal
**Purpose**: Reverse individual transfer operations

### 10. **returndelete2()** - Batch Transfer Reversal
**Purpose**: Reverse entire operation batches

### 11. **tempdelete()** - Temporary Deletion
**Purpose**: Temporarily remove transfer records

### Utility Functions

### 12. **getStoredetailData()** - Inventory Data Retrieval
**Purpose**: Get current inventory levels for products

### 13. **insertStoredetail()** - Inventory Record Creation
**Purpose**: Create new inventory records for products

### 14. **insertStorereport()** - Audit Trail Creation
**Purpose**: Create audit trail entries for all transfers

### 15. **increaseProductQuantity()** - Inventory Increase
**Purpose**: Increase product quantities at destination stores

### 16. **decreaseProductQuantity()** - Inventory Decrease  
**Purpose**: Decrease product quantities at source stores

---

## 🔄 Workflows

### Workflow 1: Complete Transfer Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Store Transfer Request                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Create Transfer Request                                 │
│     - Select source and destination stores                 │
│     - Select products and quantities                       │
│     - Choose receive type (immediate/approval required)    │
│     - Assign delivery driver if needed                     │
│     - Generate unique operation number                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Validate and Process Request                            │
│     - Check inventory availability at source store         │
│     - Validate size/color variants if applicable           │
│     - Create transfer records in database                  │
│     - Update source store inventory (decrease)             │
│     - Create store report entries for audit                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Handle Transfer Type                                    │
│     IF immediate transfer (workerbetweenstores = 0):       │
│       ├─→ Process destination store immediately            │
│       ├─→ Update destination inventory (increase)          │
│       └─→ Create accounting entries                        │
│     ELSE (approval required):                              │
│       ├─→ Mark for delivery/approval                       │
│       ├─→ Assign to driver if specified                    │
│       └─→ Wait for receiving confirmation                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Delivery and Receiving (if approval workflow)          │
│     - Driver delivers products to destination store        │
│     - Destination store staff receives products            │
│     - Update delivery timestamps and confirmation          │
│     - Process destination store inventory updates          │
│     - Create final accounting entries                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Complete Transfer                                       │
│     - All inventory quantities updated correctly           │
│     - Accounting entries created and balanced              │
│     - Audit trail complete in store reports                │
│     - Transfer marked as completed                         │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Size/Color Product Handling
```
┌─────────────────────────────────────────────────────────────┐
│           START: Complex Product Transfer                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Parse Complex Product ID                                │
│     IF productId contains "hasSizeColor":                  │
│       ├─→ Extract base product ID                          │
│       ├─→ Extract size ID from complex string              │
│       ├─→ Extract color ID from complex string             │
│       └─→ Format: "123hasSizeColor-5-7"                   │
│           Results: productId=123, sizeId=5, colorId=7     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Handle Inventory for Variants                           │
│     - Update main product inventory (storedetail table)    │
│     - Update size/color inventory (sizecolorstoredetail)   │
│     - Ensure both records exist at source and destination  │
│     - Handle creation of missing variant records           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Transfer with Variant Data                      │
│     - Transfer includes size/color information             │
│     - Store reports include variant details                │
│     - Accounting entries account for specific variants     │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display transfer interface |
| `do=add` | `add()` | Create new transfer request |
| `do=show` | Show interface | Display transfer records |
| `do=showdetails` | Detail view | Show detailed transfer information |
| `do=recieveproduct` | `recieveproduct` | Receive products at destination |
| `do=returndelete` | `returndelete()` | Reverse single transfer |
| `do=returndelete2` | `returndelete2()` | Reverse operation batch |
| `do=tempdelete` | `tempdelete()` | Temporarily delete transfer |
| `do=tempdelete2` | `tempdelete2()` | Temporarily delete batch |
| `do=edit` | Edit interface | Edit transfer details |
| `do=editprint` | Print edit | Print editable transfer |
| `do=recieve` | Receive interface | Display receiving interface |

### Required Parameters by Action

**Create Transfer** (`do=add`):
- `storeidfrom` - Source store ID (via POST)
- `storeidto` - Destination store ID (via POST)
- `productitr` - Number of products being transferred (via POST)
- `product{N}` - Product ID for item N (via POST)
- `productamount{N}` - Transfer quantity for item N (via POST)
- `operationnum` - Operation number (via POST)
- `recieveType` - Receive type (1=immediate, 2=approval, via POST)
- `driver` - Driver ID if applicable (via POST)

**Receive Products** (`do=recieveproduct`):
- `id` - Transfer record ID (via REQUEST)
- `delivererid` - Delivery person ID if applicable (via POST)

**Show Transfers** (`do=show`):
- `from` - Start date filter (via REQUEST)
- `to` - End date filter (via REQUEST)
- `operationnum` - Operation number filter (via REQUEST)
- `storeidto` - Destination store filter (via POST)

---

## 🧮 Calculation Methods

### Inventory Quantity Updates

**Source Store Decrease**:
```php
$currentQuantity = $storeDetail->productquantity;
$newQuantity = $currentQuantity - $transferAmount;
$storeDetail->productquantity = $newQuantity;
```

**Destination Store Increase**:
```php
$currentQuantity = $storeDetail->productquantity;
$newQuantity = $currentQuantity + $transferAmount;
$storeDetail->productquantity = $newQuantity;
```

**Size/Color Variant Updates**:
```php
// Update both main inventory and variant inventory
$sizeColorDetail = $sizeColorDAO->load($sizeColorStoreDetailId);
$newVariantQty = $sizeColorDetail->quantity - $transferAmount;
$sizeColorDetail->quantity = $newVariantQty;
```

### Operation Number Generation
```php
// Get next operation number
$nextId = $myStoremovementEx->queryAlloperationnum();
$last_val = $nextId[0];
$operationNum = $last_val->operationnum + 1;
```

---

## 🔒 Security & Permissions

### Authentication
- All operations require authentication
- User permissions control store access
- Store supervisor permissions for receiving

### Store Access Control
```php
$userData = $userDAO->load($_SESSION['userid']);
$userData->storeSupervisorStores = explode(',', $userData->storeSupervisorStores);
```

### Transaction Safety
- Database transactions ensure data integrity
- Rollback capability for failed operations
- Validation before inventory updates

---

## 📊 Performance Considerations

### Critical Indexes Required
1. `storemovement(operationnum, transferproductdate)`
2. `storedetail(productid, storeid)`  
3. `sizecolorstoredetail(productid, storeid, sizeid, colorid)`
4. `storereport(tablename, recordid)`

### Optimization Tips
- Batch operations by operation number
- Use transactions for consistency
- Consider caching for frequently accessed stores/products
- Optimize size/color variant queries

---

## 🐛 Common Issues & Troubleshooting

### 1. **Inventory Sync Issues**
**Issue**: Source and destination inventories don't balance  
**Cause**: Transaction failures or partial updates

### 2. **Operation Number Conflicts**
**Issue**: Duplicate operation numbers generated  
**Cause**: Concurrency in operation number generation

### 3. **Size/Color Variant Problems**
**Issue**: Complex product IDs not parsing correctly  
**Cause**: Incorrect format or missing variant data

### 4. **Approval Workflow Issues**
**Issue**: Transfers stuck in pending state  
**Cause**: Missing delivery confirmation or permission issues

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [storemovementController.php](#) - Store movement operations
- [storedetailController.php](#) - Store inventory management
- [dailyentryController.php](#) - Accounting integration

---

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