Skip to content

Latest commit

 

History

History
698 lines (549 loc) · 21.7 KB

File metadata and controls

698 lines (549 loc) · 21.7 KB

Leave Management Module - J.M.F Team

Team: J.M.F
Module: Leave Management Subsystem
Status:COMPLETE - Production Ready
Last Updated: November 29, 2025


Table of Contents

  1. Overview
  2. Current System Architecture
  3. Database Schemas
  4. API Endpoints
  5. Business Rules Implementation
  6. Integration Points
  7. Features Implemented
  8. Testing

Overview

The Leave Management Module provides a comprehensive solution for managing employee leave requests, entitlements, policies, and approvals. It handles the complete leave lifecycle from policy configuration to leave request submission and approval workflows.

Key Capabilities

  • Leave Type Management - Define and manage various leave types (Annual, Sick, Emergency, etc.)
  • Leave Policy Configuration - Configure leave policies with accrual rules and approval workflows
  • Leave Category Management - Organize leave types into categories
  • Calendar Management - Manage working calendars and holidays
  • Leave Entitlement - Track and manage employee leave balances
  • Leave Request Workflow - Submit, approve, reject, and finalize leave requests
  • Document Management - Attach and verify supporting documents
  • Block Periods - Define periods when leave requests are restricted
  • Manual Adjustments - HR can manually adjust leave balances with audit trail
  • Accrual Processing - Automated leave accrual based on policies
  • Multi-level Approval - Manager and HR approval workflow with delegation support

Current System Architecture

Module Structure

src/leaves/
├── models/                          # Database Schemas (9 schemas)
│   ├── leave-type.schema.ts         # Leave type definitions
│   ├── leave-category.schema.ts     # Leave categories
│   ├── leave-policy.schema.ts       # Leave policies and rules
│   ├── calendar.schema.ts           # Working calendars
│   ├── leave-entitlement.schema.ts  # Employee entitlements
│   ├── leave-request.schema.ts      # Leave requests
│   ├── attachment.schema.ts         # Document attachments
│   ├── leave-adjustment.schema.ts   # Manual adjustments
│   └── index.ts                     # Schema exports
├── dto/                             # Data Transfer Objects (30 DTOs)
│   ├── create-leave-type.dto.ts
│   ├── update-leave-type.dto.ts
│   ├── create-leave-category.dto.ts
│   ├── create-leave-policy.dto.ts
│   ├── update-leave-policy.dto.ts
│   ├── create-calendar.dto.ts
│   ├── update-calendar.dto.ts
│   ├── assign-entitlement.dto.ts
│   ├── update-entitlement.dto.ts
│   ├── submit-leave-request.dto.ts
│   ├── modify-leave-request.dto.ts
│   ├── approve-leave-request.dto.ts
│   ├── reject-leave-request.dto.ts
│   ├── finalize-leave-request.dto.ts
│   ├── delegate-approval.dto.ts
│   ├── hr-override.dto.ts
│   ├── attach-document.dto.ts
│   ├── verify-documents.dto.ts
│   ├── bulk-approve.dto.ts
│   ├── bulk-reject.dto.ts
│   ├── validate-leave-request.dto.ts
│   ├── manual-adjustment.dto.ts
│   ├── create-block-period.dto.ts
│   ├── update-block-period.dto.ts
│   ├── check-blocked-date.dto.ts
│   ├── trigger-accrual.dto.ts
│   ├── accrual-processing-result.dto.ts
│   ├── final-settlement-response.dto.ts
│   ├── create-attachment.dto.ts
│   └── index.ts
├── enums/                           # Enumerations
│   └── [leave status, types, etc.]
├── leaves.module.ts                 # Module definition
├── leaves.service.ts                # Business logic
├── leaves.controller.ts             # API endpoints
├── leaves.scheduler.ts              # Scheduled tasks
└── leaves.service.spec.ts           # Unit tests

Technology Stack

  • Framework: NestJS 11.x
  • Database: MongoDB with Mongoose ODM
  • Language: TypeScript 5.7
  • Validation: class-validator, class-transformer
  • Scheduling: @nestjs/schedule (for automated accrual)
  • Authentication: JWT with role-based access control

Database Schemas

1. Leave Type Schema

File: models/leave-type.schema.ts

Defines different types of leaves available in the system.

Key Fields:

  • code - Unique leave type code (e.g., ANNUAL, SICK)
  • name - Display name
  • categoryId - Reference to leave category
  • description - Detailed description
  • isActive - Status flag
  • requiresDocumentation - Whether documents are required
  • maxDaysPerRequest - Maximum days per request
  • minDaysNotice - Minimum notice period
  • allowNegativeBalance - Allow balance to go negative
  • createdBy, createdAt, updatedAt - Audit fields

Business Rules:

  • Each leave type must have a unique code
  • Leave type must belong to a category
  • Can specify documentation requirements

2. Leave Category Schema

File: models/leave-category.schema.ts

Organizes leave types into logical categories.

Key Fields:

  • code - Unique category code
  • name - Category name
  • description - Category description
  • deductFromBalance - Whether leaves in this category deduct from balance
  • isPaid - Whether leaves are paid
  • isActive - Status flag
  • displayOrder - Order for UI display

Examples:

  • Annual Leaves (Paid, Deducted from balance)
  • Sick Leaves (Paid, May be deducted)
  • Emergency Leaves (Unpaid, Not deducted)

3. Leave Policy Schema

File: models/leave-policy.schema.ts

Defines leave policies including accrual rules and approval workflows.

Key Fields:

  • name - Policy name
  • leaveTypeId - Reference to leave type
  • accrualMethod - How leave accrues (Monthly, Yearly, etc.)
  • accrualRate - Rate of accrual
  • carryOverAllowed - Allow carrying over unused days
  • carryOverMaxDays - Maximum days that can be carried over
  • resetDate - When balance resets
  • approvalWorkflow - Approval hierarchy
  • eligibilityCriteria - Who can use this policy
  • applicableTo - Departments, positions, etc.

Business Rules:

  • Each policy must specify accrual method
  • Approval workflow must have at least one level
  • Can specify different rates for different employment types

4. Calendar Schema

File: models/calendar.schema.ts

Manages working calendars and holidays.

Key Fields:

  • name - Calendar name
  • year - Calendar year
  • workingDays - Array of working days
  • holidays - Array of holiday dates with descriptions
  • weekends - Weekend configuration
  • isDefault - Whether this is the default calendar

Business Rules:

  • Used for calculating leave duration
  • Excludes holidays and weekends from leave calculations
  • Can have multiple calendars for different locations

5. Leave Entitlement Schema

File: models/leave-entitlement.schema.ts

Tracks employee leave entitlements and balances.

Key Fields:

  • employeeId - Reference to employee
  • leaveTypeId - Reference to leave type
  • leaveYear - Year of entitlement
  • totalEntitled - Total days entitled
  • accrued - Days accrued so far
  • taken - Days taken
  • pending - Days in pending requests
  • available - Available balance
  • carriedOver - Days carried from previous year
  • carryOverExpiry - When carried days expire
  • lastAccrualDate - Last accrual processing date

Calculations:

  • available = accrued + carriedOver - taken - pending

6. Leave Request Schema

File: models/leave-request.schema.ts

Core entity for leave requests and their lifecycle.

Key Fields:

  • requestId - Unique request identifier
  • employeeId - Employee making the request
  • leaveTypeId - Type of leave
  • startDate, endDate - Leave period
  • totalDays - Duration (excluding weekends/holidays)
  • reason - Justification
  • status - Request status (Pending, Approved, Rejected, etc.)
  • currentStage - Current approval stage
  • approvalChain - Array of approvers with decisions
  • attachments - Supporting documents
  • isPostLeave - Whether submitted after taking leave
  • balanceAtSubmission - Balance when submitted
  • managerId - Direct manager
  • hrAdminId - HR admin assigned
  • isDelegated - Whether approval is delegated
  • delegatedTo - Delegate information
  • validationErrors - Validation issues

Status Flow:

Pending → Manager Approved → HR Approved → Finalized
          ↓
        Rejected

Business Rules:

  • Cannot submit if insufficient balance (unless allowed)
  • Manager approval required first
  • HR finalizes the request
  • Can be delegated during manager absence

7. Attachment Schema

File: models/attachment.schema.ts

Manages document attachments for leave requests.

Key Fields:

  • leaveRequestId - Reference to leave request
  • fileUrl - Document storage location
  • fileName - Original file name
  • fileType - MIME type
  • fileSize - Size in bytes
  • documentType - Type of document (Medical, Travel, etc.)
  • uploadedBy - Who uploaded
  • uploadedAt - Upload timestamp
  • isVerified - Verification status
  • verifiedBy, verifiedAt - Verification details

Business Rules:

  • Some leave types require documentation
  • HR can verify documents
  • Supports multiple file types (PDF, images, etc.)

8. Leave Adjustment Schema

File: models/leave-adjustment.schema.ts

Tracks manual adjustments to leave balances.

Key Fields:

  • employeeId - Employee affected
  • leaveTypeId - Leave type adjusted
  • adjustmentType - Type of adjustment (Manual, Correction, etc.)
  • amount - Adjustment amount (positive or negative)
  • balanceBefore - Balance before adjustment
  • balanceAfter - Balance after adjustment
  • reason - Justification for adjustment
  • adjustedBy - HR admin who made adjustment
  • approvedBy - Who approved the adjustment
  • adjustmentDate - When adjustment was made

Business Rules:

  • Only HR admins can make adjustments
  • Full audit trail maintained
  • Reason is required
  • Affects available balance immediately

9. Block Period (Embedded in Policy)

Structure: Part of Leave Policy or separate collection

Defines periods when leave requests are blocked.

Key Fields:

  • startDate, endDate - Blocked period
  • reason - Why this period is blocked
  • affectedLeaveTypes - Which leave types are blocked
  • exemptedEmployees - Employees who can still request
  • departments - Affected departments
  • isActive - Whether block is active

Business Rules:

  • Used for busy periods (year-end, audits, etc.)
  • Can exempt certain employees or leave types
  • Validated during leave request submission

API Endpoints

Base URL

http://localhost:3000/api/leaves

Leave Type Management

Method Endpoint Description Roles
POST /leave-types Create leave type HR Manager, HR Admin
GET /leave-types List all leave types All
GET /leave-types/:id Get leave type by ID All
PATCH /leave-types/:id Update leave type HR Manager, HR Admin
DELETE /leave-types/:id Delete leave type HR Admin

Leave Category Management

Method Endpoint Description Roles
POST /categories Create category HR Admin
GET /categories List all categories All
GET /categories/:id Get category by ID All
PATCH /categories/:id Update category HR Admin

Leave Policy Management

Method Endpoint Description Roles
POST /policies Create leave policy HR Admin
GET /policies List all policies HR Manager, HR Admin
GET /policies/:id Get policy by ID HR Manager, HR Admin
PATCH /policies/:id Update policy HR Admin
GET /policies/applicable/:employeeId Get applicable policies for employee All

Calendar Management

Method Endpoint Description Roles
POST /calendars Create calendar HR Admin
GET /calendars List all calendars HR Manager, HR Admin
GET /calendars/:id Get calendar by ID All
PATCH /calendars/:id Update calendar HR Admin
GET /calendars/default Get default calendar All

Leave Entitlement Management

Method Endpoint Description Roles
POST /entitlements/assign Assign entitlement HR Admin
GET /entitlements/employee/:employeeId Get employee entitlements Employee (self), Manager, HR
PATCH /entitlements/:id Update entitlement HR Admin
GET /entitlements/balance/:employeeId/:leaveTypeId Get specific leave balance Employee (self), Manager, HR

Leave Request Management

Method Endpoint Description Roles
POST /requests Submit leave request Employee
GET /requests List all requests (filtered) Manager, HR
GET /requests/:id Get request by ID Employee (own), Manager, HR
PATCH /requests/:id Modify pending request Employee (own)
DELETE /requests/:id Cancel request Employee (own)
POST /requests/:id/validate Validate request Employee, Manager, HR

Approval Workflow

Method Endpoint Description Roles
POST /requests/:id/approve Approve request Manager, HR Manager
POST /requests/:id/reject Reject request Manager, HR Manager
POST /requests/:id/finalize Finalize approved request HR Manager, HR Admin
POST /requests/:id/delegate Delegate approval Manager
POST /requests/:id/hr-override HR override decision HR Manager, HR Admin

Bulk Operations

Method Endpoint Description Roles
POST /requests/bulk-approve Bulk approve requests HR Manager, HR Admin
POST /requests/bulk-reject Bulk reject requests HR Manager, HR Admin

Document Management

Method Endpoint Description Roles
POST /requests/:id/attachments Attach document Employee (own), HR
GET /requests/:id/attachments Get attachments Employee (own), Manager, HR
POST /requests/:id/verify-documents Verify documents HR Manager, HR Admin

Manual Adjustments

Method Endpoint Description Roles
POST /adjustments Create manual adjustment HR Admin
GET /adjustments List all adjustments HR Admin
GET /adjustments/employee/:employeeId Get employee adjustments HR Admin

Block Periods

Method Endpoint Description Roles
POST /block-periods Create block period HR Admin
GET /block-periods List all block periods HR Manager, HR Admin
PATCH /block-periods/:id Update block period HR Admin
POST /block-periods/check Check if date is blocked All

Accrual Processing

Method Endpoint Description Roles
POST /accruals/trigger Manually trigger accrual HR Admin
GET /accruals/history/:employeeId Get accrual history Employee (self), Manager, HR

Reports & Analytics

Method Endpoint Description Roles
GET /reports/employee/:employeeId Employee leave report Employee (self), Manager, HR
GET /reports/team/:managerId Team leave report Manager, HR
GET /reports/department/:deptId Department report HR Manager, HR Admin
GET /reports/analytics System-wide analytics HR Manager, HR Admin

Integration Endpoints

Method Endpoint Description Used By
GET /integration/balance/:employeeId Get leave balance Payroll, Employee Profile
GET /integration/upcoming-leaves Get upcoming leaves Time Management
GET /integration/final-settlement/:employeeId Get final settlement data Offboarding/Payroll

Business Rules Implementation

Leave Request Validation (BR 1-10)

BR 1: Employee must have sufficient balance ✅ BR 2: Cannot submit overlapping requests ✅ BR 3: Must meet minimum notice period ✅ BR 4: Cannot exceed maximum days per request ✅ BR 5: Must attach documents if required ✅ BR 6: Cannot request during block periods (unless exempted) ✅ BR 7: Leave duration excludes weekends and holidays ✅ BR 8: Post-leave requests have special grace period ✅ BR 9: Cannot submit if previous request is pending ✅ BR 10: Eligibility criteria must be met

Approval Workflow (BR 11-15)

BR 11: Manager approval required first ✅ BR 12: HR finalizes after manager approval ✅ BR 13: Can delegate approval during absence ✅ BR 14: HR can override any decision ✅ BR 15: Balance deducted only after finalization

Accrual Rules (BR 16-20)

BR 16: Accrual based on employment type and tenure ✅ BR 17: Accrual pauses during unpaid leave ✅ BR 18: Carry-over has maximum limit ✅ BR 19: Carried days expire after specified period ✅ BR 20: Accrual processing runs automatically

Manual Adjustments (BR 21-25)

BR 21: Only HR Admin can adjust balances ✅ BR 22: Reason required for all adjustments ✅ BR 23: Full audit trail maintained ✅ BR 24: Adjustments affect balance immediately ✅ BR 25: Adjustment approval tracked


Integration Points

📤 Outputs to Other Modules

To Payroll Module

// Get leave balance for salary calculation
GET /leaves/integration/balance/:employeeId

Response: {
  employeeId: string,
  leaveBalances: [{
    leaveType: string,
    taken: number,
    pending: number,
    available: number
  }],
  unpaidLeaveDays: number
}

To Time Management Module

// Get upcoming leaves for attendance tracking
GET /leaves/integration/upcoming-leaves

Response: [{
  employeeId: string,
  leaveType: string,
  startDate: Date,
  endDate: Date,
  status: string
}]

To Offboarding/Recruitment Module

// Get final settlement data
GET /leaves/integration/final-settlement/:employeeId

Response: {
  employeeId: string,
  unusedDays: number,
  encashableAmount: number,
  lastWorkingDay: Date
}

📥 Inputs from Other Modules

From Employee Profile Module

  • Employee information (employment type, hire date, department)
  • Manager information (for approval workflow)

From Organization Structure Module

  • Department information
  • Position information
  • Approval hierarchy

From Time Management Module

  • Working calendar
  • Holiday dates
  • Attendance data (for validation)

Features Implemented

✅ Core Features

  1. Complete Leave Type System

    • Multiple leave types with different rules
    • Category-based organization
    • Configurable documentation requirements
  2. Flexible Policy Configuration

    • Accrual methods (Monthly, Yearly, etc.)
    • Carry-over rules
    • Approval workflows
    • Eligibility criteria
  3. Comprehensive Request Management

    • Submit, modify, cancel requests
    • Multi-level approval workflow
    • Document attachment support
    • Validation before submission
  4. Balance Tracking

    • Real-time balance calculation
    • Accrual tracking
    • Carry-over management
    • Manual adjustment capability
  5. Automated Processing

    • Scheduled accrual processing
    • Automatic balance updates
    • Carry-over processing at year-end
  6. Reporting & Analytics

    • Employee leave reports
    • Team/Department reports
    • System-wide analytics
    • Pattern detection

✅ Advanced Features

  • Delegation Support - Manager can delegate approval authority
  • HR Override - HR can override any approval decision
  • Bulk Operations - Approve/reject multiple requests at once
  • Block Periods - Restrict leave during busy periods
  • Post-Leave Requests - Submit requests after taking emergency leave
  • Document Verification - HR verifies submitted documents
  • Integration Ready - APIs for other modules

Testing

Running Tests

# Unit tests
npm run test

# E2E tests
npm run test:e2e

# Test coverage
npm run test:cov

Manual Testing Examples

Example 1: Submit Leave Request

curl -X POST http://localhost:3000/api/leaves/requests \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "leaveTypeId": "507f1f77bcf86cd799439011",
    "startDate": "2025-02-01",
    "endDate": "2025-02-05",
    "reason": "Family vacation"
  }'

Example 2: Check Leave Balance

curl -X GET http://localhost:3000/api/leaves/entitlements/balance/EMP001/ANNUAL \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Example 3: Approve Leave Request

curl -X POST http://localhost:3000/api/leaves/requests/REQ001/approve \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "comments": "Approved"
  }'

Statistics

Metric Count
Database Schemas 9
API Endpoints 60+
DTOs 30+
Business Rules 25+
Supported Leave Types Unlimited
Approval Levels Configurable
Integration Endpoints 3

Team Contact

Team: J.M.F
Module: Leave Management
Status: Production Ready ✅


Last Updated: November 29, 2025
Version: 2.0 (Updated Structure Documentation)