# User Right Access Module

## Overview
The User Right Access module is a separated, independent module for managing hierarchical access assignments for users. It allows administrators to assign State, Zone, or School-level access to users independently of the employee creation process.

## Complete Flow

### 1. User Selection Page
**Route:** `/hierarchical-access/select-user`
**View:** `hierarchical-access/select-user.blade.php`

**Features:**
- Displays a paginated list of users with roles (employee, school_hm, school_hr, district_manager, zone_manager, state_manager)
- Search functionality by name or email
- Shows current access assignments for each user
- "Manage Access" button to navigate to access assignment page

**User Information Displayed:**
- Name with initials avatar
- Email
- Phone number
- Role(s)
- Current access (State/Zone/School badges)
- Status (Active/Inactive)

### 2. Access Assignment Page
**Route:** `/hierarchical-access/assign/{userId}`
**View:** `hierarchical-access/assign-access.blade.php`

**Features:**
- User profile card with current information
- Current primary access display (State, Zone, School)
- Hierarchical access assignment form
- Current access assignments with revoke option
- Access type selection (Single vs Multiple)
- Save/Cancel actions

**Access Type Selection:**
- **Single Level:** Highest level wins (School > Zone > State). Unchecking higher level disables lower levels.
- **Multiple Levels:** All selected levels remain active independently. Can assign multiple access levels simultaneously.

**Hierarchical Access Assignment Component:**
- Uses reusable partial: `partials/hierarchical-access-assignment.blade.php`
- State selection with checkbox and dropdown
- Zone selection with checkbox and dropdown (filtered by state)
- School selection with checkbox and dropdown (filtered by zone)
- Cascading logic for single mode
- AJAX loading of zones and services

### 3. Save Access Changes
**Route:** `POST /hierarchical-access/store/{userId}`
**Controller Method:** `HierarchicalAccessController@storeAccess`

**Process:**
1. Validates input (access_type, checkboxes, IDs)
2. Removes existing service access records
3. Clears user's hierarchical fields (state_id, zone_id, school_id)
4. Based on access_type:
   - **Single:** Assigns highest level only (School > Zone > State)
   - **Multiple:** Assigns all selected levels independently
5. Creates UserServiceAccess records for each assignment
6. Updates user's primary hierarchical fields
7. Redirects back to access assignment page with success message

### 4. Revoke Access
**Route:** `POST /hierarchical-access/revoke/{accessId}`
**Controller Method:** `HierarchicalAccessController@revokeAccess`

**Process:**
1. Finds the UserServiceAccess record
2. Sets is_active to false
3. Redirects back to access assignment page

## Routes

### Main Routes
```
GET  /hierarchical-access                    → index (redirects to select-user)
GET  /hierarchical-access/select-user        → selectUser
GET  /hierarchical-access/assign/{userId}    → assignAccess
POST /hierarchical-access/store/{userId}    → storeAccess
GET  /hierarchical-access/user/{userId}     → getUserAccess (AJAX)
POST /hierarchical-access/revoke/{accessId}  → revokeAccess
```

### AJAX Routes
```
GET /hierarchical-access/api/zones?state_id={id}  → getZonesByState
GET /hierarchical-access/api/services?zone_id={id} → getServicesByZone
```

### Alias Route (Backward Compatibility)
```
GET /hierarchical-access-assignment  → index (redirects to select-user)
```

## Controller Methods

### HierarchicalAccessController

#### `index()`
Redirects to user selection page for the new flow.

#### `selectUser(Request $request)`
- Filters users by role (employee, school_hm, school_hr, district_manager, zone_manager, state_manager)
- Applies search filter if provided
- Paginates results (20 per page)
- Returns user selection view

#### `assignAccess($userId)`
- Loads user with relationships (profile, status, serviceAccess, state, zone, school)
- Loads all active states, zones, and services
- Gets current active access assignments
- Returns access assignment view

#### `storeAccess(Request $request, $userId)`
- Validates request data
- Handles transaction for data integrity
- Clears existing access
- Assigns new access based on access_type (single/multiple)
- Creates UserServiceAccess records
- Updates user's primary hierarchical fields
- Redirects with success/error message

#### `getUserAccess($userId)`
- AJAX endpoint to get user's current access
- Returns JSON with state_id, zone_id, school_id, and service_access records

#### `revokeAccess($accessId)`
- Deactivates specific access assignment
- Redirects back to user's access assignment page

#### `getZonesByState(Request $request)`
- AJAX endpoint to load zones by state
- Returns JSON with zone data

#### `getServicesByZone(Request $request)`
- AJAX endpoint to load services by zone
- Returns JSON with service data

## Views

### `hierarchical-access/select-user.blade.php`
User selection page with search and user table.

### `hierarchical-access/assign-access.blade.php`
Access assignment page with user info and form.

### `partials/hierarchical-access-assignment.blade.php`
Reusable component for hierarchical access assignment.
- Props: states, zones, services, currentAccess, oldStateId, oldZoneId, oldSchoolId, assignStateChecked, assignZoneChecked, assignSchoolChecked, showAccessType, accessType, showRevokeButton
- JavaScript for cascading logic and AJAX loading

### `hierarchical-access/index.blade.php`
Redirect page with loading spinner (redirects to select-user).

## Database Models

### UserServiceAccess
Stores access assignments in `user_service_access` table.

**Fields:**
- `user_id` - User who has access
- `state_id` - State-level access (optional)
- `zone_id` - Zone-level access (optional)
- `service_id` - School-level access (optional)
- `is_active` - Active status
- `assigned_at` - When access was assigned
- `expires_at` - Optional expiry date
- `tenant_id` - Tenant for multi-tenancy

**Scopes:**
- `active()` - Filter active access
- `byUser($userId)` - Filter by user
- `byState($stateId)` - Filter by state
- `byZone($zoneId)` - Filter by zone
- `byService($serviceId)` - Filter by service

**Methods:**
- `isValid()` - Check if access is currently valid
- `getAccessLevelAttribute()` - Get access level (state/zone/service/none)

## Integration with Existing Code

### Employee Creation
The employee creation forms (`employees/create-basic.blade.php` and `employees/create-edit.blade.php`) still include the hierarchical access assignment embedded in the form. This remains unchanged for backward compatibility.

### Reusable Component
The `partials/hierarchical-access-assignment.blade.php` component can be included in any view that needs hierarchical access assignment functionality. It's used by:
- Employee creation forms (existing)
- User Right Access module (new)

### HierarchicalAccessService
The existing `HierarchicalAccessService` continues to handle access control logic across all modules. The new User Right Access module uses this service to determine accessible data.

## Usage Example

### Assigning Access to a User

1. Navigate to `/hierarchical-access`
2. Search for the user by name or email
3. Click "Manage Access" for the desired user
4. Review current access assignments
5. Select access type (Single or Multiple)
6. Check the desired access level(s):
   - Check "Assign State Access" and select a state
   - Check "Assign Zone Access" and select a zone (filtered by state)
   - Check "Assign School Access" and select a school (filtered by zone)
7. Click "Save Access Changes"
8. Review updated access assignments

### Revoking Access

1. Navigate to user's access assignment page
2. Find the access assignment to revoke in "Current Access Assignments"
3. Click "Revoke" button
4. Confirm the action

## Differences from Employee Creation

### Employee Creation (Existing)
- Access assignment is embedded in employee creation form
- Single mode only (highest level wins)
- Access is set during employee creation
- Cannot be modified without editing the entire employee record

### User Right Access Module (New)
- Independent module for access management
- Supports both Single and Multiple access modes
- Access can be assigned/revoked independently
- Can be used for existing users without editing their profile
- Shows current access assignments with revoke option
- Dedicated user selection interface

## Security Considerations

- All routes require authentication (`auth` middleware)
- User filtering respects tenant isolation (`byTenant()` scope)
- Access assignments are validated against existing states, zones, and services
- Transaction handling ensures data integrity
- Only users with appropriate roles can be managed

## Future Enhancements

1. **Bulk Assignment:** Assign access to multiple users at once
2. **Access Expiry:** Set expiry dates for access assignments
3. **Audit Trail:** Log all access assignment changes with who made the change
4. **Access Templates:** Create predefined access templates for quick assignment
5. **Access Request Workflow:** Allow users to request access with approval process
6. **Access Analytics:** Dashboard showing access distribution across hierarchy levels

## Troubleshooting

### Issue: User not appearing in selection list
**Solution:** Ensure user has one of the allowed roles (employee, school_hm, school_hr, district_manager, zone_manager, state_manager)

### Issue: Zones not loading when state is selected
**Solution:** Check browser console for JavaScript errors. Ensure AJAX endpoint is accessible and returning data.

### Issue: Access not saving
**Solution:** Check that state_id, zone_id, or service_id exist in database. Check validation errors in session.

### Issue: Multiple access mode not working
**Solution:** Ensure "Multiple Levels" radio button is selected before checking multiple boxes.

## Related Files

- `app/Http/Controllers/HierarchicalAccessController.php` - Main controller
- `app/Models/UserServiceAccess.php` - Access assignment model
- `app/Services/HierarchicalAccessService.php` - Access control service
- `resources/views/hierarchical-access/select-user.blade.php` - User selection view
- `resources/views/hierarchical-access/assign-access.blade.php` - Access assignment view
- `resources/views/partials/hierarchical-access-assignment.blade.php` - Reusable component
- `routes/web.php` - Route definitions
