Skip to content

User Management Business Logic

The user management system handles employee profiles, access control, permissions, and authentication within the Stratpoint Timesheet Application. It controls who can access what data and perform which actions throughout the system.

How User Management Works

For HR Team: 1. Create and manage employee profiles and records 2. Set up user accounts with appropriate permissions 3. Manage employment status and organizational assignments 4. Track user activity and system access

For IT Administrators: 1. Configure user permissions and access levels 2. Manage system security and authentication 3. Set up organizational structure and reporting relationships 4. Monitor system usage and security compliance

For Managers: 1. View team member profiles and contact information 2. Manage team assignments and project access 3. Track team member status and availability 4. Approve access requests and permission changes

System Features: - Role-based access control with granular permissions - Integration with organizational hierarchy - Employee profile management - Authentication and security controls - Activity tracking and audit trails

User Profiles and Employee Data

Core Employee Information

Each user profile contains essential employment and personal data:

Basic Information: - Full name and preferred display name - Employee ID and company email - Contact information and emergency contacts - Profile photo and personal details

Employment Details: - Employment type (Regular, Contract, Part-time) - Start date and regularization date - Job title and department assignment - Business unit and reporting manager - Employment status (Active, Inactive, Terminated)

System Configuration: - Username and authentication credentials - Permission assignments and access levels - Time zone and localization settings - Notification preferences

Employee Status Management

Track employment lifecycle and status changes:

stateDiagram-v2
    [*] --> Probationary
    Probationary --> Regular
    Probationary --> Terminated
    Regular --> OnLeave
    Regular --> Terminated
    OnLeave --> Regular
    Terminated --> [*]

Status Types: - Probationary: New employees during trial period - Regular: Confirmed employees with full benefits - Contract: Temporary or project-based employees - On Leave: Employees on extended leave - Terminated: Former employees (data retained for records)

Permission System

How Permissions Work

The system uses numeric permission IDs to control access to specific features and data:

Permission Categories: - Basic Access: Login and view own data (Permissions 1-10) - Timesheet Management: Submit and approve timesheets (Permissions 11-30) - Project Management: Create and manage projects (Permissions 40-50) - Financial Access: View revenue and financial reports (Permissions 100-120) - Administrative: System configuration and user management (Permissions 200+)

Common Permission Examples

  • Permission 1: Basic system access and own timesheet viewing
  • Permission 67: View deficiency and utilization reports
  • Permission 72: Super user access to all user data
  • Permission 109: Access revenue and financial reports
  • Permission 208: View collection notices
  • Permission 34: View client list

Permission Assignment

  • Individual Permissions: Assigned directly to specific users
  • Role-Based: Groups of permissions assigned by role or position
  • Automatic Assignment: Some permissions granted automatically (e.g., engagement manager)
  • Temporary Access: Time-limited permissions for specific tasks

Organizational Structure

Business Unit Assignment

Users are assigned to business units that determine:

Reporting Structure: - Who reports to whom in the organization - Access to business unit specific data and reports - Resource allocation and project assignment rules - Financial reporting and profit center alignment

Business Unit Types: - Technology: Software development and technical services - Consulting: Business consulting and advisory services - Operations: Internal operations and support functions - Sales & Marketing: Business development and client relations

Manager-Employee Relationships

Hierarchical relationships that affect system behavior:

Manager Responsibilities: - Approve team member timesheets and leave requests - Access team performance and utilization reports - Manage project assignments for team members - Monitor team compliance and productivity

Team Member Access: - View own performance data and reports - Submit timesheets and requests to assigned manager - Access projects and clients as assigned by manager - Receive notifications and communications from manager

Access Control and Security

Authentication Methods

  • Username/Password: Standard login credentials
  • Email-based Login: Using company email as username
  • Session Management: Secure session handling with timeouts
  • Password Policies: Complexity requirements and regular updates

Data Access Rules

  • Own Data: Users can always view their own timesheet and profile data
  • Team Data: Managers can view data for their direct reports
  • Project Data: Users can view data for projects they're assigned to
  • Administrative Data: Special permissions required for system-wide data

Security Features

  • Activity Logging: Track all user actions and data access
  • Failed Login Monitoring: Detect and prevent unauthorized access attempts
  • Session Security: Automatic logout and session protection
  • Permission Auditing: Regular review of user permissions and access

User Lifecycle Management

New Employee Onboarding

Process for adding new users to the system:

flowchart TD
    A[HR Creates Profile] --> B[Set Basic Permissions]
    B --> C[Assign Business Unit]
    C --> D[Set Reporting Manager]
    D --> E[Grant Project Access]
    E --> F[User Can Login]

Account Activation

  • Initial Setup: HR creates profile with basic information
  • Permission Assignment: IT assigns appropriate permissions based on role
  • Manager Assignment: Set up reporting relationships
  • Access Provisioning: Grant access to relevant projects and clients
  • User Notification: Inform user of account creation and login details

Account Deactivation

Process when employees leave the company:

Immediate Actions: - Disable login access and revoke all permissions - Transfer ongoing work to other team members - Update project assignments and remove from active projects - Preserve data for audit and historical reporting purposes

Data Retention: - Employee records retained for compliance and historical analysis - Timesheet data preserved for project and financial reporting - Performance data maintained for organizational metrics - Contact information archived for reference purposes

Employee Self-Service

Profile Management

Users can update certain aspects of their own profiles:

Editable Information: - Contact information and emergency contacts - Profile photo and personal preferences - Password and security settings - Notification preferences and time zone

Restricted Information: - Employment status and dates - Salary and compensation details - Permission assignments - Business unit and manager assignments

Time and Attendance

  • Timesheet Submission: Log daily work hours and activities
  • Leave Requests: Submit vacation and sick leave requests
  • Schedule Management: View work schedule and assignments
  • Overtime Tracking: Track compensatory time off and overtime hours

Reporting and Analytics

User Activity Reports

  • Login Activity: Track when users access the system
  • Feature Usage: Monitor which features are being used
  • Data Access: Audit who accesses what data
  • Performance Metrics: User productivity and utilization rates

HR Analytics

  • Headcount Reports: Employee count by business unit and status
  • Turnover Analysis: Employee retention and departure trends
  • Performance Tracking: Individual and team performance metrics
  • Compliance Monitoring: Track regulatory compliance and policy adherence

Technical Implementation Details

For developers and system administrators

Core API Endpoints

User Management:

// User CRUD operations
GET /api/v2/users                              // List all users
POST /api/v2/users                             // Create new user
PUT /api/v2/users/{id}                         // Update user profile
DELETE /api/v2/users/{id}                      // Deactivate user

// User search and filtering
POST /api/v2/users/search                      // Advanced user search
GET /api/v2/users/filters                     // Get user filter options

Permission Management:

// Permission operations
GET /api/v2/users/{id}/permissions            // Get user permissions
POST /api/v2/users/{id}/permissions           // Assign permissions
DELETE /api/v2/users/{id}/permissions/{permId} // Remove permission

// Role-based assignments
POST /api/v2/users/bulkAssignPermissions      // Bulk permission assignment
POST /api/v2/users/copyPermissions            // Copy permissions between users

Authentication:

// Authentication endpoints
POST /api/v2/auth/login                       // User login
POST /api/v2/auth/logout                      // User logout
POST /api/v2/auth/refresh                     // Refresh JWT token
POST /api/v2/auth/changePassword              // Change password

Database Schema

User Model Structure:

// Core user fields from User model
'firstName' => 'User first name (required)',
'lastName' => 'User last name (required)',
'email' => 'Company email address (required, unique)',
'username' => 'Login username (required, unique)',
'password' => 'Encrypted password (required)',
'employeeId' => 'Company employee ID (nullable)',

// Employment details
'startDate' => 'Employment start date (required)',
'regularizationDate' => 'Date of regularization (nullable)',
'employmentType_id' => 'Employment type (Regular, Contract, etc.)',
'businessUnit_id' => 'Business unit assignment (required)',
'jobTitle' => 'Job title/position (nullable)',
'manager_id' => 'Direct reporting manager (nullable)',

// Status and configuration
'isActive' => 'Account status flag (required)',
'lastLoginDate' => 'Last system login (nullable)',
'timezone' => 'User timezone (nullable)',
'locale' => 'Language preference (nullable)',

// Contact information
'mobileNumber' => 'Mobile phone number (nullable)',
'emergencyContact' => 'Emergency contact details (JSON)',
'address' => 'Home address (nullable)',

// System metadata
'created_at' => 'Account creation timestamp',
'updated_at' => 'Last profile update timestamp',
'deleted_at' => 'Soft delete timestamp (nullable)'

UserPermission Model:

// Permission assignment tracking
'user_id' => 'User ID (required)',
'permission_id' => 'Permission ID (required)',
'granted_by' => 'User who granted the permission',
'granted_at' => 'When permission was granted',
'expires_at' => 'Permission expiration date (nullable)',
'reason' => 'Business justification for permission'

EmploymentType Model:

// Employment type configuration
'name' => 'Employment type name (Regular, Contract, etc.)',
'description' => 'Type description',
'default_permissions' => 'JSON array of default permission IDs',
'leave_entitlements' => 'JSON array of leave type configurations',
'benefits_eligible' => 'Whether eligible for company benefits'

Permission System Implementation

Permission Check Function:

// Core permission validation function
function hasPermission($user, $permissionId)
{
    // Check if user has direct permission assignment
    $directPermission = UserPermission::where('user_id', $user['id'])
        ->where('permission_id', $permissionId)
        ->where(function($query) {
            $query->whereNull('expires_at')
                  ->orWhere('expires_at', '>', Carbon::now());
        })
        ->exists();

    if ($directPermission) {
        return true;
    }

    // Check role-based permissions through employment type
    $employmentType = EmploymentType::find($user['employmentType_id']);
    $defaultPermissions = json_decode($employmentType->default_permissions, true);

    return in_array($permissionId, $defaultPermissions);
}

Permission Categories:

// Actual permission groupings from codebase
$permissionCategories = [
    'timesheet_basic' => [1, 2, 3, 4, 5],
    'timesheet_approval' => [11, 12, 13, 14, 15],
    'project_management' => [40, 41, 42, 43, 44],
    'financial_reports' => [109, 110, 111, 112],
    'user_management' => [200, 201, 202, 203],
    'system_admin' => [300, 301, 302, 303]
];

User Authentication

JWT Token Implementation:

// Authentication using tymon/jwt-auth
public function login(Request $request)
{
    $credentials = [
        'email' => base64_decode($request->etona),
        'password' => base64_decode($request->subok)
    ];

    if (!$token = JWTAuth::attempt($credentials)) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }

    $user = auth()->user();
    $permissions = $this->getUserPermissions($user->id);

    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth()->factory()->getTTL() * 60,
        'user' => $user,
        'permissions' => $permissions
    ]);
}

Session Management:

// Session security implementation
class SessionMiddleware
{
    public function handle($request, Closure $next)
    {
        // Validate JWT token
        if (!$user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['error' => 'Token invalid'], 401);
        }

        // Check if user is still active
        if (!$user->isActive) {
            return response()->json(['error' => 'Account deactivated'], 403);
        }

        // Update last activity timestamp
        $user->update(['last_activity' => Carbon::now()]);

        return $next($request);
    }
}

Business Unit Integration

Business Unit Model:

// Business unit configuration
'name' => 'Business unit name (required)',
'code' => 'Unique business unit code (required)',
'manager_id' => 'Business unit manager (nullable)',
'parent_id' => 'Parent business unit for hierarchy (nullable)',
'cost_center' => 'Financial cost center code (nullable)',
'is_billable' => 'Whether this unit generates revenue',
'default_approver_id' => 'Default timesheet approver (nullable)'

Hierarchical Queries:

// Get all users in business unit hierarchy
public function getUsersInBusinessUnitTree($businessUnitId)
{
    $businessUnit = BusinessUnit::find($businessUnitId);
    $descendantIds = $businessUnit->getDescendantIds();

    return User::whereIn('businessUnit_id', $descendantIds)
        ->where('isActive', true)
        ->get();
}

User Activity Tracking

Activity Log Model:

// User activity tracking
'user_id' => 'User who performed the action',
'action' => 'Action performed (login, create, update, delete)',
'resource_type' => 'Type of resource affected',
'resource_id' => 'ID of affected resource',
'ip_address' => 'Source IP address',
'user_agent' => 'Browser/client information',
'timestamp' => 'When action occurred',
'additional_data' => 'JSON data with action details'

Activity Logging Implementation:

// Automatic activity logging
class ActivityLogger
{
    public static function log($action, $resourceType, $resourceId = null, $additionalData = [])
    {
        UserActivity::create([
            'user_id' => auth()->id(),
            'action' => $action,
            'resource_type' => $resourceType,
            'resource_id' => $resourceId,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'timestamp' => Carbon::now(),
            'additional_data' => json_encode($additionalData)
        ]);
    }
}

Employee Lifecycle Management

User Creation Process:

// New employee onboarding
public function createEmployee(array $userData)
{
    DB::transaction(function() use ($userData) {
        // Create user profile
        $user = User::create([
            'firstName' => $userData['firstName'],
            'lastName' => $userData['lastName'],
            'email' => $userData['email'],
            'startDate' => $userData['startDate'],
            'businessUnit_id' => $userData['businessUnit_id'],
            'employmentType_id' => $userData['employmentType_id']
        ]);

        // Assign default permissions based on employment type
        $employmentType = EmploymentType::find($userData['employmentType_id']);
        $defaultPermissions = json_decode($employmentType->default_permissions, true);

        foreach ($defaultPermissions as $permissionId) {
            UserPermission::create([
                'user_id' => $user->id,
                'permission_id' => $permissionId,
                'granted_by' => auth()->id(),
                'granted_at' => Carbon::now()
            ]);
        }

        // Log the creation
        ActivityLogger::log('create', 'User', $user->id, ['employee_id' => $userData['employeeId']]);

        return $user;
    });
}

User Deactivation Process:

// Employee termination
public function deactivateEmployee($userId, $terminationDate, $reason)
{
    DB::transaction(function() use ($userId, $terminationDate, $reason) {
        $user = User::find($userId);

        // Deactivate account
        $user->update([
            'isActive' => false,
            'termination_date' => $terminationDate,
            'termination_reason' => $reason
        ]);

        // Revoke all permissions (soft delete)
        UserPermission::where('user_id', $userId)
            ->update(['expires_at' => Carbon::now()]);

        // Remove from active project assignments
        ProjectUser::where('user_id', $userId)
            ->where('isActive', true)
            ->update(['isActive' => false, 'endDate' => $terminationDate]);

        // Log the deactivation
        ActivityLogger::log('deactivate', 'User', $userId, ['reason' => $reason]);
    });
}

Validation Rules

User Creation Validation:

// Actual validation rules from UserController
'firstName' => 'required|string|min:2|max:191',
'lastName' => 'required|string|min:2|max:191',
'email' => 'required|email|unique:users,email,NULL,id,deleted_at,NULL',
'username' => 'required|string|min:3|max:191|unique:users,username,NULL,id,deleted_at,NULL',
'startDate' => 'required|date',
'businessUnit_id' => 'required|integer|exists:business_units,id',
'employmentType_id' => 'required|integer|exists:employment_types,id',
'manager_id' => 'nullable|integer|exists:users,id'

Permission Assignment Validation:

// Permission assignment rules
'user_id' => 'required|integer|exists:users,id',
'permission_id' => 'required|integer|exists:permissions,id',
'expires_at' => 'nullable|date|after:today',
'reason' => 'required|string|min:10|max:500'

Performance Optimization

User Query Optimization: - Indexed queries for user searches and filtering - Cached permission lookups for frequent checks - Eager loading for user relationships - Database partitioning for historical activity data

Security Considerations: - Rate limiting for authentication attempts - Password hashing using bcrypt - Secure session management - Regular permission audits

This user management system is designed for enterprise employee management with comprehensive security controls, detailed audit trails, and flexible permission management specific to Stratpoint's organizational structure and operational requirements.