Team: J.M.F
Module: Leave Management Subsystem
Status: ✅ COMPLETE - Production Ready
Last Updated: November 29, 2025
- Overview
- Current System Architecture
- Database Schemas
- API Endpoints
- Business Rules Implementation
- Integration Points
- Features Implemented
- Testing
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.
- 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
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
- 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
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 namecategoryId- Reference to leave categorydescription- Detailed descriptionisActive- Status flagrequiresDocumentation- Whether documents are requiredmaxDaysPerRequest- Maximum days per requestminDaysNotice- Minimum notice periodallowNegativeBalance- Allow balance to go negativecreatedBy,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
File: models/leave-category.schema.ts
Organizes leave types into logical categories.
Key Fields:
code- Unique category codename- Category namedescription- Category descriptiondeductFromBalance- Whether leaves in this category deduct from balanceisPaid- Whether leaves are paidisActive- Status flagdisplayOrder- Order for UI display
Examples:
- Annual Leaves (Paid, Deducted from balance)
- Sick Leaves (Paid, May be deducted)
- Emergency Leaves (Unpaid, Not deducted)
File: models/leave-policy.schema.ts
Defines leave policies including accrual rules and approval workflows.
Key Fields:
name- Policy nameleaveTypeId- Reference to leave typeaccrualMethod- How leave accrues (Monthly, Yearly, etc.)accrualRate- Rate of accrualcarryOverAllowed- Allow carrying over unused dayscarryOverMaxDays- Maximum days that can be carried overresetDate- When balance resetsapprovalWorkflow- Approval hierarchyeligibilityCriteria- Who can use this policyapplicableTo- 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
File: models/calendar.schema.ts
Manages working calendars and holidays.
Key Fields:
name- Calendar nameyear- Calendar yearworkingDays- Array of working daysholidays- Array of holiday dates with descriptionsweekends- Weekend configurationisDefault- 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
File: models/leave-entitlement.schema.ts
Tracks employee leave entitlements and balances.
Key Fields:
employeeId- Reference to employeeleaveTypeId- Reference to leave typeleaveYear- Year of entitlementtotalEntitled- Total days entitledaccrued- Days accrued so fartaken- Days takenpending- Days in pending requestsavailable- Available balancecarriedOver- Days carried from previous yearcarryOverExpiry- When carried days expirelastAccrualDate- Last accrual processing date
Calculations:
available = accrued + carriedOver - taken - pending
File: models/leave-request.schema.ts
Core entity for leave requests and their lifecycle.
Key Fields:
requestId- Unique request identifieremployeeId- Employee making the requestleaveTypeId- Type of leavestartDate,endDate- Leave periodtotalDays- Duration (excluding weekends/holidays)reason- Justificationstatus- Request status (Pending, Approved, Rejected, etc.)currentStage- Current approval stageapprovalChain- Array of approvers with decisionsattachments- Supporting documentsisPostLeave- Whether submitted after taking leavebalanceAtSubmission- Balance when submittedmanagerId- Direct managerhrAdminId- HR admin assignedisDelegated- Whether approval is delegateddelegatedTo- Delegate informationvalidationErrors- 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
File: models/attachment.schema.ts
Manages document attachments for leave requests.
Key Fields:
leaveRequestId- Reference to leave requestfileUrl- Document storage locationfileName- Original file namefileType- MIME typefileSize- Size in bytesdocumentType- Type of document (Medical, Travel, etc.)uploadedBy- Who uploadeduploadedAt- Upload timestampisVerified- Verification statusverifiedBy,verifiedAt- Verification details
Business Rules:
- Some leave types require documentation
- HR can verify documents
- Supports multiple file types (PDF, images, etc.)
File: models/leave-adjustment.schema.ts
Tracks manual adjustments to leave balances.
Key Fields:
employeeId- Employee affectedleaveTypeId- Leave type adjustedadjustmentType- Type of adjustment (Manual, Correction, etc.)amount- Adjustment amount (positive or negative)balanceBefore- Balance before adjustmentbalanceAfter- Balance after adjustmentreason- Justification for adjustmentadjustedBy- HR admin who made adjustmentapprovedBy- Who approved the adjustmentadjustmentDate- When adjustment was made
Business Rules:
- Only HR admins can make adjustments
- Full audit trail maintained
- Reason is required
- Affects available balance immediately
Structure: Part of Leave Policy or separate collection
Defines periods when leave requests are blocked.
Key Fields:
startDate,endDate- Blocked periodreason- Why this period is blockedaffectedLeaveTypes- Which leave types are blockedexemptedEmployees- Employees who can still requestdepartments- Affected departmentsisActive- 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
http://localhost:3000/api/leaves
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| Method | Endpoint | Description | Roles |
|---|---|---|---|
| POST | /accruals/trigger |
Manually trigger accrual | HR Admin |
| GET | /accruals/history/:employeeId |
Get accrual history | Employee (self), Manager, HR |
| 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 |
| 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 |
✅ 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
✅ 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
✅ 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
✅ 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
// 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
}// Get upcoming leaves for attendance tracking
GET /leaves/integration/upcoming-leaves
Response: [{
employeeId: string,
leaveType: string,
startDate: Date,
endDate: Date,
status: string
}]// Get final settlement data
GET /leaves/integration/final-settlement/:employeeId
Response: {
employeeId: string,
unusedDays: number,
encashableAmount: number,
lastWorkingDay: Date
}- Employee information (employment type, hire date, department)
- Manager information (for approval workflow)
- Department information
- Position information
- Approval hierarchy
- Working calendar
- Holiday dates
- Attendance data (for validation)
-
Complete Leave Type System
- Multiple leave types with different rules
- Category-based organization
- Configurable documentation requirements
-
Flexible Policy Configuration
- Accrual methods (Monthly, Yearly, etc.)
- Carry-over rules
- Approval workflows
- Eligibility criteria
-
Comprehensive Request Management
- Submit, modify, cancel requests
- Multi-level approval workflow
- Document attachment support
- Validation before submission
-
Balance Tracking
- Real-time balance calculation
- Accrual tracking
- Carry-over management
- Manual adjustment capability
-
Automated Processing
- Scheduled accrual processing
- Automatic balance updates
- Carry-over processing at year-end
-
Reporting & Analytics
- Employee leave reports
- Team/Department reports
- System-wide analytics
- Pattern detection
- 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
# Unit tests
npm run test
# E2E tests
npm run test:e2e
# Test coverage
npm run test:covcurl -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"
}'curl -X GET http://localhost:3000/api/leaves/entitlements/balance/EMP001/ANNUAL \
-H "Authorization: Bearer YOUR_JWT_TOKEN"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"
}'| Metric | Count |
|---|---|
| Database Schemas | 9 |
| API Endpoints | 60+ |
| DTOs | 30+ |
| Business Rules | 25+ |
| Supported Leave Types | Unlimited |
| Approval Levels | Configurable |
| Integration Endpoints | 3 |
Team: J.M.F
Module: Leave Management
Status: Production Ready ✅
Last Updated: November 29, 2025
Version: 2.0 (Updated Structure Documentation)