# Movement Management Controller Documentation

**File**: `/controllers/movementmanageController.php`  
**Purpose**: Tracks and reports user activities and system operations across the ERP system  
**Last Updated**: December 20, 2024  
**Total Functions**: 10  
**Lines of Code**: ~282

---

## 📋 Overview

The Movement Management Controller provides comprehensive audit trail and user activity tracking functionality. It manages:
- User activity logging and monitoring
- System operation tracking across all modules
- Detailed audit reports with filtering capabilities
- User behavior analysis and reporting
- Movement data archival and cleanup
- Security monitoring and access tracking
- Performance analytics for system usage

### Primary Functions
- [x] Display user movement reports with filtering
- [x] Track operations by date range
- [x] Filter activities by specific users
- [x] Monitor specific operation types
- [x] Combine multiple filter criteria
- [x] Archive old movement data
- [x] Maintain deleted movement records
- [x] User activity analytics

### Related Controllers
- [userController.php](#) - User management
- [usergroupController.php](#) - User group permissions
- All system controllers contribute movement data

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **movementmanage** | Active user movements | movementmanageid, operationname, movementmanagedate, userid, currentDo, ip, mac, deviceType |
| **movementmanagedeleted** | Archived movements | movementmanagedeleted, operationname, movementmanagedate, userid, currentDo, ip, mac, deviceType |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, employeename, viewclients, viewbills, usergroupid |
| **usergroup** | User permission groups | usergroupid, usergroupname |
| **youtubelink** | Tutorial references | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default Action (show)** - Movement Report Display
**Location**: Lines 88-150  
**Purpose**: Main interface for viewing user movement reports with advanced filtering

**Function Signature**:
```php
if (empty($do) || $do == "show")
```

**Input Parameters**:
- `from` / `to` - Date range filters
- `usersearchid` - Specific user filter
- `operationname` - Operation type filter
- `nameopration` - Operation display name

**Process Flow**:
1. Load user data for dropdown filters
2. Load YouTube tutorials for help system
3. Parse filter parameters from request
4. Execute appropriate filtering function based on criteria
5. Generate descriptive message for report header
6. Display results via movement template

**Complex Filter Logic**:
```php
// Filter combinations with priority
if (date range AND no user AND no operation) {
    showByDate($startDate, $endDate);
} elseif (user only AND no date AND no operation) {
    showByUser($userSearchId);
} elseif (operation only AND no date AND no user) {
    showByOperationName($operationName);
} elseif (date range AND user AND no operation) {
    showByDateAndUser($startDate, $endDate, $userSearchId);
} elseif (date range AND operation AND no user) {
    showByDateAndOperationName($startDate, $endDate, $operationName);
} elseif (user AND operation AND no date) {
    showByUserAndOperationName($userSearchId, $operationName);
}
```

---

### 2. **loadUser()** - User Data Loading
**Location**: Lines 172-178  
**Purpose**: Load active users for filter dropdown

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

**Process Flow**:
1. Query users with conditions = 0 (active only)
2. Return user array for template assignment

---

### 3. **showByDate()** - Date Range Filtering
**Location**: Lines 189-199  
**Purpose**: Display movements within specific date range

**Function Signature**:
```php
function showByDate($startDate, $endDate)
```

**Process Flow**:
1. Query active movements within date range
2. Query deleted movements within same range
3. Assign both datasets to template
4. Generate combined report

**Data Sources**:
- `movementmanageData` - Active movement records
- `movementmanageDataDel` - Archived movement records

---

### 4. **showByUser()** - User-Specific Reports
**Location**: Lines 201-211  
**Purpose**: Display all movements for a specific user

**Function Signature**:
```php
function showByUser($userSearchId)
```

**Process Flow**:
1. Query movements filtered by user ID
2. Include both active and deleted records
3. Provide complete user activity history

---

### 5. **showByOperationName()** - Operation Type Reports
**Location**: Lines 213-223  
**Purpose**: Display movements for specific operation types

**Function Signature**:
```php
function showByOperationName($operationName)
```

**Process Flow**:
1. Filter movements by operation name
2. Show system-wide usage of specific features
3. Include archived data for complete picture

**Operation Examples**:
- `sellbillController.php` - Sales operations
- `buyBillController.php` - Purchase operations
- `clientController.php` - Customer management
- `productController.php` - Product management

---

### 6. **showByDateAndUser()** - Combined Date/User Filter
**Location**: Lines 225-235  
**Purpose**: User activity within specific date range

**Function Signature**:
```php
function showByDateAndUser($startDate, $endDate, $userSearchId)
```

**Business Use Cases**:
- Employee productivity tracking
- Security auditing for specific users
- Time-based activity analysis

---

### 7. **showByDateAndOperationName()** - Combined Date/Operation Filter
**Location**: Lines 237-247  
**Purpose**: System feature usage within date range

**Function Signature**:
```php
function showByDateAndOperationName($startDate, $endDate, $operationName)
```

**Business Use Cases**:
- Feature adoption tracking
- System performance analysis
- Module usage statistics

---

### 8. **showByUserAndOperationName()** - Combined User/Operation Filter
**Location**: Lines 249-259  
**Purpose**: Specific user's usage of specific operations

**Function Signature**:
```php
function showByUserAndOperationName($userSearchId, $operationName)
```

**Business Use Cases**:
- Individual training needs assessment
- Role-based usage analysis
- Security monitoring for sensitive operations

---

### 9. **delete()** - Movement Data Archival
**Location**: Lines 152-160 and 261-280  
**Purpose**: Archive old movement data and clean up active table

**Function Signature**:
```php
function delete($startDate, $endDate)
```

**Process Flow**:
1. Query movements to be archived within date range
2. Copy each record to `movementmanagedeleted` table
3. Preserve all original data fields
4. Delete records from active `movementmanage` table
5. Redirect to success page

**Archival Logic**:
```php
$dataThatWillBeDeleted = $myMovementmanageEx->queryAllWithOpnameAndDateSimple($startDate, $endDate);
foreach ($dataThatWillBeDeleted as $value) {
    $movementManageDeleted->operationname = $value->operationname;
    $movementManageDeleted->movementmanagedate = $value->movementmanagedate;
    $movementManageDeleted->userid = $value->userid;
    $movementManageDeleted->currentDo = $value->currentDo;
    $movementManageDeleted->ip = $value->ip;
    $movementManageDeleted->mac = $value->mac;
    $movementManageDeleted->deviceType = $value->deviceType;
    $movementManageDeletedDAO->insert($movementManageDeleted);
}
$myMovementmanageEx->deleteByMovementmanagedateEX($startDate, $endDate);
```

**Data Preservation**: Complete movement history maintained in archive table

---

## 🔄 Workflows

### Workflow 1: User Activity Analysis
```
┌─────────────────────────────────────────────────────────────┐
│              START: Analyze User Activity                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Analysis Criteria                                │
│     - Choose date range (optional)                         │
│     - Select specific user (optional)                      │
│     - Pick operation type (optional)                       │
│     - Combine multiple filters                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Execute Filtered Query                                  │
│     Based on filter combination:                           │
│       ├─→ Date only: Show system activity by date         │
│       ├─→ User only: Show all user operations             │
│       ├─→ Operation only: Show feature usage              │
│       ├─→ Date + User: User activity in timeframe         │
│       ├─→ Date + Operation: Feature usage by date         │
│       └─→ User + Operation: User's specific feature use   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Display Comprehensive Report                           │
│     - Active movement data                                  │
│     - Archived movement data                               │
│     - Combined timeline view                               │
│     - User performance metrics                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Analysis and Actions                                    │
│     - Identify usage patterns                              │
│     - Security audit results                               │
│     - Performance optimization insights                    │
│     - Training needs assessment                            │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Movement Data Lifecycle
```
┌─────────────────────────────────────────────────────────────┐
│                Movement Data Lifecycle                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Movement Creation                                       │
│     - User performs system operation                       │
│     - Movement automatically logged                        │
│     - Stored in movementmanage table                       │
│     - Includes: operation, user, timestamp, IP, MAC        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Active Monitoring Phase                                │
│     - Data available for real-time reports                 │
│     - Used for current period analysis                     │
│     - Security monitoring and alerts                       │
│     - Performance tracking                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Archival Decision                                       │
│     - Administrator selects date range for cleanup         │
│     - Data beyond retention period identified              │
│     - Archive process initiated                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Data Archival Process                                   │
│     - Copy to movementmanagedeleted table                  │
│     - Preserve all original data fields                    │
│     - Verify data integrity                                │
│     - Remove from active table                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Historical Reporting                                    │
│     - Archived data remains searchable                     │
│     - Combined reports include both datasets               │
│     - Long-term trend analysis possible                    │
│     - Compliance audit trail maintained                    │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | show() | Display movement reports interface |
| `do=show` | show() | Same as empty - main reporting |
| `do=delete` | delete() | Archive movement data by date range |
| `do=sucess` | Success page | Show operation success message |
| `do=error` | Error page | Show operation error message |

### Filter Parameters (GET/POST)
| Parameter | Type | Description |
|-----------|------|-------------|
| `from` | Date | Start date for filtering (YYYY-MM-DD) |
| `to` | Date | End date for filtering (YYYY-MM-DD) |
| `usersearchid` | Integer | User ID filter |
| `operationname` | String | Operation type filter |
| `nameopration` | String | Operation display name (POST) |

### Delete Operation (POST)
| Parameter | Type | Description |
|-----------|------|-------------|
| `from2` | Date | Start date for archival |
| `to2` | Date | End date for archival |

---

## 🧮 Calculation Methods

### Report Message Generation
```php
// Dynamic message building based on filters
$message = "تقرير حركة المستخدمين";

if (isset($startDate) && $startDate != "") {
    $message .= " من تاريخ:" . $startDate . "الى تاريخ :" . $endDate;
}

if (isset($userSearchId) && $userSearchId != "-1") {
    $myuserdata = $myUserRecord->load($userSearchId);
    $message .= " للموظف :" . $myuserdata->employeename;
}

if (isset($operationName) && $operationName != "-1") {
    $message .= " فى عمليه :" . $nameopration;
}
```

### User Permission Integration
```php
$userGroup = $myUserGroupRecord->load($_SESSION['usergroupid']);
$smarty->assign("userGroup", $userGroup);
$smarty->assign("sessionuserid", $_SESSION['userid']);
```

---

## 🔒 Security & Permissions

### User Group Authorization
```php
// Load user group permissions for access control
$userGroup = $myUserGroupRecord->load($_SESSION['usergroupid']);
```

### Session-Based Access
- All operations require valid user session
- User ID tracked for audit purposes
- Permission level checking via user groups

### Sensitive Data Protection
- IP and MAC address tracking for security
- Device type identification
- Complete audit trail for compliance

---

## 📊 Performance Considerations

### Database Optimization
1. **Critical Indexes Needed**:
   - `movementmanage(movementmanagedate, userid)`
   - `movementmanage(operationname, movementmanagedate)`
   - `movementmanagedeleted(movementmanagedate, userid)`
   - `movementmanagedeleted(operationname, movementmanagedate)`

2. **Query Performance**:
   - Date range queries should use indexed columns
   - Extended DAO methods provide optimized queries
   - Archive cleanup improves active table performance

### Memory Management
- Large date ranges may return significant data
- Consider pagination for very large result sets
- Archive process handles bulk operations efficiently

### Archival Strategy
```php
// Efficient bulk archival process
foreach ($dataThatWillBeDeleted as $value) {
    // Copy to archive table
    $movementManageDeletedDAO->insert($movementManageDeleted);
}
// Bulk delete from active table
$myMovementmanageEx->deleteByMovementmanagedateEX($startDate, $endDate);
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Large Dataset Performance**
**Issue**: Reports slow with large movement datasets  
**Cause**: Missing database indexes on filter columns

**Fix**: Add compound indexes:
```sql
CREATE INDEX idx_movement_date_user ON movementmanage(movementmanagedate, userid);
CREATE INDEX idx_movement_operation_date ON movementmanage(operationname, movementmanagedate);
```

### 2. **Archival Process Failures**
**Issue**: Archive operation fails partway through  
**Cause**: Transaction not properly handled

**Fix**: Wrap in transaction:
```php
try {
    R::begin();
    // Archive operations
    R::commit();
} catch (Exception $e) {
    R::rollback();
    throw $e;
}
```

### 3. **Memory Issues with Large Archives**
**Issue**: Out of memory during large archival operations  
**Cause**: Loading entire dataset into memory

**Fix**: Process in batches:
```php
$batchSize = 1000;
$offset = 0;
do {
    $batch = $myMovementmanageEx->queryBatch($startDate, $endDate, $offset, $batchSize);
    // Process batch
    $offset += $batchSize;
} while (count($batch) > 0);
```

### 4. **Filter Combination Logic**
**Issue**: Complex filter combinations not working correctly  
**Cause**: Incorrect boolean logic in filter processing

**Fix**: Simplify filter logic with clear precedence:
```php
$hasDate = !empty($startDate) && !empty($endDate);
$hasUser = !empty($userSearchId) && $userSearchId != "-1";
$hasOperation = !empty($operationName) && $operationName != "-1";

if ($hasDate && $hasUser && $hasOperation) {
    // All three filters
} elseif ($hasDate && $hasUser) {
    // Date and user
} // Continue with clear logic
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Movement Reporting
```
1. Access movement reports with no filters
2. Apply date range filter and verify results
3. Filter by specific user and check data
4. Test operation type filtering
```

### Test Case 2: Complex Filter Combinations
```
1. Combine date range with user filter
2. Test date range with operation filter
3. Apply user and operation filters together
4. Verify all combinations work correctly
```

### Test Case 3: Data Archival Process
```
1. Create test movement data
2. Run archival process for specific date range
3. Verify data moved to archive table
4. Confirm data removed from active table
5. Test archived data still searchable
```

### Test Case 4: Performance Testing
```
1. Generate large movement dataset
2. Test report performance with various filters
3. Measure archival process speed
4. Verify memory usage within limits
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [User Management Documentation](#) - User and group setup
- [System Audit Guide](#) - Compliance and security
- [Database Maintenance Guide](#) - Performance optimization

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When archival strategy needs optimization