Skip to content

HRM Module Implementation Guide

Module Overview

The Human Resource Management (HRM) module provides comprehensive employee lifecycle management, from recruitment and onboarding through performance management and offboarding. It implements sophisticated organizational hierarchy management, time tracking, leave management, and performance evaluation systems.

Business Context

The HRM module serves as the backbone for all employee-related operations within the CRM system:

  • Employee Lifecycle Management: Complete employee journey from hire to termination
  • Organizational Structure: Department and position hierarchy with reporting relationships
  • Time & Attendance: Time tracking, overtime calculation, and schedule management
  • Leave Management: Leave request, approval workflow, and balance tracking
  • Performance Management: Performance reviews, goal setting, and evaluation tracking

Integration Points

The HRM module integrates with other modules through domain events:

  • Finance Module: Payroll data, compensation tracking, and budget allocation
  • Analytics Module: HR metrics, performance analytics, and workforce insights
  • CRM Module: Employee customer assignments and sales territory management

Architecture Decisions

1. Rich Domain Models with Complex Business Logic

The HRM module employs rich Eloquent models that encapsulate complex HR business rules:

php
// Employee model with sophisticated business methods
class Employee extends BaseEntity
{
    public function changeStatus(EmploymentStatus $newStatus, string $reason, string $changedBy): void
    {
        $previousStatus = $this->status;
        
        // Validate status transition using business rules
        $this->validateStatusTransition($previousStatus, $newStatus);
        
        $this->status = $newStatus;
        $this->is_active = $newStatus->isActive();
        
        // Handle termination scenarios
        if ($newStatus === EmploymentStatus::TERMINATED) {
            $this->termination_date = now();
        }
        
        $this->save();
        
        // Fire domain event for cross-module integration
        EmployeeStatusChanged::dispatch(
            $this->id,
            $this->employee_number,
            $previousStatus,
            $newStatus,
            $reason,
            $changedBy
        );
    }
    
    public function getHierarchyLevel(): int
    {
        $level = 0;
        $manager = $this->manager;
        
        while ($manager) {
            $level++;
            $manager = $manager->manager;
        }
        
        return $level;
    }
}

2. Complex Value Objects for HR Concepts

Value objects encapsulate HR-specific business concepts with validation:

php
// Employee Number value object with format validation
class EmployeeNumber
{
    private string $value;
    
    public function __construct(string $value)
    {
        if (!preg_match('/^EMP\d{6}$/', $value)) {
            throw new InvalidEmployeeNumberException("Invalid employee number format: {$value}");
        }
        
        $this->value = $value;
    }
    
    public function getValue(): string
    {
        return $this->value;
    }
    
    public static function generate(): self
    {
        $lastEmployee = Employee::orderBy('employee_number', 'desc')->first();
        $lastNumber = $lastEmployee ? (int) substr($lastEmployee->employee_number, -6) : 0;
        
        return new self('EMP' . str_pad($lastNumber + 1, 6, '0', STR_PAD_LEFT));
    }
}

// Personal Info value object with comprehensive validation
class PersonalInfo
{
    public function __construct(
        private string $firstName,
        private string $lastName,
        private string $email,
        private ?string $phone = null,
        private ?string $mobile = null,
        private ?string $addressLine1 = null,
        private ?string $addressLine2 = null,
        private ?string $city = null,
        private ?string $state = null,
        private ?string $postalCode = null,
        private ?string $country = null
    ) {
        $this->validateEmail($email);
        $this->validateNames($firstName, $lastName);
        $this->validatePhoneNumbers($phone, $mobile);
    }
}

3. Event-Driven Architecture for HR Workflows

The module leverages Laravel's event system for complex HR workflows:

php
// Employee model boot method for automatic event firing
protected static function boot()
{
    parent::boot();
    
    static::creating(function ($employee) {
        if (empty($employee->employee_number)) {
            $employee->employee_number = static::generateEmployeeNumber();
        }
        
        $employee->currency = $employee->currency ?? 'USD';
        $employee->working_hours_per_week = $employee->working_hours_per_week ?? 
            $employee->employment_type->getDefaultWorkingHours();
        $employee->is_active = $employee->status->isActive();
    });
    
    static::created(function ($employee) {
        EmployeeCreated::dispatch(
            $employee->id,
            $employee->employee_number,
            $employee->first_name,
            $employee->last_name,
            $employee->email,
            $employee->department_id,
            $employee->position_id,
            $employee->employment_type,
            $employee->status,
            new \DateTimeImmutable($employee->hire_date->toDateString()),
            $employee->manager_id
        );
    });
}

4. Domain Services for Complex HR Operations

Domain services handle complex business operations that span multiple entities:

php
class EmployeeOnboardingService
{
    public function initializeOnboarding(Employee $employee): void
    {
        // Create onboarding workflow
        $this->createOnboardingWorkflow($employee);
        
        // Set up system accounts
        $this->provisionSystemAccounts($employee);
        
        // Generate access credentials
        $this->generateAccessCredentials($employee);
        
        // Schedule orientation sessions
        $this->scheduleOrientation($employee);
        
        // Notify relevant stakeholders
        $this->notifyStakeholders($employee);
    }
    
    public function initializeOffboarding(Employee $employee, EmployeeTerminated $event): void
    {
        // Create offboarding checklist
        $this->createOffboardingChecklist($employee, $event);
        
        // Schedule access revocation
        $this->scheduleAccessRevocation($employee, $event->terminationDate);
        
        // Plan knowledge transfer
        $this->planKnowledgeTransfer($employee);
        
        // Schedule exit procedures
        $this->scheduleExitProcedures($employee);
    }
}

Domain Layer Implementation

Core Models

Employee Model

File: app/Modules/HRM/Domain/Models/Employee.php

The Employee model is the central entity containing comprehensive employee information and business logic:

  • Employee Identification: Employee number generation, personal information management
  • Status Management: Employment status transitions with validation rules
  • Hierarchy Management: Manager-subordinate relationships and organizational structure
  • Time Tracking: Hours worked calculation and leave balance management
  • Performance Tracking: Performance review integration and rating history

Key business methods:

  • changeStatus(): Handles employment status changes with validation
  • assignTo(): Manages organizational assignments (manager, department, position)
  • terminate(): Processes employee termination with proper workflow
  • getHierarchyLevel(): Calculates organizational hierarchy depth
  • getAllSubordinates(): Retrieves complete subordinate tree
  • getLeaveBalance(): Calculates available leave days by type

Department Model

File: app/Modules/HRM/Domain/Models/Department.php

Manages organizational departments with hierarchy and budget tracking:

  • Department Hierarchy: Parent-child department relationships
  • Manager Assignment: Department head management and delegation
  • Budget Management: Department budget allocation and tracking
  • Employee Assignment: Department membership and headcount management

Position Model

File: app/Modules/HRM/Domain/Models/Position.php

Defines job positions with requirements and compensation bands:

  • Position Definition: Job title, description, and requirements
  • Compensation Management: Salary ranges and benefit eligibility
  • Reporting Structure: Position hierarchy and reporting relationships
  • Skill Requirements: Required skills and qualifications tracking

Leave Model

File: app/Modules/HRM/Domain/Models/Leave.php

Handles leave requests with approval workflow:

  • Leave Request Management: Leave application and documentation
  • Approval Workflow: Multi-level approval process with delegation
  • Balance Calculation: Leave entitlement and usage tracking
  • Calendar Integration: Leave scheduling and conflict detection

TimeEntry Model

File: app/Modules/HRM/Domain/Models/TimeEntry.php

Tracks employee time and attendance:

  • Time Recording: Clock in/out with location tracking
  • Project Allocation: Time allocation to projects and tasks
  • Overtime Calculation: Automatic overtime detection and calculation
  • Approval Workflow: Time entry approval by supervisors

Performance Model

File: app/Modules/HRM/Domain/Models/Performance.php

Manages performance reviews and evaluations:

  • Review Cycle Management: Performance review scheduling and tracking
  • Goal Setting: Performance objectives and key results (OKRs)
  • Rating System: Multi-dimensional performance evaluation
  • Development Planning: Career development and training recommendations

Value Objects

EmployeeNumber

File: app/Modules/HRM/Domain/ValueObjects/EmployeeNumber.php

Encapsulates employee number generation and validation with format enforcement (EMP######).

PersonalInfo

File: app/Modules/HRM/Domain/ValueObjects/PersonalInfo.php

Comprehensive personal information management with validation for contact details and addresses.

Salary

File: app/Modules/HRM/Domain/ValueObjects/Salary.php

Salary information with currency conversion and tax calculation support.

WorkingHours

File: app/Modules/HRM/Domain/ValueObjects/WorkingHours.php

Working hours configuration with flexible scheduling and overtime rules.

Enumerations

The module includes comprehensive enums for HR-specific statuses:

  • EmploymentStatus: ACTIVE, INACTIVE, ON_LEAVE, SUSPENDED, TERMINATED, RESIGNED, RETIRED, DECEASED
  • EmploymentType: FULL_TIME, PART_TIME, CONTRACT, INTERN, TEMPORARY, CONSULTANT
  • LeaveType: ANNUAL, SICK, MATERNITY, PATERNITY, BEREAVEMENT, PERSONAL, UNPAID
  • LeaveStatus: PENDING, APPROVED, REJECTED, CANCELLED, IN_PROGRESS, COMPLETED
  • PerformanceRating: OUTSTANDING, EXCEEDS_EXPECTATIONS, MEETS_EXPECTATIONS, NEEDS_IMPROVEMENT, UNSATISFACTORY
  • TimeEntryType: REGULAR, OVERTIME, DOUBLE_TIME, HOLIDAY, SICK, VACATION, TRAINING
  • DepartmentStatus: ACTIVE, INACTIVE, RESTRUCTURING, DISBANDED
  • PositionStatus: ACTIVE, INACTIVE, DISCONTINUED, UNDER_REVIEW

Domain Events

The HRM module fires comprehensive domain events for cross-module integration:

Employee Events

  • EmployeeCreated: New employee onboarding initiation
  • EmployeeStatusChanged: Status transitions for workflow triggers
  • EmployeeAssigned: Organizational assignment changes
  • EmployeeTerminated: Termination processing and offboarding

Department Events

  • DepartmentCreated: New department establishment
  • DepartmentManagerAssigned: Management structure changes
  • DepartmentStatusChanged: Department lifecycle management

Leave Events

  • LeaveRequested: Leave application submission
  • LeaveApproved: Leave approval with calendar updates
  • LeaveRejected: Leave denial with feedback

Performance Events

  • PerformanceReviewCreated: Review cycle initiation
  • PerformanceReviewCompleted: Performance evaluation completion

Time Tracking Events

  • TimeEntryCreated: Time record submission
  • TimeEntryApproved: Time approval for payroll processing

Domain Services

EmployeeOnboardingService

File: app/Modules/HRM/Domain/Services/EmployeeOnboardingService.php

Manages employee onboarding and offboarding workflows:

  • Onboarding Workflow: System account creation, access provisioning, orientation scheduling
  • Offboarding Workflow: Access revocation, knowledge transfer, exit procedures
  • Checklist Management: Automated task creation and assignment
  • Stakeholder Notification: Automated notifications to relevant parties

HRNotificationService

File: app/Modules/HRM/Domain/Services/HRNotificationService.php

Handles HR-specific notification workflows:

  • Leave Notifications: Leave request notifications to managers and HR
  • Performance Notifications: Review reminders and completion notifications
  • Status Change Notifications: Employment status change alerts
  • Compliance Notifications: Regulatory compliance reminders

PayrollIntegrationService

File: app/Modules/HRM/Domain/Services/PayrollIntegrationService.php

Integrates with external payroll systems:

  • Time Integration: Time entry data synchronization
  • Salary Integration: Compensation and benefit data management
  • Tax Integration: Tax calculation and withholding management
  • Compliance Reporting: Regulatory reporting and compliance

Application Layer

Application Services

HRMService

File: app/Modules/HRM/Application/Services/HRMService.php

Main orchestration service for HR operations with use case coordination and business rule enforcement.

EmployeeManagementService

File: app/Modules/HRM/Application/Services/EmployeeManagementService.php

Employee lifecycle management including hiring, transfers, promotions, and terminations.

TimeTrackingService

File: app/Modules/HRM/Application/Services/TimeTrackingService.php

Time and attendance management with overtime calculation and approval workflows.

LeaveManagementService

File: app/Modules/HRM/Application/Services/LeaveManagementService.php

Leave request processing with approval workflows and balance management.

PerformanceManagementService

File: app/Modules/HRM/Application/Services/PerformanceManagementService.php

Performance review management with goal setting and evaluation tracking.

Data Transfer Objects (DTOs)

The module includes comprehensive DTOs for data transfer between layers:

  • EmployeeDTO: Complete employee information transfer
  • DepartmentDTO: Department structure and management data
  • PositionDTO: Job position and compensation information
  • TimeEntryDTO: Time tracking and attendance data
  • LeaveDTO: Leave request and approval information
  • PerformanceDTO: Performance review and evaluation data

Each DTO includes validation rules and transformation methods for consistent data handling.

Infrastructure Layer

Repository Implementations

All repositories implement comprehensive CRUD operations with domain-specific query methods:

EloquentEmployeeRepository

File: app/Modules/HRM/Infrastructure/Repositories/EloquentEmployeeRepository.php

Advanced employee queries including hierarchy navigation, performance filtering, and organizational reporting.

EloquentDepartmentRepository

File: app/Modules/HRM/Infrastructure/Repositories/EloquentDepartmentRepository.php

Department management with hierarchy traversal and budget tracking capabilities.

EloquentLeaveRepository

File: app/Modules/HRM/Infrastructure/Repositories/EloquentLeaveRepository.php

Leave management with balance calculation and approval workflow tracking.

EloquentTimeEntryRepository

File: app/Modules/HRM/Infrastructure/Repositories/EloquentTimeEntryRepository.php

Time tracking with project allocation and overtime calculation support.

EloquentPerformanceRepository

File: app/Modules/HRM/Infrastructure/Repositories/EloquentPerformanceRepository.php

Performance review management with multi-dimensional rating support.

Event Listeners

Comprehensive event listeners handle cross-module integration:

EmployeeEventListener

File: app/Modules/HRM/Infrastructure/Listeners/EmployeeEventListener.php

Processes employee lifecycle events for system integration and workflow automation.

LeaveEventListener

File: app/Modules/HRM/Infrastructure/Listeners/LeaveEventListener.php

Handles leave-related events for calendar integration and notification workflows.

PerformanceEventListener

File: app/Modules/HRM/Infrastructure/Listeners/PerformanceEventListener.php

Manages performance review events for analytics and reporting integration.

Database Schema

Core Tables

hrm_employees

Primary employee information table with comprehensive tracking:

sql
CREATE TABLE hrm_employees (
    id char(36) PRIMARY KEY,
    employee_number varchar(20) UNIQUE NOT NULL,
    first_name varchar(100) NOT NULL,
    last_name varchar(100) NOT NULL,
    email varchar(255) UNIQUE NOT NULL,
    phone varchar(20),
    mobile varchar(20),
    address_line_1 text,
    address_line_2 text,
    city varchar(100),
    state varchar(100),
    postal_code varchar(20),
    country varchar(100),
    hire_date date NOT NULL,
    termination_date date,
    employment_type enum('FULL_TIME', 'PART_TIME', 'CONTRACT', 'INTERN', 'TEMPORARY', 'CONSULTANT') NOT NULL,
    status enum('ACTIVE', 'INACTIVE', 'ON_LEAVE', 'SUSPENDED', 'TERMINATED', 'RESIGNED', 'RETIRED', 'DECEASED') NOT NULL,
    manager_id char(36),
    department_id char(36) NOT NULL,
    position_id char(36) NOT NULL,
    salary decimal(15,2),
    currency varchar(3) DEFAULT 'USD',
    hourly_rate decimal(10,2),
    working_hours_per_week integer,
    emergency_contact_name varchar(200),
    emergency_contact_phone varchar(20),
    emergency_contact_relationship varchar(100),
    skills json,
    qualifications json,
    custom_fields json,
    notes text,
    is_active boolean DEFAULT true,
    is_eligible_for_rehire boolean DEFAULT true,
    created_by char(36),
    created_at timestamp,
    updated_at timestamp,
    deleted_at timestamp,
    tenant_id char(36) NOT NULL,
    
    INDEX idx_hrm_employees_number (employee_number),
    INDEX idx_hrm_employees_email (email),
    INDEX idx_hrm_employees_status (status),
    INDEX idx_hrm_employees_department (department_id),
    INDEX idx_hrm_employees_manager (manager_id),
    INDEX idx_hrm_employees_hire_date (hire_date),
    INDEX idx_hrm_employees_tenant (tenant_id),
    
    FOREIGN KEY (manager_id) REFERENCES hrm_employees(id),
    FOREIGN KEY (department_id) REFERENCES hrm_departments(id),
    FOREIGN KEY (position_id) REFERENCES hrm_positions(id),
    FOREIGN KEY (created_by) REFERENCES users(id)
);

hrm_departments

Department structure with hierarchy support:

sql
CREATE TABLE hrm_departments (
    id char(36) PRIMARY KEY,
    name varchar(200) NOT NULL,
    description text,
    code varchar(50) UNIQUE,
    parent_department_id char(36),
    manager_id char(36),
    status enum('ACTIVE', 'INACTIVE', 'RESTRUCTURING', 'DISBANDED') NOT NULL DEFAULT 'ACTIVE',
    budget decimal(15,2),
    currency varchar(3) DEFAULT 'USD',
    location varchar(255),
    cost_center varchar(50),
    is_active boolean DEFAULT true,
    created_by char(36),
    created_at timestamp,
    updated_at timestamp,
    deleted_at timestamp,
    tenant_id char(36) NOT NULL,
    
    INDEX idx_hrm_departments_parent (parent_department_id),
    INDEX idx_hrm_departments_manager (manager_id),
    INDEX idx_hrm_departments_status (status),
    INDEX idx_hrm_departments_tenant (tenant_id),
    
    FOREIGN KEY (parent_department_id) REFERENCES hrm_departments(id),
    FOREIGN KEY (manager_id) REFERENCES hrm_employees(id),
    FOREIGN KEY (created_by) REFERENCES users(id)
);

hrm_leaves

Leave management with approval workflow:

sql
CREATE TABLE hrm_leaves (
    id char(36) PRIMARY KEY,
    employee_id char(36) NOT NULL,
    leave_type enum('ANNUAL', 'SICK', 'MATERNITY', 'PATERNITY', 'BEREAVEMENT', 'PERSONAL', 'UNPAID') NOT NULL,
    start_date date NOT NULL,
    end_date date NOT NULL,
    days_requested integer NOT NULL,
    reason text,
    status enum('PENDING', 'APPROVED', 'REJECTED', 'CANCELLED', 'IN_PROGRESS', 'COMPLETED') NOT NULL DEFAULT 'PENDING',
    approved_by char(36),
    approved_at timestamp,
    rejection_reason text,
    covering_employee_id char(36),
    attachments json,
    emergency_contact_notified boolean DEFAULT false,
    created_by char(36),
    created_at timestamp,
    updated_at timestamp,
    tenant_id char(36) NOT NULL,
    
    INDEX idx_hrm_leaves_employee (employee_id),
    INDEX idx_hrm_leaves_dates (start_date, end_date),
    INDEX idx_hrm_leaves_status (status),
    INDEX idx_hrm_leaves_type (leave_type),
    INDEX idx_hrm_leaves_tenant (tenant_id),
    
    FOREIGN KEY (employee_id) REFERENCES hrm_employees(id),
    FOREIGN KEY (approved_by) REFERENCES hrm_employees(id),
    FOREIGN KEY (covering_employee_id) REFERENCES hrm_employees(id),
    FOREIGN KEY (created_by) REFERENCES users(id)
);

hrm_time_entries

Time tracking with project allocation:

sql
CREATE TABLE hrm_time_entries (
    id char(36) PRIMARY KEY,
    employee_id char(36) NOT NULL,
    date date NOT NULL,
    start_time time,
    end_time time,
    hours_worked decimal(4,2) NOT NULL,
    overtime_hours decimal(4,2) DEFAULT 0,
    entry_type enum('REGULAR', 'OVERTIME', 'DOUBLE_TIME', 'HOLIDAY', 'SICK', 'VACATION', 'TRAINING') NOT NULL DEFAULT 'REGULAR',
    project_id char(36),
    task_description text,
    location varchar(255),
    status enum('DRAFT', 'SUBMITTED', 'APPROVED', 'REJECTED') NOT NULL DEFAULT 'DRAFT',
    approved_by char(36),
    approved_at timestamp,
    rejection_reason text,
    billable boolean DEFAULT false,
    rate_per_hour decimal(10,2),
    created_by char(36),
    created_at timestamp,
    updated_at timestamp,
    tenant_id char(36) NOT NULL,
    
    INDEX idx_hrm_time_entries_employee (employee_id),
    INDEX idx_hrm_time_entries_date (date),
    INDEX idx_hrm_time_entries_status (status),
    INDEX idx_hrm_time_entries_project (project_id),
    INDEX idx_hrm_time_entries_tenant (tenant_id),
    
    FOREIGN KEY (employee_id) REFERENCES hrm_employees(id),
    FOREIGN KEY (approved_by) REFERENCES hrm_employees(id),
    FOREIGN KEY (created_by) REFERENCES users(id)
);

Event-Driven Integration

Cross-Module Event Flow

Employee Lifecycle Integration

php
// When employee is created
EmployeeCreated::dispatch()  {
    Analytics: Update workforce metrics
    Finance: Create payroll entry
    Operations: Assign system access
}

// When employee status changes
EmployeeStatusChanged::dispatch()  {
    Analytics: Update employment statistics
    Finance: Adjust payroll status
    Operations: Modify access privileges
}

// When employee is terminated
EmployeeTerminated::dispatch()  {
    Analytics: Update turnover metrics
    Finance: Process final payroll
    Operations: Revoke system access
    CRM: Reassign customer accounts
}

Leave Management Integration

php
// When leave is approved
LeaveApproved::dispatch()  {
    Analytics: Update leave utilization metrics
    Operations: Adjust resource allocation
    Finance: Calculate leave accrual impact
}

// When performance review is completed
PerformanceReviewCompleted::dispatch()  {
    Analytics: Update performance metrics
    Finance: Trigger salary review
    CRM: Update employee capabilities
}

Performance Considerations

Database Optimization

  1. Hierarchical Queries: Optimized recursive queries for organizational hierarchy
  2. Time Entry Aggregation: Efficient summation queries for payroll processing
  3. Leave Balance Calculation: Cached balance calculations with incremental updates
  4. Performance Metrics: Aggregated performance data for reporting

Caching Strategy

  1. Employee Hierarchy: Cache organizational structure for quick access
  2. Leave Balances: Cache calculated balances with TTL-based expiration
  3. Performance Ratings: Cache latest ratings for dashboard displays
  4. Department Structure: Cache department hierarchy for navigation

Query Optimization

  1. Indexed Searches: Comprehensive indexing on frequently queried fields
  2. Eager Loading: Optimized relationship loading for complex queries
  3. Scoped Queries: Efficient filtering by employment status and department
  4. Pagination: Optimized pagination for large employee datasets

Testing Strategy

Unit Tests

  1. Employee Business Logic: Status transitions, hierarchy calculations, leave eligibility
  2. Value Object Validation: Employee number generation, salary calculations, personal info validation
  3. Domain Services: Onboarding workflows, notification logic, payroll integration
  4. Repository Methods: Query optimization, data integrity, relationship handling

Integration Tests

  1. Employee Lifecycle: Complete hire-to-termination workflows
  2. Leave Management: Request submission through approval workflows
  3. Performance Management: Review creation through completion
  4. Cross-Module Events: Event firing and listener processing

Feature Tests

  1. API Endpoints: Complete CRUD operations for all entities
  2. Authentication: Role-based access control for HR operations
  3. Workflow Integration: Multi-step approval processes
  4. Reporting: HR metrics and analytics generation

Security Considerations

Data Protection

  1. Personal Information: Encryption of sensitive employee data
  2. Salary Information: Restricted access to compensation data
  3. Performance Data: Confidential performance review information
  4. Medical Information: HIPAA-compliant handling of health-related data

Access Control

  1. Role-Based Permissions: HR manager, employee self-service, department manager roles
  2. Hierarchical Access: Manager access to subordinate information only
  3. Audit Trails: Comprehensive logging of all HR data modifications
  4. Data Retention: Automated data purging based on retention policies

The HRM module provides a comprehensive foundation for employee management with sophisticated business logic, event-driven integration, and robust security controls. The implementation supports complex organizational structures while maintaining high performance and data integrity standards.

Documentation for SynthesQ CRM/ERP Platform