# Other Requests Controller Documentation

**File**: `/controllers/otherrequests.php`  
**Purpose**: Internal communication and request management system for branches, user groups, and individual users  
**Last Updated**: December 20, 2024  
**Total Functions**: 4  
**Lines of Code**: ~364

---

## 📋 Overview

The Other Requests Controller manages internal communication and request routing within the organization. It provides a structured system for:
- Creating requests directed to branches, user groups, or individual users
- Managing request workflows and approvals
- Tracking request status and completion
- Providing hierarchical request visibility based on user permissions
- Supporting multi-level organizational communication
- Handling request editing and lifecycle management

### Primary Functions
- [x] Create requests with flexible targeting (branch, group, user)
- [x] Display requests based on user permissions and organizational hierarchy
- [x] Edit and update existing requests
- [x] Manage request status and visibility
- [x] Support multi-branch and multi-group request routing
- [x] Track request seen/unseen status
- [x] Handle request deletion and archiving

### Related Controllers
- [userController.php](userController.md) - User management
- [usergroupController.php](#) - User group management
- [branchesController.php](#) - Branch management
- [employeeController.php](#) - Employee management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **otherrequest** | Request master records | id, requestTitle, comment, requestTo, requestToId, userId, branchId, requestDate, seen, deleted |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users/employees | userid, username, employeename, branchId, usergroupid |
| **usergroup** | User group definitions | usergroupid, usergroupname |
| **branch** | Organization branches | branchId, branchName |

---

## 🔑 Key Functions

### 1. **Default Action** - Request Creation Form
**Location**: Lines 53-74  
**Purpose**: Display request creation interface with reference data

**Function Signature**:
```php
// Triggered when: empty $do
```

**Process Flow**:
1. Load all branches for targeting options
2. Load all user groups for targeting
3. Load all users for individual targeting
4. Display request creation form

**Reference Data Loading**:
```php
// Load branches for dropdown
$branches = $BranchDAO->queryAll();
$smarty->assign('branches', $branches);

// Load user groups for dropdown
$userGroup = $userGroupDAO->queryAll();
$smarty->assign('userGroups', $userGroup);

// Load users for individual targeting
$user = $userDAO->queryAll();
$smarty->assign('users', $user);
```

---

### 2. **add()** - Create New Request
**Location**: Lines 301-331  
**Purpose**: Process request creation with flexible targeting

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

**Process Flow**:
1. Determine request target type from form
2. Extract appropriate target ID based on type
3. Create request record with metadata
4. Set initial status (unseen, not deleted)
5. Save request to database

**Target Type Resolution**:
```php
$requestTo = filter_input(INPUT_POST, "requestTo");
if ($requestTo == 2) {
    $requestToSelectName = 'userId';        // Individual user
} elseif ($requestTo == 1) {
    $requestToSelectName = 'userGroupId';   // User group
} else {
    $requestToSelectName = 'branchId';      // Branch
}

$requestToId = filter_input(INPUT_POST, $requestToSelectName);
```

**Request Creation**:
```php
$otherRequest->comment = filter_input(INPUT_POST, "comment");
$otherRequest->requestDate = date('Y-m-d');
$otherRequest->requestTitle = filter_input(INPUT_POST, "requestTitle");
$otherRequest->requestTo = $requestTo;
$otherRequest->requestToId = $requestToId;
$otherRequest->userId = $_SESSION['userid'];
$otherRequest->branchId = $_SESSION['branchId'];
$otherRequest->seen = 0;        // Not yet seen
$otherRequest->deleted = 0;     // Not deleted

$otherRequestDAO->insert($otherRequest);
```

---

### 3. **show** - Request Dashboard with Permission-Based Filtering
**Location**: Lines 168-259  
**Purpose**: Display requests based on user's organizational position and permissions

**Function Signature**:
```php
// Triggered when: $do == "show"
```

**Process Flow**:
1. Determine user's organizational context (branch, user group)
2. Build permission-based queries for different request types
3. Execute queries to get relevant requests
4. Organize requests by type and assignment
5. Display comprehensive request dashboard

**Permission-Based Request Loading**:

#### Branch-Level Permissions:
```php
$branchId = $_SESSION['branchId'];         // 0 = all branches, else specific branch
$userGroupId = $userdata->usergroupid;     // 1 = admin, else specific group
$userId = $_SESSION['userid'];

if ($branchId == 0) {
    // User can see all branches
    
    // My branch requests (from branch 0 = headquarters)
    $string1 = 'and o.branchId = ' . $branchId . ' ';
    $myBranchRequests = $otherRequestEX->getRequestsWithStringEx($string1, ' 0 , 1 ', 0);
    
    // Requests to all branches
    $string2 = 'and o.requestTo = 0 ';
    $toBranchRequests = $otherRequestEX->getRequestsWithStringEx($string2, ' 0 , 1 ', 0);
    
} else {
    // User limited to specific branch
    
    // My branch requests
    $string1 = 'and o.branchId = ' . $branchId . ' ';
    $myBranchRequests = $otherRequestEX->getRequestsWithString($string1, ' 0 , 1 ', 0);
    
    // Requests to my specific branch
    $string2 = 'and o.requestTo = 0 and o.requestToId = ' . $branchId . ' ';
    $toBranchRequests = $otherRequestEX->getRequestsWithString($string2, ' 0 , 1 ', 0);
}
```

#### User Group-Level Permissions:
```php
if ($userGroupId == 1) {
    // Admin can see all user group requests
    $string3 = 'and o.requestTo = 1 ';
    $toGroupRequests = $otherRequestEX->getRequestsWithStringEx($string3, ' 0 , 1 ', 0);
    
    $string4 = 'and o.requestTo = 2 ';
    $toUserRequests = $otherRequestEX->getRequestsWithStringEx($string4, ' 0 , 1 ', 0);
} else {
    // User limited to own group
    $string3 = 'and o.requestTo = 1 and o.requestToId = ' . $userGroupId . ' ';
    $toGroupRequests = $otherRequestEX->getRequestsWithString($string3, ' 0 , 1 ', 0);
    
    $string4 = 'and o.requestTo = 2 and o.requestToId = ' . $userId . ' ';
    $toUserRequests = $otherRequestEX->getRequestsWithString($string4, ' 0 , 1 ', 0);
}
```

---

### 4. **details** - Request Details and Status Update
**Location**: Lines 125-165  
**Purpose**: Display request details and mark as seen

**Function Signature**:
```php
// Triggered when: $do == "details"
```

**Process Flow**:
1. Load request by ID
2. Mark request as seen
3. Resolve and display target information
4. Show request details

**Target Name Resolution**:
```php
// Branch targeting
if ($otherRequest->requestTo == 0) {
    $Branch = $BranchDAO->load($otherRequest->requestToId);
    $otherRequest->requestToName = $Branch->branchName;
}
// User group targeting
elseif ($otherRequest->requestTo == 1) {
    $userGroup = $userGroupDAO->load($otherRequest->requestToId);
    $otherRequest->requestToName = $userGroup->usergroupname;
}
// Individual user targeting
elseif ($otherRequest->requestTo == 2) {
    $user = $userDAO->load($otherRequest->requestToId);
    $otherRequest->requestToName = $user->username;
}
```

---

### 5. **update()** - Request Modification
**Location**: Lines 333-362  
**Purpose**: Update existing request with new information

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

**Process Flow**:
1. Load existing request
2. Update request fields
3. Reset seen status (mark as unseen)
4. Save updated request

**Update Logic**:
```php
$otherRequest = $otherRequestDAO->load($requestId);
$otherRequest->comment = filter_input(INPUT_POST, "comment");
$otherRequest->requestTitle = filter_input(INPUT_POST, "requestTitle");
$otherRequest->requestTo = $requestTo;
$otherRequest->requestToId = $requestToId;
$otherRequest->userId = $_SESSION['userid'];
$otherRequest->seen = 0; // Mark as unseen since it's been updated

$otherRequestDAO->update($otherRequest);
```

---

## 🔄 Workflows

### Workflow 1: Request Creation Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create New Request                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Reference Data                                     │
│     - Load all branches for targeting                      │
│     - Load all user groups                                 │
│     - Load all users for individual targeting              │
│     - Display request creation form                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Form Submission                                 │
│     - Extract request target type (0=branch, 1=group, 2=user)│
│     - Determine appropriate target ID field                │
│     - Extract request title and content                    │
│     - Validate form data                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Request Record                                   │
│     - Set request metadata (date, creator, branch)         │
│     - Set target information (type, ID)                    │
│     - Set initial status (unseen, not deleted)            │
│     - Insert into database                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Confirmation & Routing                                  │
│     - Display success confirmation                         │
│     - Request becomes visible to targets                   │
│     - Send notifications (if implemented)                  │
│     - Return to request list                               │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Permission-Based Request Display
```
┌─────────────────────────────────────────────────────────────┐
│              START: Load Request Dashboard                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Determine User Context                                  │
│     - Get user's branch ID (0 = all branches)              │
│     - Get user's group ID (1 = admin)                      │
│     - Get user's individual ID                             │
│     - Determine permission levels                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Build Branch-Level Queries                             │
│     IF user has all-branch access:                         │
│       ├─→ Get requests from headquarters (branch 0)        │
│       └─→ Get requests to all branches                     │
│     ELSE:                                                  │
│       ├─→ Get requests from user's branch only             │
│       └─→ Get requests to user's specific branch           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Build User Group-Level Queries                         │
│     IF user is admin (group 1):                            │
│       ├─→ Get all user group requests                      │
│       └─→ Get all individual user requests                 │
│     ELSE:                                                  │
│       ├─→ Get requests to user's group only                │
│       └─→ Get requests to user individually                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Execute Queries & Organize Results                     │
│     - Execute all permission-based queries                 │
│     - Organize requests by type and target                 │
│     - Separate incoming vs outgoing requests               │
│     - Apply sorting and filtering                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Display Organized Dashboard                            │
│     - Show requests by category                            │
│     - Display request counts and status                    │
│     - Enable request actions (view, edit, delete)          │
│     - Highlight unseen requests                            │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Request creation form |
| `do=add` | `add()` | Process request creation |
| `do=edit` | Edit form | Request editing form |
| `do=update` | `update()` | Process request update |
| `do=details` | Details view | Show request details and mark as seen |
| `do=show` | Request dashboard | Permission-based request listing |
| `do=delete` | Delete action | Mark request as deleted |
| `do=sucess` | Success template | Success confirmation |
| `do=error` | Error template | Error display |

### Required Parameters by Action

**Request Creation** (`do=add`):
- `requestTo` - Target type: 0=branch, 1=group, 2=user (POST, required)
- `branchId` - Branch ID (POST, if requestTo=0)
- `userGroupId` - User group ID (POST, if requestTo=1) 
- `userId` - User ID (POST, if requestTo=2)
- `requestTitle` - Request title (POST, required)
- `comment` - Request content (POST, required)

**Request Edit** (`do=edit`):
- `id` - Request ID (GET, required)

**Request Details** (`do=details`):
- `id` - Request ID (GET, required)

**Request Delete** (`do=delete`):
- `id` - Request ID (GET, required)

---

## 🧮 Calculation Methods

### Target Type Resolution
```php
// Determine target type and corresponding field name
$requestTo = filter_input(INPUT_POST, "requestTo");
switch ($requestTo) {
    case 2:  // Individual user
        $requestToSelectName = 'userId';
        break;
    case 1:  // User group
        $requestToSelectName = 'userGroupId';
        break;
    case 0:  // Branch
    default:
        $requestToSelectName = 'branchId';
        break;
}
```

### Permission-Based Query Building
```php
// Branch-level permissions
if ($branchId == 0) {
    // Headquarters user - can see all branches
    $queryExtension = 'Ex';  // Use extended query methods
} else {
    // Branch user - limited to own branch
    $queryExtension = '';    // Use standard query methods
}

// User group-level permissions
if ($userGroupId == 1) {
    // Admin - can see all groups and users
    $groupScope = 'all';
} else {
    // Regular user - limited to own group
    $groupScope = 'own';
}
```

---

## 🔒 Security & Permissions

### Hierarchical Access Control
```php
// Branch-level access
$branchId = $_SESSION['branchId'];
if ($branchId == 0) {
    // Headquarters access - can see requests from all branches
    $canSeeAllBranches = true;
} else {
    // Branch access - limited to own branch
    $canSeeAllBranches = false;
}

// User group-level access
$userGroupId = $userdata->usergroupid;
if ($userGroupId == 1) {
    // Admin access - can see all user group requests
    $canSeeAllGroups = true;
} else {
    // Regular user - limited to own group
    $canSeeAllGroups = false;
}
```

### Input Sanitization
```php
$requestTitle = filter_input(INPUT_POST, "requestTitle");
$comment = filter_input(INPUT_POST, "comment");
$requestTo = filter_input(INPUT_POST, "requestTo");
$requestId = filter_input(INPUT_GET, "id");
```

### Session-Based Authentication
```php
include_once("../public/authentication.php");

// Use session data for request creation
$otherRequest->userId = $_SESSION['userid'];
$otherRequest->branchId = $_SESSION['branchId'];
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Required Indexes**:
   - `otherrequest(requestTo, requestToId, deleted)`
   - `otherrequest(branchId, deleted)`
   - `otherrequest(userId, requestDate)`
   - `otherrequest(seen, deleted)`

2. **Query Optimization**:
   - Use appropriate filtering to limit result sets
   - Efficient permission-based queries
   - Proper JOIN usage for reference data

3. **Memory Management**:
   - Limit request history displayed
   - Efficient template variable assignment
   - Clean up large data arrays

---

## 🐛 Common Issues & Troubleshooting

### 1. **Requests Not Showing for Users**
**Issue**: Users not seeing requests they should have access to  
**Cause**: Incorrect permission logic or missing branch/group assignments

**Debug**:
```sql
-- Check user's branch and group assignment
SELECT u.*, ug.usergroupname FROM user u
JOIN usergroup ug ON u.usergroupid = ug.usergroupid
WHERE u.userid = [USER_ID];

-- Check requests targeting user's branch
SELECT * FROM otherrequest 
WHERE requestTo = 0 
AND (requestToId = [BRANCH_ID] OR requestToId = 0)
AND deleted = 0;
```

### 2. **Target Name Not Resolving**
**Issue**: Request details showing blank target names  
**Cause**: Missing reference records or incorrect ID references

**Verification**:
```sql
-- Check branch existence
SELECT * FROM branch WHERE branchId = [BRANCH_ID];

-- Check user group existence
SELECT * FROM usergroup WHERE usergroupid = [GROUP_ID];

-- Check user existence
SELECT * FROM user WHERE userid = [USER_ID];
```

### 3. **Request Status Not Updating**
**Issue**: Seen status not updating when viewing details  
**Cause**: Database update failure or session issues

**Fix**:
```php
// Verify request update
$otherRequest = $otherRequestDAO->load($requestId);
$otherRequest->seen = 1;
$result = $otherRequestDAO->update($otherRequest);
if (!$result) {
    // Handle update failure
    error_log("Failed to update request seen status: " . $requestId);
}
```

### 4. **Permission Query Performance**
**Issue**: Dashboard loading slowly with many requests  
**Cause**: Inefficient permission-based queries

**Optimization**:
```php
// Cache permission calculations
$_SESSION['user_permissions'] = [
    'canSeeAllBranches' => ($branchId == 0),
    'canSeeAllGroups' => ($userGroupId == 1),
    'branchId' => $branchId,
    'userGroupId' => $userGroupId
];
```

---

## 🧪 Testing Scenarios

### Test Case 1: Request Creation and Targeting
```
1. Create requests with different target types:
   - Request to specific branch
   - Request to user group  
   - Request to individual user
2. Verify each request appears for correct recipients
3. Check request details resolve target names correctly
4. Test request editing and updates
```

### Test Case 2: Permission-Based Visibility
```
1. Create users in different branches and groups
2. Create requests with various targets
3. Login as different users and verify:
   - Headquarters users see all branch requests
   - Branch users see only their branch requests  
   - Admin users see all group requests
   - Regular users see only their group/personal requests
```

### Test Case 3: Request Lifecycle Management
```
1. Create new request (status: unseen)
2. View request details (should mark as seen)
3. Edit request (should mark as unseen again)
4. Delete request (should mark as deleted)
5. Verify status changes throughout lifecycle
```

### Test Case 4: Multi-Branch/Multi-Group Scenarios
```
1. Set up complex organizational structure
2. Create requests crossing branch boundaries
3. Test admin vs regular user visibility
4. Verify headquarters users can see all activity
5. Test group-specific request routing
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [userController.md](userController.md) - User management
- [branchesController.md](#) - Branch management
- [Database Schema Documentation](#) - Table relationships

---

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