# Store Asked Reflux Controller Documentation

**File**: `/controllers/storeAskedRefluxController.php`  
**Purpose**: Inter-store transfer management system with approval workflow and inventory tracking  
**Last Updated**: December 21, 2024  
**Total Functions**: 15+  
**Lines of Code**: ~2,000+

---

## 📋 Overview

The Store Asked Reflux Controller manages complex inter-store transfer operations with approval workflows and inventory tracking. It handles:
- Multi-step store transfer processes with approval workflows
- Size/color variant product transfers
- Driver management and delivery tracking
- Operation number generation and tracking
- Store supervisor approval systems
- Inventory validation and adjustment
- Complete audit trail for all transfers
- Transaction rollback capabilities for data integrity

### Primary Functions
- [x] Inter-store product transfer management
- [x] Multi-step approval workflow (request → approval → delivery)
- [x] Size/color variant handling
- [x] Driver assignment and tracking
- [x] Operation number generation and tracking
- [x] Inventory validation before transfers
- [x] Complete audit trail and reporting
- [x] Transaction management with rollback

### Related Controllers
- [storemovementController.php](#) - Basic store movements
- [storeHousingController.php](storeHousingController.md) - Inventory management
- [inventoryController.php](#) - Core inventory operations
- [userController.php](#) - User and driver management

---

## 🗄️ Database Tables

### Primary Transfer Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storemovement** | Store transfer operations | transferproductid, operationnum, storeidfrom, storeidto, productid, transferproductamount, userid, conditions |
| **storedetail** | Store inventory levels | storedetailid, productid, storeid, productquantity, userid |
| **storereport** | Transfer audit trail | storereportid, productid, storeid, productquantity, productbefore, productafter, processname, tablename |
| **sizecolorstoredetail** | Size/color variant inventory | sizecolorstoredetailid, productid, storeid, sizeid, colorid, quantity |

### Workflow Management Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storemovement** (workflow fields) | Transfer workflow status | recieveType, recieveUserid, recieveTime, delivererid, deliverdate, driverid, drivertimeout, driverdate |
| **buypriceshistorybook** | Cost tracking for transfers | buypriceshistorybookid, productid, storeid, buyprice, buyquantity |
| **productserial** | Serial number tracking | productserialid, productid, storeid, serialnumber, expiredate |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **store** | Store information | storeId, storeName |
| **product** | Product master data | productId, productName |
| **user** | Users including drivers | userid, employeename, usergroupid, storeSupervisorStores |
| **usergroup** | User role management | usergroupid, groupname |

---

## 🔑 Key Functions

### 1. **Default Action** - Transfer Request Interface
**Location**: Line 188  
**Purpose**: Display the main transfer request interface

**Process Flow**:
1. Load authentication and permissions
2. Load available stores based on user permissions
3. Load driver information (user group "سائقين")
4. Generate next operation number
5. Display transfer request form

**Key Features**:
- Multi-store access control
- Driver selection interface
- Operation number auto-generation
- Store permission validation

---

### 2. **add()** - Full Transfer Process
**Location**: Line 652  
**Purpose**: Complete transfer process with inventory validation

**Function Signature**:
```php
function add()
```

**Process Flow**:
1. Pre-validate all products for sufficient quantity
2. Process each product in transaction
3. Handle size/color variants
4. Decrease source store inventory
5. Increase destination store inventory
6. Create audit trail entries
7. Generate operation number

**Key Variables**:
- `$storeidfrom` / `$storeidto` - Source and destination stores
- `$operationnum` - Unique operation identifier
- `$productItr` - Number of products being transferred
- `$productsBeforeValid` - Validation flag

---

### 3. **addDealWithStoreFromOnly()** - Source Store Processing
**Location**: Line 896  
**Purpose**: Handle transfers that only affect source store (approval pending)

**Process Flow**:
1. Similar to add() but only processes source store
2. Used when destination approval is required
3. Creates pending transfer records
4. Awaits confirmation from destination store

---

### 4. **addDealWithStoreToOnly()** - Destination Store Processing
**Location**: Line 1099  
**Purpose**: Complete transfer by processing destination store

**Function Signature**:
```php
function addDealWithStoreToOnly($storeMovementObject)
```

**Process Flow**:
1. Load existing transfer record
2. Process destination store inventory increase
3. Update cost tracking
4. Complete transfer workflow
5. Update audit trail

---

### 5. **show Actions** - Transfer Reporting
**Multiple locations**  
**Purpose**: Various reporting and tracking functions

**Key Functions**:
- `showByDate()` - Date range transfer reports
- `showByoperationnum()` - Operation-specific details
- `showBystoreidfrom()` - Store-specific reports

---

## 🔄 Workflows

### Workflow 1: Complete Inter-Store Transfer Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Store Transfer Request                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Initialize Transfer Request                             │
│     - Select source and destination stores                 │
│     - Choose products and quantities                       │
│     - Assign driver (if required)                          │
│     - Generate operation number                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Validate Inventory Availability                        │
│     FOR EACH product in transfer:                          │
│       │                                                     │
│       ├─→ Check if size/color variant                      │
│       │   YES: Parse complex product ID                    │
│       │   NO:  Use regular product ID                      │
│       │                                                     │
│       ├─→ Load current inventory in source store           │
│       │                                                     │
│       ├─→ Validate sufficient quantity available           │
│       │   IF insufficient: ABORT entire transfer          │
│       │   ELSE: Continue validation                        │
│       │                                                     │
│       └─→ Mark product as validated for transfer           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Transfer Based on Workflow Type                │
│     IF workerbetweenstores = 0: (Direct transfer)          │
│       └─→ Call add() - full immediate transfer             │
│     ELSE: (Approval required)                              │
│       └─→ Call addDealWithStoreFromOnly()                  │
│           └─→ Process source store only                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Source Store Processing                                 │
│     FOR EACH validated product:                            │
│       │                                                     │
│       ├─→ Create storemovement record                      │
│       │   ├─ Assign operation number                       │
│       │   ├─ Set transfer details                          │
│       │   └─ Set workflow status                           │
│       │                                                     │
│       ├─→ Update source store inventory                    │
│       │   IF size/color variant:                           │
│       │     ├─ Update sizecolorstoredetail                │
│       │     └─ Recalculate parent product total           │
│       │   ELSE:                                             │
│       │     └─ Update storedetail directly                │
│       │                                                     │
│       ├─→ Create audit trail entry                        │
│       │   ├─ Record quantity change                        │
│       │   ├─ Log operation type                            │
│       │   └─ Link to operation number                     │
│       │                                                     │
│       └─→ Sync with accounting system                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Destination Processing (if immediate transfer)         │
│     IF direct transfer (workerbetweenstores = 0):          │
│       │                                                     │
│       ├─→ Check if destination inventory record exists     │
│       │   YES: Update existing quantity                    │
│       │   NO:  Create new storedetail record              │
│       │                                                     │
│       ├─→ Handle size/color variants in destination        │
│       │                                                     │
│       ├─→ Update cost tracking                             │
│       │   ├─ Copy buy price history                        │
│       │   └─ Update serial numbers                         │
│       │                                                     │
│       └─→ Create destination audit trail                   │
│     ELSE:                                                   │
│       └─→ Leave for approval workflow                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Approval Workflow (if required)                        │
│     - Transfer appears in destination store's pending list │
│     - Store supervisor reviews transfer request            │
│     - IF approved: Call addDealWithStoreToOnly()           │
│     - IF rejected: Call returndelete() to reverse          │
│     - Update workflow status and timestamps                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  7. Driver and Delivery Management                         │
│     IF driver assigned:                                     │
│       │                                                     │
│       ├─→ Record driver assignment                         │
│       │                                                     │
│       ├─→ Track delivery time expectations                 │
│       │                                                     │
│       ├─→ Calculate late fees if exceeded                  │
│       │                                                     │
│       └─→ Update delivery confirmation                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  8. Complete Transaction                                    │
│     - Commit all database changes                          │
│     - Generate daily entry for accounting                  │
│     - Send success/error notifications                     │
│     - Update operation status                              │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display transfer request interface |
| `do=add` | `add()` or `addDealWithStoreFromOnly()` | Process new transfer request |
| `do=show` | `showByDate2()` | Display transfers with filtering |
| `do=showdetails` | `showByDate()` | Detailed transfer reports |
| `do=recieveproduct` | Approval processing | Approve pending transfer |
| `do=returndelete` | `returndelete()` | Cancel individual transfer |
| `do=returndelete2` | `returndelete2()` | Cancel entire operation |
| `do=tempdelete` | `tempdelete()` | Temporary deletion |
| `do=edit` | `edit()` | Edit transfer details |
| `do=editprint` | `editprint()` | Print transfer document |

### Required Parameters by Action

**Transfer Request** (`do=add`):
- `storeidfrom` - Source store ID
- `storeidto` - Destination store ID
- `productitr` - Number of products
- `product{N}` - Product ID for item N
- `productamount{N}` - Quantity for item N
- `driver` - Driver ID (optional)
- `recieveType` - Workflow type

**Search/Filter** (`do=show`):
- `from` - Start date
- `to` - End date
- `operationnum` - Operation number filter
- `storeidfrom` - Store filter

---

## 🧮 Calculation Methods

### Size/Color Variant Processing
```php
// Parse complex product ID for variants
if (strpos($productId, "hasSizeColor") !== false) {
    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
    $productId = $productIdComplex[0];
    $sizeId = $productIdComplex[1];
    $colorId = $productIdComplex[2];
    
    // Load size/color specific inventory
    $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX(
        $productId, $storeid, $sizeId, $colorId
    );
}
```

### Inventory Validation Logic
```php
// Pre-validation before transfer processing
$productsBeforeValid = 1;
if ($productquantityFromBefore > 0 && count($allStoredetailFromData) > 0) {
    $productsAfterValid = $productquantityFromBefore - $transferproductAmount;
    
    if ($productsAfterValid >= 0) {
        $productsBeforeValid = 1;  // Sufficient inventory
    } else {
        $productsBeforeValid = 0;  // Insufficient inventory - abort
    }
} else {
    $productsBeforeValid = 0;  // No inventory record
}
```

### Driver Time Tracking
```php
// Calculate delivery delays
if ($mystoremovementData->driverid > 0) {
    if ($mystoremovementData->deliverdate == NULL) {
        $mystoremovementData->deliverdate = date("Y-m-d H:i:s");
    }
    
    $hours = dateTimeDiff($mystoremovementData->driverdate, $mystoremovementData->deliverdate);
    if ($hours > $mystoremovementData->drivertimeout) {
        $mystoremovementData->lateHours = $hours - $mystoremovementData->drivertimeout;
    } else {
        $mystoremovementData->lateHours = 0;
    }
}
```

### Operation Number Generation
```php
// Generate unique operation numbers using stored procedure
if ($i == 1) {
    $spData = $myStoremovementEx->callInsertUniqueOptNumSP($myStoremovement);
    $transferproductId = $spData->id;
    $operationnum = $spData->optnum;
    $myStoremovement->operationnum = $operationnum;
} else {
    $transferproductId = $myStoremovementRecord->insert($myStoremovement);
}
```

---

## 🔒 Security & Permissions

### Store Access Control
```php
// Multi-store vs single-store access
if ($_SESSION['searchinonestore'] == 0) {
    if ($_SESSION['storeids'] == 0) {
        $stores = $myStoreEx->queryByConditions();  // All stores
    } else {
        $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
    }
} else {
    $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = ' . $_SESSION['storeid']);
}
```

### Store Supervisor Validation
```php
// Check if user can supervise specific stores
$userData = $userDAO->load($_SESSION['userid']);
$userData->storeSupervisorStores = explode(',', $userData->storeSupervisorStores);

// Validate supervisor permissions for approval
if (in_array($storeidto, $userData->storeSupervisorStores)) {
    // User can approve transfers to this store
}
```

### Transaction Security
```php
// All critical operations wrapped in transactions
$mytransactions = new Transaction();
try {
    // Process transfer operations
    // Multiple database updates
    $mytransactions->commit();
} catch (Exception $ex) {
    $mytransactions->rollback();
    $product_arr = array('error');
}
```

---

## 📊 Performance Considerations

### Transaction Management
1. **Atomic Operations**:
   - All transfers processed in single transaction
   - Rollback capability for data integrity
   - Pre-validation prevents partial failures

2. **Batch Processing**:
   - Multiple products processed efficiently
   - Minimal database round trips
   - Bulk audit trail creation

3. **Index Requirements**:
   - `storemovement(operationnum, storeidfrom, storeidto)`
   - `storedetail(productid, storeid)`
   - `sizecolorstoredetail(productid, storeid, sizeid, colorid)`

### Performance Monitoring
```php
// Monitor for slow operations
$startTime = microtime(true);
for ($h = 1; $h <= $productItr; $h++) {
    // Process each product
}
$processingTime = microtime(true) - $startTime;

if ($processingTime > 30.0) {
    error_log("Slow transfer operation: " . $processingTime . "s for " . $productItr . " products");
}
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Transfer Validation Failures**
**Issue**: Transfers fail with "insufficient inventory" errors  
**Cause**: Concurrent operations or inventory sync issues

**Debug**:
```php
// Check actual inventory vs expected
$storedetailData = getStoredetailData($storeidfrom, $productId, $sizeColorStoreDetailId, $sizeId, $colorId);
echo "Current Inventory: " . $storedetailData[2] . "<br>";
echo "Transfer Amount: " . $transferproductAmount . "<br>";
echo "Remaining: " . ($storedetailData[2] - $transferproductAmount) . "<br>";
```

### 2. **Size/Color Variant Issues**
**Issue**: Variant transfers not processing correctly  
**Cause**: Complex product ID parsing or missing variant records

**Fix**:
```php
// Verify variant parsing
if (strpos($productId, "hasSizeColor") !== false) {
    echo "Original: " . $productId . "<br>";
    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
    echo "Product: " . $productIdComplex[0] . "<br>";
    echo "Size: " . $productIdComplex[1] . "<br>";
    echo "Color: " . $productIdComplex[2] . "<br>";
}
```

### 3. **Operation Number Conflicts**
**Issue**: Duplicate operation numbers or missing sequences  
**Cause**: Stored procedure issues or concurrent access

**Fix**:
```php
// Check operation number generation
$nextId = $myStoremovementEx->queryAlloperationnum();
echo "Next Operation Number: " . ($nextId[0]->operationnum + 1);

// Verify uniqueness
$existing = $myStoremovementEx->querybyoperationnum($operationnum);
if (count($existing) > 0) {
    echo "Warning: Operation number already exists!";
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Transfer Validation
```
1. Create source store with known inventory
2. Attempt transfer of various quantities
3. Verify validation prevents over-transfers
4. Check audit trail completeness
5. Confirm inventory accuracy after transfer
```

### Test Case 2: Size/Color Variant Transfer
```
1. Set up products with multiple size/color variants
2. Transfer specific variants between stores
3. Verify variant-specific inventory updates
4. Check parent product total recalculation
5. Confirm audit trail captures variant details
```

### Test Case 3: Approval Workflow
```
1. Configure workerbetweenstores = 1 (approval required)
2. Create transfer request from Store A to Store B
3. Verify source store inventory decreases
4. Confirm destination shows pending approval
5. Approve transfer and verify completion
6. Test rejection and inventory restoration
```

### Test Case 4: Driver Management
```
1. Assign driver to transfer operation
2. Set delivery timeout expectations
3. Simulate delivery confirmation
4. Test late delivery calculation
5. Verify driver performance tracking
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [storeHousingController.md](storeHousingController.md) - Inventory management
- [inventoryController.md](#) - Core inventory operations
- [dailyentry.php](#) - Accounting integration
- [Database Schema Documentation](#) - Table relationships

---

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