Skip to content

SaddockAime/leave-management-system-bn

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

27 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Leave Management System - Backend API

A comprehensive REST API for managing employee leave requests, balances, and approvals with JWT authentication and role-based access control.

πŸš€ Quick Start

Prerequisites

  • Node.js (v14+)
  • PostgreSQL (v11+)
  • npm or yarn

Installation

  1. Clone the repository

    git clone https://github.com/SaddockAime/leave-management-system-bn.git
    cd leave-management-system-bn
  2. Install dependencies

    npm install
  3. Environment Setup

    cp .env.example .env
    # Edit .env file with your database and other configurations
  4. Database Setup

    npm run createAllTables
    npm run seed:all
  5. Start the server

    npm run dev

The API will be available at http://localhost:4000 with documentation at http://localhost:4000/api-docs

πŸ”§ Environment Variables

Create a .env file with these required variables:

# Database
DATABASE_URL=postgres://username:password@localhost:5432/leave_management

# JWT Authentication
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=24h
REFRESH_TOKEN_EXPIRES_IN=7d

# File Storage (Cloudinary)
CLOUDINARY_CLOUD_NAME=your-cloud-name
CLOUDINARY_API_KEY=your-api-key
CLOUDINARY_API_SECRET=your-api-secret

# Email (Required for notifications)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=[email protected]
EMAIL_PASSWORD=your-app-password

# Google OAuth (Optional)
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_CALLBACK_URL=

# Email Templates & Branding (Required)
COMPANY_NAME=Your Company Name
SUPPORT_EMAIL=[email protected]
HR_EMAIL=[email protected]

# Server
PORT=4000
NODE_ENV=development

πŸ—οΈ Architecture

Technology Stack

  • Runtime: Node.js with TypeScript
  • Framework: Express.js
  • Database: PostgreSQL with TypeORM
  • Authentication: JWT-based internal authentication system
  • File Storage: Cloudinary for images and documents
  • Documentation: Swagger/OpenAPI
  • Real-time: Socket.IO for notifications
  • Logging: Winston for structured logging
  • Validation: Joi for request validation

Key Features

  • πŸ” Authentication & Authorization: Complete JWT-based auth system with user registration, login, logout, password reset, email verification, and Google OAuth
  • πŸ‘₯ HR Management: Comprehensive HR module with employee analytics, department performance, bulk operations, and workforce insights
  • 🎯 Recruitment System: Full recruitment lifecycle with job postings, application tracking, interview scheduling, and recruitment analytics
  • πŸ’° Compensation Management: Salary administration, bonus tracking, benefits enrollment, and compensation analytics
  • πŸ“š Employee Onboarding: Structured onboarding processes with task templates, progress tracking, and completion analytics
  • πŸ“‹ Leave Management: Advanced leave system with multiple types, approval workflows, balance tracking, and manager tools
  • πŸ‘¨β€πŸ’Ό Manager Tools: Team management, performance tracking, leave approvals, and department oversight
  • πŸ“ Document Management: Cloudinary-integrated file storage for profiles, documents, and attachments
  • πŸ”” Real-time Notifications: Socket.IO notifications with email integration and preference management
  • πŸ“Š Advanced Analytics: Comprehensive reporting across HR, recruitment, compensation, and leave modules
  • πŸ•΅οΈ Audit & Compliance: Complete activity tracking, security logging, and compliance reporting
  • 🏒 Organizational Structure: Department management, manager hierarchies, and team relationships

πŸ“š API Documentation

Access

  • Swagger UI: http://localhost:4000/api-docs
  • OpenAPI Spec: http://localhost:4000/api-docs.json

Authentication

The API uses internal JWT-based authentication. Users can register, login, and manage their sessions:

# Register a new user
curl -X POST http://localhost:4000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"firstName": "John", "lastName": "Doe", "email": "[email protected]", "password": "password123"}'

# Login to get JWT token
curl -X POST http://localhost:4000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "password123"}'

# Use token in protected requests
curl -X GET http://localhost:4000/api/leave-requests/my-leaves \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# Logout (invalidates token)
curl -X POST http://localhost:4000/api/auth/logout \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

User Roles & Permissions

  • ADMIN: Full system access, user management, system configuration
  • HR_MANAGER: Employee management, department oversight, leave policies
  • MANAGER: Team management, leave approvals for direct reports
  • EMPLOYEE: Basic access, personal leave requests, profile management

πŸ› οΈ Development

Scripts

npm run dev              # Start development server
npm run build            # Build TypeScript to JavaScript
npm run start            # Start production server
npm run createAllTables  # Create database tables
npm run deleteAllTables  # Drop all database tables
npm run seed:all         # Seed database with initial data
npm run swagger:generate # Generate API documentation
npm run format           # Format code with Prettier

Project Structure

src/
β”œβ”€β”€ controllers/     # Request handlers
β”œβ”€β”€ services/        # Business logic
β”œβ”€β”€ models/          # Database entities
β”œβ”€β”€ routes/          # API route definitions
β”œβ”€β”€ middleware/      # Custom middleware
β”œβ”€β”€ validations/     # Request validation schemas
β”œβ”€β”€ config/          # Configuration files
β”œβ”€β”€ utils/           # Utility functions
└── scripts/         # Database seeders

Code Standards

  • TypeScript for type safety
  • Joi for request validation
  • Winston for structured logging
  • ESLint and Prettier for code formatting

πŸ”’ Security Features

  • JWT Authentication: Secure token-based authentication
  • Role-based Access Control: Granular permissions by user role
  • Input Validation: Comprehensive request validation with Joi
  • File Upload Security: Type and size validation for uploads
  • Audit Logging: Complete activity tracking
  • Error Handling: Secure error responses without sensitive data

πŸ—„οΈ Database

Core Models

  • User: Authentication and basic user data
  • Employee: Extended employee profiles (linked to Users)
  • Department: Organizational structure
  • Role: User roles and permissions

Leave Management Models

  • LeaveRequest: Leave applications and status
  • LeaveType: Different types of leave (Annual, Sick, etc.)
  • LeaveBalance: Available leave balances by type

HR & Management Models

  • JobPosting: Recruitment job listings
  • JobApplication: Candidate applications
  • Interview: Interview scheduling and tracking
  • Onboarding: Employee onboarding processes
  • OnboardingTask: Individual onboarding tasks

Compensation Models

  • Salary: Employee salary information
  • Bonus: Bonus allocations and tracking
  • Benefit: Company benefits catalog
  • EmployeeBenefit: Employee benefit enrollments

System Models

  • Document: File attachments with Cloudinary integration
  • Notification: System notifications and preferences
  • AuditLog: Comprehensive activity tracking
  • NotificationTemplate: Email and notification templates

Relationships

  • Users have one Employee profile (created by HR/Admin)
  • Employees belong to Departments
  • Employees can have Managers (hierarchical structure)
  • Leave Requests belong to Employees
  • Documents are attached to Leave Requests

πŸ“Š API Modules Overview

The system provides 17 comprehensive API modules with hundreds of endpoints:

πŸ” Authentication & User Management (/api/auth)

  • Professional Registration Flow: New users assigned GUEST role, receive welcome email with verification
  • Role-Based Progression: GUEST β†’ EMPLOYEE when HR creates profile, with assignment notification
  • Secure Authentication: JWT tokens, password reset, email verification workflows
  • Google OAuth Integration: Alternative authentication method
  • User role and status management (Admin only)
  • Token refresh and blacklisting for enhanced security

πŸ‘€ Profile Management (/api/profile)

  • User profile viewing and updating
  • Profile picture upload with Cloudinary integration

πŸ‘₯ Employee Management (/api/employees)

  • Smart Role Progression: Creating employee profile automatically upgrades GUEST to EMPLOYEE
  • Professional Notifications: Welcome emails sent with department and manager information
  • HR-controlled employee profile creation and management
  • Employee search and filtering with pagination
  • Department-based employee viewing for managers
  • Employee analytics and insights

πŸ‘¨β€πŸ’Ό Manager Tools (/api/manager)

  • Team management and hierarchy viewing
  • Team leave approval and oversight
  • Performance tracking and analytics
  • Direct report management

🏒 HR Management (/api/hr)

  • Comprehensive HR dashboard and analytics
  • Employee overview and workforce insights
  • Department performance metrics
  • Bulk employee operations
  • HR reporting with multiple report types

🎯 Recruitment System (/api/recruitment)

  • Job posting creation and management
  • Application tracking and processing
  • Interview scheduling and management
  • Candidate evaluation and hiring workflows
  • Recruitment analytics and metrics

πŸ’° Compensation Management (/api/compensation)

  • Salary administration and tracking
  • Bonus allocation and management
  • Benefits enrollment and administration
  • Compensation analytics and reporting
  • Payroll integration capabilities

πŸ“š Onboarding System (/api/onboarding)

  • Structured onboarding process creation
  • Task templates and checklist management
  • Progress tracking and completion monitoring
  • Onboarding analytics and optimization

πŸ“‹ Leave Management (/api/leave-requests, /api/leave-types, /api/leave-balances)

  • Advanced leave request workflows
  • Multiple leave types and balance tracking
  • Manager approval processes
  • Leave analytics and reporting
  • Department and team leave oversight

πŸ“ Document Management (/api/documents)

  • Cloudinary-integrated file storage
  • Document upload for leave requests
  • File categorization and management
  • Secure document access control

πŸ”” Notification System (/api/notifications)

  • Professional Email Templates: Handlebars-powered professional email designs
  • Role-Based Notifications: Welcome emails for GUEST, assignment emails for EMPLOYEE
  • Real-time notifications via Socket.IO
  • Email notification preferences and management
  • Notification history and tracking
  • Custom notification templates for various workflows

🏒 Department Management (/api/departments)

  • Organizational structure management
  • Department creation and administration
  • Manager assignment and hierarchies

πŸ“Š Reporting & Analytics (/api/reports)

  • Cross-module reporting capabilities
  • Advanced analytics and insights
  • Data export in multiple formats
  • Custom report generation

πŸ•΅οΈ Audit & Compliance (/api/audit)

  • Comprehensive activity logging
  • Security event tracking
  • Compliance reporting
  • Audit trail management

πŸ›‘οΈ Additional Modules

  • Protected Routes: Role-based access control across all endpoints
  • Real-time Features: Socket.IO integration for live updates
  • Email Services: SMTP integration for notifications and workflows

For complete API documentation, visit /api-docs when the server is running.

πŸ‘€ User Onboarding Workflow

πŸš€ Professional Registration & Role Progression

The system implements a sophisticated user onboarding workflow with role-based access control:

Step 1: User Registration (GUEST Role)

POST /api/auth/register
  • βœ… User assigned GUEST role initially
  • βœ… Professional welcome email sent with verification link
  • βœ… No JWT token returned (security best practice)
  • βœ… Email verification required before login

Step 2: Email Verification

GET /api/auth/verify-email/:token
  • βœ… User verifies email address
  • βœ… Account activated for login
  • βœ… User can now log in with GUEST permissions

Step 3: Employee Profile Creation (GUEST β†’ EMPLOYEE)

POST /api/employees (HR/Admin only)
  • βœ… HR/Admin creates employee profile for user
  • βœ… User role automatically upgraded from GUEST to EMPLOYEE
  • βœ… Professional assignment email sent with:
    • Department information
    • Position details
    • Manager contact information
    • Employee ID and hire date
    • Full access rights explanation

Step 4: Full Employee Access

  • βœ… User now has complete employee functionality
  • βœ… Can submit leave requests, access documents, etc.
  • βœ… Receives role-appropriate notifications

πŸ“§ Professional Email Templates

All emails use Handlebars templates with professional design:

  • Welcome Email: Clean blue gradient, verification flow explanation
  • Employee Assignment: Green celebration theme, detailed role information
  • Email Verification: Security-focused design with clear instructions

Templates are mobile-responsive and follow corporate design standards.

πŸ›‘οΈ Role-Based Access Control

The system enforces strict access control based on user roles:

πŸ”“ Public Access (No Authentication)

  • User registration and login
  • Password reset and email verification
  • Google OAuth authentication

πŸ‘₯ GUEST Role Access

  • βœ… Profile Management: View/update profile, upload profile picture
  • βœ… Status Checking: Check onboarding progress via /api/auth/status
  • βœ… Basic Notifications: View system notifications
  • ❌ Leave Management: Cannot create, view, or manage leave requests
  • ❌ Document Access: Cannot upload or access documents
  • ❌ Employee Features: Limited access until profile created

πŸ‘” EMPLOYEE Role Access

  • βœ… All GUEST permissions +
  • βœ… Leave Management: Create, view, update, cancel leave requests
  • βœ… Document Management: Upload and access leave documents
  • βœ… Leave History: View personal leave history and balances
  • βœ… Team Features: Basic team collaboration

πŸ‘¨β€πŸ’Ό MANAGER+ Role Access

  • βœ… All EMPLOYEE permissions +
  • βœ… Team Management: View and manage team leave requests
  • βœ… Approval Workflows: Approve/reject leave requests
  • βœ… Department Oversight: Department-level reporting

πŸ‘©β€πŸ’Ό HR_MANAGER & ADMIN Role Access

  • βœ… All MANAGER permissions +
  • βœ… Employee Management: Create employee profiles for GUEST users
  • βœ… System Administration: User role management, system settings
  • βœ… Advanced Analytics: Comprehensive reporting across all modules

πŸ“Š Status Endpoint for Frontend Integration

GET / api / auth / status;

Perfect for frontend applications to determine user capabilities:

{
  "success": true,
  "data": {
    "role": "GUEST",
    "emailVerified": true,
    "hasEmployeeProfile": false,
    "needsEmployeeProfile": true,
    "status": "GUEST_AWAITING_PROFILE"
  }
}

🚨 Troubleshooting

Common Issues

  1. Database Connection Failed

    • Check PostgreSQL is running
    • Verify DATABASE_URL in .env
  2. JWT Authentication Errors

    • Check JWT_SECRET is set in .env
    • Verify token format in Authorization header
    • Ensure token hasn't expired or been blacklisted
  3. File Upload Issues

    • Verify Cloudinary credentials in .env
    • Check file size limits (10MB max)
  4. TypeScript Compilation Errors

    • Run npx tsc --noEmit to check for errors
    • Ensure all dependencies are installed

Debug Mode

NODE_ENV=development npm run dev

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

πŸ“ License

This project is licensed under the MIT License.

πŸ”— Related Repositories

πŸ†• System Capabilities

This is a comprehensive enterprise HR management system with:

  • βœ… Complete HR Suite: Full employee lifecycle from recruitment to onboarding to performance management
  • βœ… Advanced Analytics: Detailed reporting across all modules with data-driven insights
  • βœ… Enterprise Security: JWT authentication, audit logging, role-based access control
  • βœ… Workflow Automation: Automated leave approvals, onboarding processes, and notifications
  • βœ… Integration Ready: Cloudinary for files, SMTP for emails, Socket.IO for real-time updates
  • βœ… Scalable Architecture: TypeScript, TypeORM, comprehensive validation, and structured logging
  • βœ… API-First Design: Complete REST API with Swagger documentation for frontend integration

Need help? Check the Swagger documentation at /api-docs or open an issue on GitHub.

About

Leave Management System + HR

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •