Skip to content

lucaosti/StaffScheduler

Repository files navigation

Staff Scheduler - Enterprise Workforce Management Platform# Staff Scheduler - Enterprise Workforce Management Platform# Staff Scheduler - Enterprise Workforce Management Platform# Staff Scheduler - Enterprise Workforce Management Platform# Staff Scheduler - Enterprise Workforce Management System

Production-grade intelligent workforce scheduling system with constraint programming optimization, N-level hierarchical organization support, and comprehensive analytics

Node.js> Production-grade intelligent workforce scheduling system with constraint programming optimization, N-level hierarchical organization support, and comprehensive analytics

React

TypeScript

MySQL

DockerNode.js> Production-grade intelligent workforce scheduling system with constraint programming optimization, N-level hierarchical organization support, and comprehensive analytics

License

React

Overview

TypeScript

Staff Scheduler is an enterprise-scale workforce management platform designed to solve complex scheduling optimization problems in high-constraint environments. The system implements advanced constraint programming algorithms combined with multi-objective optimization to generate provably-near-optimal schedules while respecting complex business rules, labor regulations, and employee preferences.

MySQL

Core Capabilities

DockerNode.js> Production-grade intelligent workforce scheduling system with constraint programming optimization, N-level hierarchical organization support, and comprehensive analytics> Advanced workforce scheduling platform with constraint programming optimization, hierarchical organization support, and comprehensive analytics

  • Constraint Programming Optimization: Hybrid greedy initialization + simulated annealing algorithm handling hard and soft constraints

  • Hierarchical Organization Structure: Support for unlimited organizational depth with role-based access control and inherited permissionsLicense

  • Multi-Objective Optimization: Balances coverage rate, cost minimization, workload fairness, and employee preference satisfaction

  • Real-Time Analytics Dashboard: Department-level KPIs, cost analysis, compliance metrics, and performance indicatorsReact

  • Enterprise Security: JWT-based authentication, RBAC with matrix organization support, comprehensive audit logging

  • Production Infrastructure: Docker containerization, horizontal scaling support, automated health monitoring, disaster recovery## Overview

Supported Use CasesTypeScript

  • Healthcare Facilities: 24/7 nursing schedules, physician rotations, compliance with healthcare labor regulationsStaff Scheduler is an enterprise-scale workforce management platform designed to solve complex scheduling optimization problems in high-constraint environments. The system implements advanced constraint programming algorithms combined with multi-objective optimization to generate provably-near-optimal schedules while respecting complex business rules, labor regulations, and employee preferences.

  • Manufacturing Operations: Shift-based production scheduling, skills-based task allocation, union rule compliance

  • Retail/Service Networks: Peak-demand optimization, part-time workforce scheduling, cross-location coordinationMySQL

  • Financial Services: Operations center staffing, disaster recovery site coverage, global time-zone coordination

Core Capabilities


DockerNode.jsNode.js

Quick Start

  • Constraint Programming Optimization: Hybrid greedy initialization + simulated annealing algorithm handling hard and soft constraints

Prerequisites

  • Hierarchical Organization Structure: Support for unlimited organizational depth with role-based access control and inherited permissionsLicense

  • Docker Desktop 4.0+ with Docker Compose V2

  • Git for version control- Multi-Objective Optimization: Balances coverage rate, cost minimization, workload fairness, and employee preference satisfaction

  • 8GB RAM minimum for full stack deployment

  • Real-Time Analytics Dashboard: Department-level KPIs, cost analysis, compliance metrics, and performance indicatorsReactReact

60-Second Deployment

  • Enterprise Security: JWT-based authentication, RBAC with matrix organization support, comprehensive audit logging
# Clone repository- **Production Infrastructure**: Docker containerization, horizontal scaling support, automated health monitoring, disaster recovery## Overview

git clone https://github.com/yourorg/StaffScheduler.git

cd StaffScheduler



# Configure environment (use provided template)### Supported Use Cases[![TypeScript](https://img.shields.io/badge/typescript-5.1.6-blue.svg)](https://www.typescriptlang.org/)[![TypeScript](https://img.shields.io/badge/typescript-5.1.6-blue.svg)](https://www.typescriptlang.org/)

cp .env.example .env

# Edit .env with your database credentials and API keys



# Deploy complete stack with one command- **Healthcare Facilities**: 24/7 nursing schedules, physician rotations, compliance with healthcare labor regulationsStaff Scheduler is an enterprise-scale workforce management platform designed to solve complex scheduling optimization problems in high-constraint environments. The system implements advanced constraint programming algorithms combined with multi-objective optimization to generate provably-near-optimal schedules while respecting complex business rules, labor regulations, and employee preferences.

docker-compose up -d

- **Manufacturing Operations**: Shift-based production scheduling, skills-based task allocation, union rule compliance

# Verify deployment (wait 30 seconds for services to initialize)

docker-compose ps- **Retail/Service Networks**: Peak-demand optimization, part-time workforce scheduling, cross-location coordination[![MySQL](https://img.shields.io/badge/mysql-8.0-orange.svg)](https://www.mysql.com/)[![MySQL](https://img.shields.io/badge/mysql-8.0-orange.svg)](https://www.mysql.com/)

curl http://localhost:3001/api/health

- **Financial Services**: Operations center staffing, disaster recovery site coverage, global time-zone coordination

# Access applications

# Frontend: http://localhost:3000### Core Capabilities

# Backend API: http://localhost:3001/api

# Database Admin: http://localhost:8080 (PhpMyAdmin)---

DockerDocker

First-Run Configuration

Quick Start

# Create initial admin user- **Constraint Programming Optimization**: Hybrid greedy initialization + simulated annealing algorithm handling hard and soft constraints

docker-compose exec backend npm run init-admin

### Prerequisites

# Load demo data (optional)

docker-compose exec backend npm run demo-data- **Hierarchical Organization Structure**: Support for unlimited organizational depth with role-based access control and inherited permissions[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)



# Access frontend at http://localhost:3000- Docker Desktop 4.0+ with Docker Compose V2

# Login: admin@example.com / generated-password

```- Git for version control- **Multi-Objective Optimization**: Balances coverage rate, cost minimization, workload fairness, and employee preference satisfaction



---- 8GB RAM minimum for full stack deployment



## Technology Stack- **Real-Time Analytics Dashboard**: Department-level KPIs, cost analysis, compliance metrics, and performance indicators



### Frontend Layer### 60-Second Deployment

- **React 18.2.0** - Component-based UI with hooks and context API

- **TypeScript 5.1.6** - Strict type checking with advanced features- **Enterprise Security**: JWT-based authentication, RBAC with matrix organization support, comprehensive audit logging

- **Bootstrap 5.3** - Responsive design system

- **Axios** - HTTP client with request/response interceptors```bash



### Backend Layer# Clone repository- **Production Infrastructure**: Docker containerization, horizontal scaling support, automated health monitoring, disaster recovery## Overview---

- **Node.js 18+** - JavaScript runtime (LTS channel)

- **Express.js 4.18** - Minimalist web framework with middlewaregit clone https://github.com/yourorg/StaffScheduler.git

- **TypeScript 5.1.6** - Server-side type safety

- **MySQL 8.0** - ACID-compliant relational databasecd StaffScheduler



### Infrastructure

- **Docker & Docker Compose V2** - Container orchestration

- **Nginx** - Reverse proxy with SSL termination capability# Configure environment (use provided template)### Supported Use Cases

- **Redis (Optional)** - In-memory caching and session storage

- **PHPMyAdmin** - Web-based database administrationcp .env.example .env



---# Edit .env with your database credentials and API keys



## System Architecture



### Layered Architecture# Deploy complete stack with one command- **Healthcare Facilities**: 24/7 nursing schedules, physician rotations, compliance with healthcare labor regulationsStaff Scheduler is an enterprise-scale workforce management platform designed to solve complex scheduling optimization problems in high-constraint environments. The system implements advanced constraint programming algorithms combined with multi-objective optimization to generate provably-near-optimal schedules while respecting complex business rules, labor regulations, and employee preferences.## 📋 Table of Contents



```docker-compose up -d

┌─────────────────────────────────────────────────────────┐

│         React SPA Frontend (TypeScript)                 │- **Manufacturing Operations**: Shift-based production scheduling, skills-based task allocation, union rule compliance

│  - Authentication & Authorization UI                    │

│  - Schedule Management Interface                         │# Verify deployment (wait 30 seconds for services to initialize)

│  - Real-time Dashboard & Analytics                       │

│  - Role-based Component Rendering                        │docker-compose ps- **Retail/Service Networks**: Peak-demand optimization, part-time workforce scheduling, cross-location coordination

└──────────────────────┬──────────────────────────────────┘

                       │ HTTP/REST APIcurl http://localhost:3001/api/health

┌──────────────────────▼──────────────────────────────────┐

│    Express.js Backend (TypeScript/Node.js)              │- **Financial Services**: Operations center staffing, disaster recovery site coverage, global time-zone coordination

│  ┌─────────────────────────────────────────────────┐   │

│  │ Middleware Layer                                │   │# Access applications

│  │ - JWT Authentication & RBAC                     │   │

│  │ - CORS, Rate Limiting, Compression              │   │# Frontend: http://localhost:3000### Core Capabilities- [The Problem](#the-problem)

│  │ - Error Handling & Logging                       │   │

│  └─────────────────────────────────────────────────┘   │# Backend API: http://localhost:3001/api

│  ┌─────────────────────────────────────────────────┐   │

│  │ Route Handlers (Controllers)                    │   │# Database Admin: http://localhost:8080 (PhpMyAdmin)---

│  │ - /api/schedules - Schedule CRUD & generation  │   │

│  │ - /api/employees - Employee management         │   │```

│  │ - /api/shifts - Shift template management      │   │

│  │ - /api/departments - Organization structure    │   │- [Our Solution](#our-solution)

│  │ - /api/users - User & role management          │   │

│  │ - /api/dashboard - Analytics & reporting       │   │### First-Run Configuration

│  └─────────────────────────────────────────────────┘   │

│  ┌─────────────────────────────────────────────────┐   │## Quick Start

│  │ Service Layer                                   │   │

│  │ - ScheduleService (CRUD + generation logic)    │   │```bash

│  │ - EmployeeService (profile & skills)           │   │

│  │ - DepartmentService (org structure)            │   │# Create initial admin user- **Constraint Programming Optimization**: Hybrid greedy initialization + simulated annealing algorithm handling hard and soft constraints- [Key Features](#key-features)

│  │ - AuthService (JWT & permissions)              │   │

│  └─────────────────────────────────────────────────┘   │docker-compose exec backend npm run init-admin

│  ┌─────────────────────────────────────────────────┐   │

│  │ Optimization Engine                             │   │### Prerequisites

│  │ - ScheduleOptimizer (hybrid CSP + SA)           │   │

│  │ - Constraint validators (hard/soft)            │   │# Load demo data (optional)

│  │ - Objective function calculators                │   │

│  └─────────────────────────────────────────────────┘   │docker-compose exec backend npm run demo-data- **Hierarchical Organization Structure**: Support for unlimited organizational depth with role-based access control and inherited permissions- [System Requirements](#system-requirements)

└──────────────────────┬──────────────────────────────────┘

                       │ TCP Port 3306

┌──────────────────────▼──────────────────────────────────┐

│      MySQL 8.0 Database                                 │# Access frontend at http://localhost:3000- Docker Desktop 4.0+ with Docker Compose V2

│  - Relational schema with 15+ tables                    │

│  - Normalized design (3NF)                              │# Login: admin@example.com / generated-password

│  - Foreign key constraints & indexes                    │

│  - Transaction support (ACID)                           │```- Git for version control- **Multi-Objective Optimization**: Balances coverage rate, cost minimization, workload fairness, and employee preference satisfaction- [Quick Start](#quick-start)

└─────────────────────────────────────────────────────────┘

------- 8GB RAM minimum for full stack deployment

API Overview

Core Endpoints## Technology Stack- Real-Time Analytics Dashboard: Department-level KPIs, cost analysis, compliance metrics, and performance indicators- Deployment Guide

Schedule Operations:

  • POST /api/schedules - Create schedule

  • GET /api/schedules - List schedules### Frontend Layer### 60-Second Deployment

  • GET /api/schedules/:id - Get schedule details

  • PUT /api/schedules/:id - Update schedule- React 18.2.0 - Component-based UI with hooks and context API

  • DELETE /api/schedules/:id - Delete schedule

  • POST /api/schedules/:id/generate - Generate optimized schedule- TypeScript 5.1.6 - Strict type checking with advanced features- Enterprise Security: JWT-based authentication, RBAC with matrix organization support, comprehensive audit logging- Configuration

  • PATCH /api/schedules/:id/publish - Publish schedule

  • PATCH /api/schedules/:id/archive - Archive schedule- Bootstrap 5.3 - Responsive design system

Employee Management:- Axios - HTTP client with request/response interceptors```bash

  • GET/POST /api/employees - Employee CRUD

  • GET/PUT/DELETE /api/employees/:id - Employee operations

Shift Management:### Backend Layer# Clone repository- Production Infrastructure: Docker containerization, horizontal scaling support, automated health monitoring, disaster recovery- API Documentation

  • GET/POST /api/shifts - Shift CRUD

  • GET/PUT/DELETE /api/shifts/:id - Shift operations- Node.js 18+ - JavaScript runtime (LTS channel)

Organization:- Express.js 4.18 - Minimalist web framework with middlewaregit clone https://github.com/yourorg/StaffScheduler.git

  • GET/POST /api/departments - Department CRUD

  • GET/PUT/DELETE /api/departments/:id - Department operations- TypeScript 5.1.6 - Server-side type safety

User Management:- MySQL 8.0 - ACID-compliant relational databasecd StaffScheduler- Architecture

  • GET/POST /api/users - User CRUD

  • GET/PUT/DELETE /api/users/:id - User operations

  • POST /api/auth/login - Authentication

  • POST /api/auth/logout - Logout### Infrastructure

Analytics:- Docker & Docker Compose V2 - Container orchestration

  • GET /api/dashboard/stats - Dashboard KPIs

  • GET /api/dashboard/activity - Recent activity- Nginx - Reverse proxy with SSL termination capability# Configure environment (use provided template)### Supported Use Cases- Development

  • GET /api/dashboard/upcoming-shifts - Next 7 days

  • Redis (Optional) - In-memory caching and session storage

System:

  • GET /api/health - Service health- PHPMyAdmin - Web-based database administrationcp .env.example .env

  • GET /api/health/database - Database connectivity

  • GET /api/health/memory - Memory status

Authentication---# Edit .env with your database credentials and API keys- Troubleshooting

All endpoints require JWT token in Authorization header:


Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

For complete API documentation with request/response examples and schemas, see TECHNICAL.md.### Layered Architecture# Deploy complete stack with one command- Healthcare Facilities: 24/7 nursing schedules, physician rotations, compliance with healthcare labor regulations- Support


Scheduling Algorithm```docker-compose up -d

Constraint Satisfaction Problem (CSP)┌─────────────────────────────────────────────────────────┐

The Staff Scheduler implements a hybrid approach combining constraint satisfaction with multi-objective optimization.│ React SPA Frontend (TypeScript) │- Manufacturing Operations: Shift-based production scheduling, skills-based task allocation, union rule compliance

**Hard Constraints (must satisfy):**│ - Authentication & Authorization UI │

  1. All required shifts filled to minimum staffing level

  2. No employee assigned to overlapping shifts│ - Schedule Management Interface │# Verify deployment (wait 30 seconds for services to initialize)

  3. Assigned staff meet skill requirements

  4. Respect employee availability and time-off│ - Real-time Dashboard & Analytics │

**Soft Constraints (optimize for):**│ - Role-based Component Rendering │docker-compose ps- Retail/Service Networks: Peak-demand optimization, part-time workforce scheduling, cross-location coordination---

  1. Minimize workload variance (fairness)

  2. Maximize preference satisfaction└──────────────────────┬──────────────────────────────────┘

  3. Limit consecutive work days

                    │ HTTP/REST APIcurl http://localhost:3001/api/health
    

Objective Function (minimize):


Cost = Σ(hard_violations × priority_weight) 

       + Σ(soft_penalties × optimization_weight)│    Express.js Backend (TypeScript/Node.js)              │- **Financial Services**: Operations center staffing, disaster recovery site coverage, global time-zone coordination



Hard Constraint Penalties:│  ┌─────────────────────────────────────────────────┐   │

- Shift gap: max(0, required - assigned) × 100

- Double-booking: 500 per conflict│  │ Middleware Layer                                │   │# Access applications

- Skill mismatch: 20 per missing skill

- Availability violation: 1000 per violation│  │ - JWT Authentication & RBAC                     │   │



Soft Constraint Penalties:│  │ - CORS, Rate Limiting, Compression              │   │# Frontend: http://localhost:3000## 🎯 The Problem

- Workload variance: √(Σ(hours - mean)²/n) × 5

- Preference: (avoided_count × 30) - (preferred_count × 20)│  │ - Error Handling & Logging                       │   │

- Consecutive days: (excess_days × 15)

```│  └─────────────────────────────────────────────────┘   │# Backend API: http://localhost:3001/api



### Algorithm: Hybrid Greedy + Simulated Annealing│  ┌─────────────────────────────────────────────────┐   │



**Phase 1: Greedy Initialization** - O(n log n)│  │ Route Handlers (Controllers)                    │   │# Database Admin: http://localhost:8080 (PhpMyAdmin)---

- Sort shifts by priority (critical → high → normal → low)

- Assign best-available employees to each shift│  │ - /api/schedules - Schedule CRUD & generation  │   │

- Produces feasible solution in seconds

│  │ - /api/employees - Employee management         │   │```

**Phase 2: Simulated Annealing** - Customizable

```│  │ - /api/shifts - Shift template management      │   │

Temperature = 100

Cooling_Rate = 0.95│  │ - /api/departments - Organization structure    │   │### Business Challenges

Max_Iterations = 10,000

Timeout = 300 seconds│  │ - /api/users - User & role management          │   │



Loop:│  │ - /api/dashboard - Analytics & reporting       │   │### First-Run Configuration

  - Random perturbation of current solution

  - Calculate cost delta│  └─────────────────────────────────────────────────┘   │

  - Accept if improvement OR with P(accept) = e^(-delta/T)

  - Update best solution if improved│  ┌─────────────────────────────────────────────────┐   │## Quick Start

  - Cool down: Temperature *= Cooling_Rate

```│  │ Service Layer                                   │   │



**Complexity:**│  │ - ScheduleService (CRUD + generation logic)    │   │```bash

- Time: O(n·m·log k + I·n·m) where n=employees, m=shifts, k=skills, I=iterations

- Space: O(n·m) for assignment matrix│  │ - EmployeeService (profile & skills)           │   │

- Typical runtime: 2-10 seconds (100 employees, 500 shifts)

│  │ - DepartmentService (org structure)            │   │# Create initial admin userModern workforce management organizations face critical challenges:

---

│  │ - AuthService (JWT & permissions)              │   │

## Configuration

│  └─────────────────────────────────────────────────┘   │docker-compose exec backend npm run init-admin

### Environment Variables

│  ┌─────────────────────────────────────────────────┐   │

Create `.env` from `.env.example`:

│  │ Optimization Engine                             │   │### Prerequisites

```bash

# Database (MySQL)│  │ - ScheduleOptimizer (hybrid CSP + SA)           │   │

DB_HOST=mysql

DB_PORT=3306│  │ - Constraint validators (hard/soft)            │   │# Load demo data (optional)

DB_USER=scheduler_user

DB_PASSWORD=secure_password_minimum_16_chars│  │ - Objective function calculators                │   │

DB_NAME=staff_scheduler

│  └─────────────────────────────────────────────────┘   │docker-compose exec backend npm run demo-data1. **Manual Scheduling Complexity**: Creating fair, optimized schedules across multiple departments, roles, and constraints takes weeks and often results in suboptimal allocations

# Backend API

BACKEND_PORT=3001└──────────────────────┬──────────────────────────────────┘

NODE_ENV=production

JWT_SECRET=your_base64_encoded_secret_minimum_32_chars                       │ TCP Port 3306

JWT_EXPIRY=7d

BCRYPT_ROUNDS=12┌──────────────────────▼──────────────────────────────────┐



# Frontend│      MySQL 8.0 Database                                 │# Access frontend at http://localhost:3000- Docker Desktop 4.0+ with Docker Compose V2

FRONTEND_PORT=3000

REACT_APP_API_URL=http://localhost:3001/api│  - Relational schema with 15+ tables                    │



# Rate Limiting│  - Normalized design (3NF)                              │# Login: admin@example.com / generated-password

RATE_LIMIT_WINDOW_MS=900000

RATE_LIMIT_MAX_REQUESTS=100│  - Foreign key constraints & indexes                    │



# Logging│  - Transaction support (ACID)                           │```- Git for version control2. **Constraint Management**: Balancing employee availability, legal requirements, union rules, preferred hours, skill requirements, and budget constraints manually is practically impossible

LOG_LEVEL=info

LOG_FORMAT=json└─────────────────────────────────────────────────────────┘


---



## Development

------- 8GB RAM minimum for full stack deployment

### Project Structure



StaffScheduler/## API Overview

├── backend/

│ ├── src/

│ │ ├── routes/ # Express endpoints

│ │ ├── services/ # Business logic### Core Endpoints## Technology Stack3. Visibility & Analytics: Lack of real-time insights into schedule efficiency, cost implications, and compliance status leads to poor decision-making

│ │ ├── optimization/ # ScheduleOptimizer

│ │ ├── middleware/ # Auth, logging, errors

│ │ ├── config/ # Configuration

│ │ ├── types/ # TypeScript interfacesSchedule Operations:

│ │ └── index.ts # Entry point

│ ├── tests/ # Jest tests- POST /api/schedules - Create schedule

│ ├── Dockerfile

│ ├── jest.config.json- GET /api/schedules - List schedules### Frontend Layer### 60-Second Deployment

│ ├── tsconfig.json

│ └── package.json- GET /api/schedules/:id - Get schedule details

├── frontend/- PUT /api/schedules/:id - Update schedule- React 18.2.0 - Component-based UI with hooks and context API

│ ├── src/

│ │ ├── pages/ # React pages- DELETE /api/schedules/:id - Delete schedule

│ │ ├── components/ # UI components

│ │ ├── services/ # API clients- POST /api/schedules/:id/generate - Generate optimized schedule- TypeScript 5.1.6 - Strict type checking with advanced features4. Hierarchical Complexity: Large organizations with multiple management levels struggle to maintain oversight and delegate scheduling authority effectively

│ │ ├── contexts/ # React contexts

│ │ ├── types/ # TypeScript interfaces- PATCH /api/schedules/:id/publish - Publish schedule

│ │ ├── App.tsx

│ │ └── index.tsx- PATCH /api/schedules/:id/archive - Archive schedule- Bootstrap 5.3 - Responsive design system

│ ├── public/ # Static assets

│ ├── Dockerfile

│ ├── tsconfig.json

│ └── package.jsonEmployee Management:- Axios - HTTP client with request/response interceptors```bash

├── docker-compose.yml- GET/POST /api/employees - Employee CRUD

├── .env.example

├── README.md # This file- GET/PUT/DELETE /api/employees/:id - Employee operations

├── TECHNICAL.md # API & deployment docs

├── CONTRIBUTING.md # Development guidelines

└── LICENSE




### Local Development- `GET/POST /api/shifts` - Shift CRUD



```bash- `GET/PUT/DELETE /api/shifts/:id` - Shift operations- **Node.js 18+** - JavaScript runtime (LTS channel)

# Install dependencies

cd backend && npm install

cd ../frontend && npm install

**Organization:**- **Express.js 4.18** - Minimalist web framework with middlewaregit clone https://github.com/yourorg/StaffScheduler.git   - Unnecessary overtime costs

# Start database

docker-compose up -d mysql redis- `GET/POST /api/departments` - Department CRUD



# Run migrations- `GET/PUT/DELETE /api/departments/:id` - Department operations- **TypeScript 5.1.6** - Server-side type safety

cd backend && npm run migrate



# Start backend (hot-reload)

npm run dev**User Management:**- **MySQL 8.0** - ACID-compliant relational databasecd StaffScheduler   - Poor coverage optimization  



# In new terminal, start frontend- `GET/POST /api/users` - User CRUD

cd ../frontend && npm run dev

- `GET/PUT/DELETE /api/users/:id` - User operations

# Access:

# Frontend: http://localhost:3000- `POST /api/auth/login` - Authentication

# API: http://localhost:3001/api

```- `POST /api/auth/logout` - Logout### Infrastructure   - Wasted skilled labor on basic tasks



### Code Standards



All code must comply with:**Analytics:**- **Docker & Docker Compose V2** - Container orchestration

- TypeScript strict mode (no implicit any)

- Prettier formatting (2-space indentation)- `GET /api/dashboard/stats` - Dashboard KPIs

- ESLint rules (see `.eslintrc`)

- Jest test coverage (80% minimum)- `GET /api/dashboard/activity` - Recent activity- **Nginx** - Reverse proxy with SSL termination capability# Configure environment (use provided template)   - High employee turnover due to unfair scheduling



See [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed development guidelines.- `GET /api/dashboard/upcoming-shifts` - Next 7 days



---- **Redis (Optional)** - In-memory caching and session storage



## Production Deployment**System:**



### Docker Compose (Development/Small Production)- `GET /api/health` - Service health- **PHPMyAdmin** - Web-based database administrationcp .env.example .env



```bash- `GET /api/health/database` - Database connectivity

docker-compose up -d

docker-compose ps- `GET /api/health/memory` - Memory status

curl http://localhost:3001/api/health

Kubernetes (Enterprise)### Authentication---# Edit .env with your database credentials and API keys### Current Solutions' Limitations

# Build images

docker build -t staff-scheduler-backend:1.0.0 ./backendAll endpoints require JWT token in Authorization header:

docker build -t staff-scheduler-frontend:1.0.0 ./frontend



# Deploy

kubectl apply -f k8s/```bash## System Architecture

kubectl rollout status deployment/staff-scheduler-backend

```Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...



For complete deployment guide, scaling recommendations, and monitoring setup, see [TECHNICAL.md - Production Deployment](./TECHNICAL.md#production-deployment).```



---



## MonitoringFor complete API documentation with request/response examples and schemas, see [TECHNICAL.md](./TECHNICAL.md).### Layered Architecture# Deploy complete stack with one commandExisting solutions either:



### Health Checks



```bash---

curl http://localhost:3001/api/health

curl http://localhost:3001/api/health/database

curl http://localhost:3001/api/health/memory

```## Scheduling Algorithm```docker-compose up -d- Are too basic (Excel, Google Sheets) → manual, error-prone, no optimization



### Structured Logging



All logs in JSON format for easy parsing:### Constraint Satisfaction Problem (CSP)┌─────────────────────────────────────────────────────────┐



```json

{

  "timestamp": "2025-10-22T15:30:45.123Z",The Staff Scheduler implements a hybrid approach combining constraint satisfaction with multi-objective optimization.│         React SPA Frontend (TypeScript)                 │- Are too complex/expensive (legacy enterprise software) → high cost, slow, poor UX

  "level": "INFO",

  "service": "backend",

  "path": "/api/schedules/123/generate",

  "statusCode": 200,**Hard Constraints (must satisfy):**│  - Authentication & Authorization UI                    │

  "duration": "2543ms",

  "userId": "456"1. All required shifts filled to minimum staffing level

}

```2. No employee assigned to overlapping shifts│  - Schedule Management Interface                         │# Verify deployment (wait 30 seconds for services to initialize)- Lack advanced features (standard HR systems) → basic CRUD without intelligence



---3. Assigned staff meet skill requirements



## Troubleshooting4. Respect employee availability and time-off│  - Real-time Dashboard & Analytics                       │



| Issue | Solution |

|-------|----------|

| Cannot connect to database | Check MySQL container: `docker-compose ps mysql` |**Soft Constraints (optimize for):**│  - Role-based Component Rendering                        │docker-compose ps

| Port already in use | Change port in `.env` or kill existing process |

| Schedule generation timeout | Reduce scope or increase timeout value |1. Minimize workload variance (fairness)

| Memory issues | Increase Docker RAM allocation to 4GB+ |

2. Maximize preference satisfaction└──────────────────────┬──────────────────────────────────┘

---

3. Limit consecutive work days

## Support & Documentation

                       │ HTTP/REST APIcurl http://localhost:3001/api/health**Staff Scheduler** fills this gap with intelligent, accessible, enterprise-grade scheduling.

- **Technical Reference**: [TECHNICAL.md](./TECHNICAL.md) - API docs, database schema, advanced configuration

- **Contributing**: [CONTRIBUTING.md](./CONTRIBUTING.md) - Development setup and code standards**Objective Function (minimize):**

- **Issues**: GitHub Issues for bug reports and feature requests

- **Security**: Report vulnerabilities to security@example.com```┌──────────────────────▼──────────────────────────────────┐



---Cost = Σ(hard_violations × priority_weight) 



## License       + Σ(soft_penalties × optimization_weight)│    Express.js Backend (TypeScript/Node.js)              │



MIT License - See [LICENSE](./LICENSE) file



---Hard Constraint Penalties:│  ┌─────────────────────────────────────────────────┐   │



**Version:** 1.0.0  - Shift gap: max(0, required - assigned) × 100

**Status:** Production Ready ✅  

**Created:** October 22, 2025  - Double-booking: 500 per conflict│  │ Middleware Layer                                │   │# Access applications---

**Maintainer:** Luca Ostinelli

- Skill mismatch: 20 per missing skill

- Availability violation: 1000 per violation│  │ - JWT Authentication & RBAC                     │   │



Soft Constraint Penalties:│  │ - CORS, Rate Limiting, Compression              │   │# Frontend: http://localhost:3000

- Workload variance: √(Σ(hours - mean)²/n) × 5

- Preference: (avoided_count × 30) - (preferred_count × 20)│  │ - Error Handling & Logging                       │   │

- Consecutive days: (excess_days × 15)

```│  └─────────────────────────────────────────────────┘   │# Backend API: http://localhost:3001/api## 💡 Our Solution



### Algorithm: Hybrid Greedy + Simulated Annealing│  ┌─────────────────────────────────────────────────┐   │



**Phase 1: Greedy Initialization** - O(n log n)│  │ Route Handlers (Controllers)                    │   │# Database Admin: http://localhost:8080 (PhpMyAdmin)

- Sort shifts by priority (critical → high → normal → low)

- Assign best-available employees to each shift│  │ - /api/schedules - Schedule CRUD & generation  │   │

- Produces feasible solution in seconds

│  │ - /api/employees - Employee management         │   │```### What Staff Scheduler Provides

**Phase 2: Simulated Annealing** - Customizable

```│  │ - /api/shifts - Shift template management      │   │

Temperature = 100

Cooling_Rate = 0.95│  │ - /api/departments - Organization structure    │   │

Max_Iterations = 10,000

Timeout = 300 seconds│  │ - /api/users - User & role management          │   │



Loop:│  │ - /api/dashboard - Analytics & reporting       │   │### First-Run Configuration**Intelligent Optimization Engine**

  - Random perturbation of current solution

  - Calculate cost delta│  └─────────────────────────────────────────────────┘   │

  - Accept if improvement OR with P(accept) = e^(-delta/T)

  - Update best solution if improved│  ┌─────────────────────────────────────────────────┐   │- Constraint programming-based scheduling algorithm

  - Cool down: Temperature *= Cooling_Rate

```│  │ Service Layer                                   │   │



**Complexity:**│  │ - ScheduleService (CRUD + generation logic)    │   │```bash- Multi-objective optimization: cost, coverage, fairness, preferences

- Time: O(n·m·log k + I·n·m) where n=employees, m=shifts, k=skills, I=iterations

- Space: O(n·m) for assignment matrix│  │ - EmployeeService (profile & skills)           │   │

- Typical runtime: 2-10 seconds (100 employees, 500 shifts)

│  │ - DepartmentService (org structure)            │   │# Create initial admin user- Real-time conflict detection and automatic resolution

---

│  │ - AuthService (JWT & permissions)              │   │

## Configuration

│  └─────────────────────────────────────────────────┘   │docker-compose exec backend npm run init-admin- Manual override capability for business exceptions

### Environment Variables

│  ┌─────────────────────────────────────────────────┐   │

Create `.env` from `.env.example`:

│  │ Optimization Engine                             │   │

```bash

# Database (MySQL)│  │ - ScheduleOptimizer (hybrid CSP + SA)           │   │

DB_HOST=mysql

DB_PORT=3306│  │ - Constraint validators (hard/soft)            │   │# Load demo data (optional)**Hierarchical Organization Support**

DB_USER=scheduler_user

DB_PASSWORD=secure_password_minimum_16_chars│  │ - Objective function calculators                │   │

DB_NAME=staff_scheduler

│  └─────────────────────────────────────────────────┘   │docker-compose exec backend npm run demo-data- N-level organizational structures (unlimited depth)

# Backend API

BACKEND_PORT=3001└──────────────────────┬──────────────────────────────────┘

NODE_ENV=production

JWT_SECRET=your_base64_encoded_secret_minimum_32_chars                       │ TCP Port 3306- Role-based access control with inherited permissions

JWT_EXPIRY=7d

BCRYPT_ROUNDS=12┌──────────────────────▼──────────────────────────────────┐



# Frontend│      MySQL 8.0 Database                                 │# Access frontend at http://localhost:3000- Delegation of scheduling authority to department managers

FRONTEND_PORT=3000

REACT_APP_API_URL=http://localhost:3001/api│  - Relational schema with 15+ tables                    │



# Rate Limiting│  - Normalized design (3NF)                              │# Login: admin@example.com / generated-password- Audit trail for all scheduling decisions and changes

RATE_LIMIT_WINDOW_MS=900000

RATE_LIMIT_MAX_REQUESTS=100│  - Foreign key constraints & indexes                    │



# Logging│  - Transaction support (ACID)                           │```

LOG_LEVEL=info

LOG_FORMAT=json└─────────────────────────────────────────────────────────┘

---



## Development

------- Real-time dashboard with KPIs

### Project Structure



StaffScheduler/## API Overview- Department-level performance metrics

├── backend/

│ ├── src/

│ │ ├── routes/ # Express endpoints

│ │ ├── services/ # Business logic### Core Endpoints## Technology Stack- Cost analysis and optimization recommendations

│ │ ├── optimization/ # ScheduleOptimizer

│ │ ├── middleware/ # Auth, logging, errors

│ │ ├── config/ # Configuration

│ │ ├── types/ # TypeScript interfacesSchedule Operations:- Compliance and audit reports

│ │ └── index.ts # Entry point

│ ├── tests/ # Jest tests- POST /api/schedules - Create schedule

│ ├── Dockerfile

│ ├── jest.config.json- GET /api/schedules - List schedules### Frontend Layer

│ ├── tsconfig.json

│ └── package.json- GET /api/schedules/:id - Get schedule details

├── frontend/- PUT /api/schedules/:id - Update schedule- React 18.2.0 - Component-based UI with hooks and context APIProduction-Ready Infrastructure

│ ├── src/

│ │ ├── pages/ # React pages- DELETE /api/schedules/:id - Delete schedule

│ │ ├── components/ # UI components

│ │ ├── services/ # API clients- POST /api/schedules/:id/generate - Generate optimized schedule- TypeScript 5.1.6 - Strict type checking with advanced features- Complete Docker containerization

│ │ ├── contexts/ # React contexts

│ │ ├── types/ # TypeScript interfaces- PATCH /api/schedules/:id/publish - Publish schedule

│ │ ├── App.tsx

│ │ └── index.tsx- PATCH /api/schedules/:id/archive - Archive schedule- Bootstrap 5.3 - Responsive design system- Automated deployment and scaling

│ ├── public/ # Static assets

│ ├── Dockerfile

│ ├── tsconfig.json

│ └── package.jsonEmployee Management:- Axios - HTTP client with request/response interceptors- Health monitoring and recovery

├── docker-compose.yml- GET/POST /api/employees - Employee CRUD

├── .env.example

├── README.md # This file- GET/PUT/DELETE /api/employees/:id - Employee operations- Data persistence and backup

├── TECHNICAL.md # API & deployment docs

├── CONTRIBUTING.md # Development guidelines

└── LICENSE




### Local Development- `GET/POST /api/shifts` - Shift CRUD



```bash- `GET/PUT/DELETE /api/shifts/:id` - Shift operations- **Node.js 18+** - JavaScript runtime (LTS channel)### How It Works

# Install dependencies

cd backend && npm install

cd ../frontend && npm install

**Organization:**- **Express.js 4.18** - Minimalist web framework with middleware

# Start database

docker-compose up -d mysql redis- `GET/POST /api/departments` - Department CRUD



# Run migrations- `GET/PUT/DELETE /api/departments/:id` - Department operations- **TypeScript 5.1.6** - Server-side type safety```

cd backend && npm run migrate



# Start backend (hot-reload)

npm run dev**User Management:**- **MySQL 8.0** - ACID-compliant relational database1. Setup ──> Define departments, employees, roles, shifts, constraints



# In new terminal, start frontend- `GET/POST /api/users` - User CRUD

cd ../frontend && npm run dev

- `GET/PUT/DELETE /api/users/:id` - User operations   ↓

# Access:

# Frontend: http://localhost:3000- `POST /api/auth/login` - Authentication

# API: http://localhost:3001/api

```- `POST /api/auth/logout` - Logout### Infrastructure2. Configure ──> Set optimization objectives, weights, labor rules



### Code Standards



All code must comply with:**Analytics:**- **Docker & Docker Compose V2** - Container orchestration   ↓

- TypeScript strict mode (no implicit any)

- Prettier formatting (2-space indentation)- `GET /api/dashboard/stats` - Dashboard KPIs

- ESLint rules (see `.eslintrc`)

- Jest test coverage (80% minimum)- `GET /api/dashboard/activity` - Recent activity- **Nginx** - Reverse proxy with SSL termination capability3. Generate ──> Run optimization algorithm with your constraints



See [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed development guidelines.- `GET /api/dashboard/upcoming-shifts` - Next 7 days



---- **Redis (Optional)** - In-memory caching and session storage   ↓



## Production Deployment**System:**



### Docker Compose (Development/Small Production)- `GET /api/health` - Service health- **PHPMyAdmin** - Web-based database administration4. Review ──> Dashboard shows schedule with metrics and conflicts



```bash- `GET /api/health/database` - Database connectivity

docker-compose up -d

docker-compose ps- `GET /api/health/memory` - Memory status   ↓

curl http://localhost:3001/api/health

Kubernetes (Enterprise)### Authentication---5. Publish ──> Approve and distribute to employees

# Build images

docker build -t staff-scheduler-backend:1.0.0 ./backendAll endpoints require JWT token in Authorization header:   ↓

docker build -t staff-scheduler-frontend:1.0.0 ./frontend



# Deploy

kubectl apply -f k8s/```bash## System Architecture6. Monitor ──> Track performance, adjust for next cycle

kubectl rollout status deployment/staff-scheduler-backend

```Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...



For complete deployment guide, scaling recommendations, and monitoring setup, see [TECHNICAL.md - Production Deployment](./TECHNICAL.md#production-deployment).``````



---



## MonitoringFor complete API documentation with request/response examples and schemas, see [TECHNICAL.md](./TECHNICAL.md).### Layered Architecture



### Health Checks



```bash------

curl http://localhost:3001/api/health

curl http://localhost:3001/api/health/database

curl http://localhost:3001/api/health/memory

```## Scheduling Algorithm```



### Structured Logging



All logs in JSON format for easy parsing:### Constraint Satisfaction Problem (CSP)┌─────────────────────────────────────────────────────────┐## ✨ Key Features



```json

{

  "timestamp": "2025-10-22T15:30:45.123Z",The Staff Scheduler implements a hybrid approach combining constraint satisfaction with multi-objective optimization.│         React SPA Frontend (TypeScript)                 │

  "level": "INFO",

  "service": "backend",

  "path": "/api/schedules/123/generate",

  "statusCode": 200,**Hard Constraints (must satisfy):**│  - Authentication & Authorization UI                    │### 🔧 Core Scheduling

  "duration": "2543ms",

  "userId": "456"1. All required shifts filled to minimum staffing level

}

```2. No employee assigned to overlapping shifts│  - Schedule Management Interface                         │



---3. Assigned staff meet skill requirements



## Troubleshooting4. Respect employee availability and time-off│  - Real-time Dashboard & Analytics                       │- **Intelligent Shift Assignment**: Optimal matching of employees to shifts



| Issue | Solution |

|-------|----------|

| Cannot connect to database | Check MySQL container: `docker-compose ps mysql` |**Soft Constraints (optimize for):**│  - Role-based Component Rendering                        │- **Constraint Management**: Hard and soft constraints fully supported

| Port already in use | Change port in `.env` or kill existing process |

| Schedule generation timeout | Reduce scope or increase timeout value |1. Minimize workload variance (fairness)

| Memory issues | Increase Docker RAM allocation to 4GB+ |

2. Maximize preference satisfaction└──────────────────────┬──────────────────────────────────┘- **Conflict Detection**: Automatic identification of violations

---

3. Limit consecutive work days

## Support & Documentation

                       │ HTTP/REST API- **Manual Override**: Override system recommendations when needed

- **Technical Reference**: [TECHNICAL.md](./TECHNICAL.md) - API docs, database schema, advanced configuration

- **Contributing**: [CONTRIBUTING.md](./CONTRIBUTING.md) - Development setup and code standards**Objective Function (minimize):**

- **Issues**: GitHub Issues for bug reports and feature requests

- **Security**: Report vulnerabilities to security@example.com```┌──────────────────────▼──────────────────────────────────┐- **Batch Operations**: Create and update multiple shifts at once



---Cost = Σ(hard_violations × priority_weight) 



## License       + Σ(soft_penalties × optimization_weight)│    Express.js Backend (TypeScript/Node.js)              │



MIT License - See [LICENSE](./LICENSE) file



---Hard Constraint Penalties:│  ┌─────────────────────────────────────────────────┐   │### 👥 Employee Management



**Version:** 1.0.0  - Shift gap: max(0, required - assigned) × 100

**Status:** Production Ready ✅  

**Created:** October 22, 2025  - Double-booking: 500 per conflict│  │ Middleware Layer                                │   │

**Maintainer:** Luca Ostinelli

- Skill mismatch: 20 per missing skill

- Availability violation: 1000 per violation│  │ - JWT Authentication & RBAC                     │   │- **Detailed Profiles**: Skills, certifications, availability, preferences



Soft Constraint Penalties:│  │ - CORS, Rate Limiting, Compression              │   │- **Skill Tracking**: Proficiency levels and endorsements

- Workload variance: √(Σ(hours - mean)²/n) × 5

- Preference: (avoided_count × 30) - (preferred_count × 20)│  │ - Error Handling & Logging                       │   │- **Availability Management**: Time-off requests and blackout dates

- Consecutive days: (excess_days × 15)

```│  └─────────────────────────────────────────────────┘   │- **Performance Metrics**: Utilization and satisfaction tracking



### Algorithm: Hybrid Greedy + Simulated Annealing│  ┌─────────────────────────────────────────────────┐   │- **Department Assignment**: Multi-department employee support



**Phase 1: Greedy Initialization** - O(n log n)│  │ Route Handlers (Controllers)                    │   │

- Sort shifts by priority (critical → high → normal → low)

- Assign best-available employees to each shift│  │ - /api/schedules - Schedule CRUD & generation  │   │### 📊 Analytics & Reporting

- Produces feasible solution in seconds

│  │ - /api/employees - Employee management         │   │

**Phase 2: Simulated Annealing** - Customizable

```│  │ - /api/shifts - Shift template management      │   │- **Dashboard**: Real-time KPIs and performance metrics

Temperature = 100

Cooling_Rate = 0.95│  │ - /api/departments - Organization structure    │   │- **Coverage Analysis**: Identify understaffed periods

Max_Iterations = 10,000

Timeout = 300 seconds│  │ - /api/users - User & role management          │   │- **Cost Tracking**: Labor cost analysis and optimization



Loop:│  │ - /api/dashboard - Analytics & reporting       │   │- **Trend Analysis**: Historical performance and patterns

  - Random perturbation of current solution

  - Calculate cost delta│  └─────────────────────────────────────────────────┘   │- **Compliance Reports**: Legal and union requirement verification

  - Accept if improvement OR with P(accept) = e^(-delta/T)

  - Update best solution if improved│  ┌─────────────────────────────────────────────────┐   │

  - Cool down: Temperature *= Cooling_Rate

```│  │ Service Layer                                   │   │### 🏛️ Organizational Support



**Complexity:**│  │ - ScheduleService (CRUD + generation logic)    │   │

- Time: O(n·m·log k + I·n·m) where n=employees, m=shifts, k=skills, I=iterations

- Space: O(n·m) for assignment matrix│  │ - EmployeeService (profile & skills)           │   │- **Unlimited Hierarchies**: N-level organizational structures

- Typical runtime: 2-10 seconds (100 employees, 500 shifts)

│  │ - DepartmentService (org structure)            │   │- **Department Management**: Department-specific settings and rules

---

│  │ - AuthService (JWT & permissions)              │   │- **Role Hierarchy**: Manager, supervisor, employee roles

## Configuration

│  └─────────────────────────────────────────────────┘   │- **Delegation**: Distribute scheduling authority to managers

### Environment Variables

│  ┌─────────────────────────────────────────────────┐   │- **Permission Model**: Granular access control

Create `.env` from `.env.example`:

│  │ Optimization Engine                             │   │

```bash

# Database (MySQL)│  │ - ScheduleOptimizer (hybrid CSP + SA)           │   │### 🔐 Security & Compliance

DB_HOST=mysql

DB_PORT=3306│  │ - Constraint validators (hard/soft)            │   │

DB_USER=scheduler_user

DB_PASSWORD=secure_password_minimum_16_chars│  │ - Objective function calculators                │   │- **JWT Authentication**: Secure token-based authentication

DB_NAME=staff_scheduler

│  └─────────────────────────────────────────────────┘   │- **Role-Based Access**: Permission-based UI and API access

# Backend API

BACKEND_PORT=3001└──────────────────────┬──────────────────────────────────┘- **Password Security**: bcrypt hashing with salt (rounds: 12)

NODE_ENV=production

JWT_SECRET=your_base64_encoded_secret_minimum_32_chars                       │ TCP Port 3306- **CORS Protection**: Configurable cross-origin restrictions

JWT_EXPIRY=7d

BCRYPT_ROUNDS=12┌──────────────────────▼──────────────────────────────────┐- **Rate Limiting**: Protection against abuse (100 req/15min per IP)



# Frontend│      MySQL 8.0 Database                                 │- **Audit Logging**: Track all data modifications

FRONTEND_PORT=3000

REACT_APP_API_URL=http://localhost:3001/api│  - Relational schema with 15+ tables                    │- **Data Validation**: Input sanitization and type checking



# Rate Limiting│  - Normalized design (3NF)                              │

RATE_LIMIT_WINDOW_MS=900000

RATE_LIMIT_MAX_REQUESTS=100│  - Foreign key constraints & indexes                    │---



# Logging│  - Transaction support (ACID)                           │

LOG_LEVEL=info

LOG_FORMAT=json└─────────────────────────────────────────────────────────┘## 💻 System Requirements

---

### Minimum Requirements

## Development

---- **CPU**: 2 cores

### Project Structure

- **Memory**: 4GB RAM (8GB recommended)

StaffScheduler/## API Overview- Disk: 10GB available space

├── backend/

│ ├── src/- Network: Internet connection for Docker image download

│ │ ├── routes/ # Express endpoints

│ │ ├── services/ # Business logic### Core Endpoints

│ │ ├── optimization/ # ScheduleOptimizer

│ │ ├── middleware/ # Auth, logging, errors### Software Requirements

│ │ ├── config/ # Configuration

│ │ ├── types/ # TypeScript interfacesSchedule Operations:

│ │ └── index.ts # Entry point

│ ├── tests/ # Jest tests- POST /api/schedules - Create schedule#### Docker Deployment (Recommended)

│ ├── Dockerfile

│ ├── jest.config.json- GET /api/schedules - List schedules- Docker Desktop 4.0+ (includes Docker Compose V2)

│ ├── tsconfig.json

│ └── package.json- GET /api/schedules/:id - Get schedule details- Macintosh, Windows 10+, or Linux with Docker daemon

├── frontend/- PUT /api/schedules/:id - Update schedule

│ ├── src/

│ │ ├── pages/ # React pages- DELETE /api/schedules/:id - Delete schedule#### Manual Setup

│ │ ├── components/ # UI components

│ │ ├── services/ # API clients- POST /api/schedules/:id/generate - Generate optimized schedule- Node.js 18.0+ LTS

│ │ ├── contexts/ # React contexts

│ │ ├── types/ # TypeScript interfaces- PATCH /api/schedules/:id/publish - Publish schedule- npm 8.0+ or yarn 1.22+

│ │ ├── App.tsx

│ │ └── index.tsx- PATCH /api/schedules/:id/archive - Archive schedule- MySQL 8.0+ (or compatible)

│ ├── public/ # Static assets

│ ├── Dockerfile

│ ├── tsconfig.json

│ └── package.jsonEmployee Management:### Supported Platforms

├── docker-compose.yml- GET/POST /api/employees - Employee CRUD

├── .env.example

├── README.md # This file- GET/PUT/DELETE /api/employees/:id - Employee operations- ✅ macOS: 10.15+ (Intel and Apple Silicon)

├── TECHNICAL.md # API & deployment docs

├── CONTRIBUTING.md # Development guidelines- ✅ Windows: 10/11 (WSL2 or native Docker)

└── LICENSE




### Local Development- `GET/POST /api/shifts` - Shift CRUD- ✅ **Cloud**: AWS, Google Cloud, Azure, DigitalOcean



```bash- `GET/PUT/DELETE /api/shifts/:id` - Shift operations

# Install dependencies

cd backend && npm install---

cd ../frontend && npm install

**Organization:**

# Start database

docker-compose up -d mysql redis- `GET/POST /api/departments` - Department CRUD## 🚀 Quick Start



# Run migrations- `GET/PUT/DELETE /api/departments/:id` - Department operations

cd backend && npm run migrate

### Option 1: Docker (Recommended - 2 minutes)

# Start backend (hot-reload)

npm run dev**User Management:**



# In new terminal, start frontend- `GET/POST /api/users` - User CRUD**Step 1: Clone Repository**

cd ../frontend && npm run dev

- `GET/PUT/DELETE /api/users/:id` - User operations```bash

# Access:

# Frontend: http://localhost:3000- `POST /api/auth/login` - Authenticationgit clone https://github.com/yourorg/StaffScheduler.git

# API: http://localhost:3001/api

```- `POST /api/auth/logout` - Logoutcd StaffScheduler



### Code Standards```



All code must comply with:**Analytics:**

- TypeScript strict mode (no implicit any)

- Prettier formatting (2-space indentation)- `GET /api/dashboard/stats` - Dashboard KPIs**Step 2: Configure Environment**

- ESLint rules (see `.eslintrc`)

- Jest test coverage (80% minimum)- `GET /api/dashboard/activity` - Recent activity```bash



See [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed development guidelines.- `GET /api/dashboard/upcoming-shifts` - Next 7 dayscp .env.example .env



---# Edit .env with your settings (see Configuration section)



## Production Deployment**System:**```



### Docker Compose (Development/Small Production)- `GET /api/health` - Service health



```bash- `GET /api/health/database` - Database connectivity**Step 3: Start Application**

docker-compose up -d

docker-compose ps- `GET /api/health/memory` - Memory status```bash

curl http://localhost:3001/api/health

```./start.sh



### Kubernetes (Enterprise)### Authentication```



```bash

# Build images

docker build -t staff-scheduler-backend:1.0.0 ./backendAll endpoints require JWT token in Authorization header:This single command:

docker build -t staff-scheduler-frontend:1.0.0 ./frontend

- Builds all Docker images

# Deploy

kubectl apply -f k8s/```bash- Starts MySQL database

kubectl rollout status deployment/staff-scheduler-backend

```Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...- Starts backend API



For complete deployment guide, scaling recommendations, and monitoring setup, see [TECHNICAL.md - Production Deployment](./TECHNICAL.md#production-deployment).```- Starts frontend web app



---- Initializes database schema



## MonitoringFor complete API documentation with request/response examples and schemas, see [TECHNICAL.md](./TECHNICAL.md).- Runs health checks



### Health Checks



```bash---**Step 4: Access Application**

curl http://localhost:3001/api/health

curl http://localhost:3001/api/health/database```

curl http://localhost:3001/api/health/memory

```## Scheduling Algorithm🌐 Frontend:    http://localhost:3000



### Structured Logging📡 Backend API: http://localhost:3001/api



All logs in JSON format for easy parsing:### Constraint Satisfaction Problem (CSP)💾 Database:    http://localhost:8080 (phpMyAdmin)



```json```

{

  "timestamp": "2025-10-22T15:30:45.123Z",The Staff Scheduler implements a hybrid approach combining constraint satisfaction with multi-objective optimization.

  "level": "INFO",

  "service": "backend",**Default Login**

  "path": "/api/schedules/123/generate",

  "statusCode": 200,**Hard Constraints (must satisfy):**```

  "duration": "2543ms",

  "userId": "456"1. All required shifts filled to minimum staffing levelEmail:    admin@company.com

}

```2. No employee assigned to overlapping shiftsPassword: admin123



---3. Assigned staff meet skill requirements```



## Troubleshooting4. Respect employee availability and time-off



| Issue | Solution |### Option 2: Development Setup

|-------|----------|

| Cannot connect to database | Check MySQL container: `docker-compose ps mysql` |**Soft Constraints (optimize for):**

| Port already in use | Change port in `.env` or kill existing process |

| Schedule generation timeout | Reduce scope or increase timeout value |1. Minimize workload variance (fairness)For active development with hot-reload:

| Memory issues | Increase Docker RAM allocation to 4GB+ |

2. Maximize preference satisfaction

---

3. Limit consecutive work days```bash

## Support & Documentation

# Clone and configure

- **Technical Reference**: [TECHNICAL.md](./TECHNICAL.md) - API docs, database schema, advanced configuration

- **Contributing**: [CONTRIBUTING.md](./CONTRIBUTING.md) - Development setup and code standards**Objective Function (minimize):**git clone https://github.com/yourorg/StaffScheduler.git

- **Issues**: GitHub Issues for bug reports and feature requests

- **Security**: Report vulnerabilities to security@example.com```cd StaffScheduler



---Cost = Σ(hard_violations × priority_weight) cp .env.example .env



## License       + Σ(soft_penalties × optimization_weight)



MIT License - See [LICENSE](./LICENSE) file# Start development environment



---Hard Constraint Penalties:./start-dev.sh



**Version:** 1.0.0  - Shift gap: max(0, required - assigned) × 100```

**Status:** Production Ready ✅  

**Created:** October 22, 2025  - Double-booking: 500 per conflict

**Maintainer:** Luca Ostinelli

- Skill mismatch: 20 per missing skillFeatures:

- Availability violation: 1000 per violation- ✅ Backend hot-reload (nodemon)

- ✅ Frontend hot-reload (React dev server)

Soft Constraint Penalties:- ✅ Source code volumes mounted

- Workload variance: √(Σ(hours - mean)²/n) × 5- ✅ Debug port exposed (9229)

- Preference: (avoided_count × 30) - (preferred_count × 20)

- Consecutive days: (excess_days × 15)```bash

```# View logs

docker-compose logs -f backend

### Algorithm: Hybrid Greedy + Simulated Annealingdocker-compose logs -f frontend



**Phase 1: Greedy Initialization** - O(n log n)# Run tests

- Sort shifts by priority (critical → high → normal → low)docker-compose exec backend npm test

- Assign best-available employees to each shift

- Produces feasible solution in seconds# Stop everything

./stop.sh

**Phase 2: Simulated Annealing** - Customizable```

Temperature = 100### Option 3: Manual Setup

Cooling_Rate = 0.95

Max_Iterations = 10,000For advanced users or specific environments:

Timeout = 300 seconds

Loop:# Backend

  - Random perturbation of current solutioncd backend

  - Calculate cost deltanpm install

  - Accept if improvement OR with P(accept) = e^(-delta/T)npm run build

  - Update best solution if improvednpm run db:init  # Initialize database

  - Cool down: Temperature *= Cooling_Ratenpm start

Frontend (in new terminal)

**Complexity:**cd frontend

  • Time: O(n·m·log k + I·n·m) where n=employees, m=shifts, k=skills, I=iterationsnpm install

  • Space: O(n·m) for assignment matrixnpm start

  • Typical runtime: 2-10 seconds (100 employees, 500 shifts)```


Configuration## 📦 Deployment Guide

Environment Variables### Docker Compose (Production)

Create .env from .env.example:Full System Start

```bash# Build and start all services

# Database (MySQL)./start.sh -b

DB_HOST=mysql

DB_PORT=3306# Or just start (uses cached images)

DB_USER=scheduler_user./start.sh

DB_PASSWORD=secure_password_minimum_16_chars```

DB_NAME=staff_scheduler

**Stopping Services**

# Backend API```bash

BACKEND_PORT=3001# Stop but keep volumes/data

NODE_ENV=production./stop.sh

JWT_SECRET=your_base64_encoded_secret_minimum_32_chars

JWT_EXPIRY=7d# Clean: remove containers and volumes

BCRYPT_ROUNDS=12./stop.sh -c



# Frontend# Purge: remove everything

FRONTEND_PORT=3000./stop.sh -p

REACT_APP_API_URL=http://localhost:3001/api```



# Rate Limiting### Rebuild Images

RATE_LIMIT_WINDOW_MS=900000

RATE_LIMIT_MAX_REQUESTS=100```bash

# Rebuild all images

# Logging./build.sh

LOG_LEVEL=info

LOG_FORMAT=json# Rebuild specific service

```./build.sh backend

./build.sh frontend

---

# Build without cache

## Development./build.sh --no-cache



### Project Structure# Development build

./build.sh backend --dev

StaffScheduler/

├── backend/### Health Checks

│ ├── src/

│ │ ├── routes/ # Express endpoints```bash

│ │ ├── services/ # Business logic# Frontend health

│ │ ├── optimization/ # ScheduleOptimizercurl http://localhost:3000/health

│ │ ├── middleware/ # Auth, logging, errors

│ │ ├── config/ # Configuration# Backend health

│ │ ├── types/ # TypeScript interfacescurl http://localhost:3001/api/health

│ │ └── index.ts # Entry point

│ ├── tests/ # Jest tests# Backend readiness

│ ├── Dockerfilecurl http://localhost:3001/api/ready

│ ├── jest.config.json

│ ├── tsconfig.json# View all containers

│ └── package.jsondocker-compose ps

├── frontend/# View container logs

│ ├── src/docker-compose logs mysql

│ │ ├── pages/ # React pagesdocker-compose logs backend

│ │ ├── components/ # UI componentsdocker-compose logs frontend

│ │ ├── services/ # API clients```

│ │ ├── contexts/ # React contexts

│ │ ├── types/ # TypeScript interfaces### Production Deployment

│ │ ├── App.tsx

│ │ └── index.tsxSee TECHNICAL.md for detailed production deployment guide including:

│ ├── public/ # Static assets- Environment configuration

│ ├── Dockerfile- Database backup/restore procedures

│ ├── tsconfig.json- SSL/TLS setup

│ └── package.json- Kubernetes deployment

│- CI/CD integration

├── docker-compose.yml- Monitoring and alerting setup

├── .env.example

├── README.md # This file---

├── TECHNICAL.md # API & deployment docs

├── CONTRIBUTING.md # Development guidelines## ⚙️ Configuration

└── LICENSE




### Local DevelopmentCreate `.env` file from `.env.example`:



```bash```bash

# Install dependenciescp .env.example .env

cd backend && npm install```

cd ../frontend && npm install

Key variables:

# Start database

docker-compose up -d mysql redis```bash

# ═══════════════════════════════════

# Run migrations# DATABASE CONFIGURATION

cd backend && npm run migrate# ═══════════════════════════════════

MYSQL_ROOT_PASSWORD=your-secure-root-password

# Start backend (hot-reload)MYSQL_DATABASE=staff_scheduler

npm run devMYSQL_USER=scheduler_user

MYSQL_PASSWORD=your-secure-password

# In new terminal, start frontendDB_PORT=3306

cd ../frontend && npm run dev

# ═══════════════════════════════════

# Access:# SECURITY (⚠️ CHANGE IN PRODUCTION!)

# Frontend: http://localhost:3000# ═══════════════════════════════════

# API: http://localhost:3001/apiJWT_SECRET=your-256-bit-secret-key-min-32-chars

```SESSION_SECRET=your-session-secret-key

CORS_ORIGIN=http://localhost:3000

### Code Standards

# ═══════════════════════════════════

All code must comply with:# APPLICATION PORTS

- TypeScript strict mode (no implicit any)# ═══════════════════════════════════

- Prettier formatting (2-space indentation)BACKEND_PORT=3001

- ESLint rules (see `.eslintrc`)FRONTEND_PORT=3000

- Jest test coverage (80% minimum)PHPMYADMIN_PORT=8080



See [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed development guidelines.# ═══════════════════════════════════

# FRONTEND CONFIGURATION

---# ═══════════════════════════════════

REACT_APP_API_URL=http://localhost:3001/api

## Production DeploymentREACT_APP_APP_NAME=Staff Scheduler

REACT_APP_DEBUG=false

### Docker Compose (Development/Small Production)

# ═══════════════════════════════════

```bash# BACKEND CONFIGURATION

docker-compose up -d# ═══════════════════════════════════

docker-compose psNODE_ENV=production

curl http://localhost:3001/api/healthPORT=3001

Kubernetes (Enterprise)### Database Schema


# Build images- Users table with role-based access

docker build -t staff-scheduler-backend:1.0.0 ./backend- Employees table with skills and availability

docker build -t staff-scheduler-frontend:1.0.0 ./frontend- Shifts and shift templates

- Schedules with optimization metadata

# Deploy- Assignments with conflict tracking

kubectl apply -f k8s/- Departments with hierarchy

kubectl rollout status deployment/staff-scheduler-backend- Audit logs for compliance

See TECHNICAL.md for complete schema documentation.

For complete deployment guide, scaling recommendations, and monitoring setup, see TECHNICAL.md - Production Deployment.



📡 API Documentation

Monitoring

Base URL

Health Checks```

http://localhost:3001/api

bash

curl http://localhost:3001/api/health

curl http://localhost:3001/api/health/database### Authentication

curl http://localhost:3001/api/health/memoryAll protected endpoints require JWT token in Authorization header:


Authorization: Bearer <JWT_TOKEN>

### Structured Logging```



All logs in JSON format for easy parsing:### Core Endpoints



```json**Authentication**

{```

  "timestamp": "2025-10-22T15:30:45.123Z",POST   /auth/login       - User login

  "level": "INFO",GET    /auth/verify      - Verify token

  "service": "backend",POST   /auth/refresh     - Refresh token

  "path": "/api/schedules/123/generate",POST   /auth/logout      - User logout

  "statusCode": 200,```

  "duration": "2543ms",

  "userId": "456"**Employees**

}```

```GET    /employees        - List all employees

GET    /employees/:id    - Get employee details

---POST   /employees        - Create employee

PUT    /employees/:id    - Update employee

## TroubleshootingDELETE /employees/:id    - Delete employee



| Issue | Solution |GET    /employees/:id/skills        - Get employee skills

|-------|----------|POST   /employees/:id/skills        - Add skill

| Cannot connect to database | Check MySQL container: `docker-compose ps mysql` |DELETE /employees/:id/skills/:skill - Remove skill

| Port already in use | Change port in `.env` or kill existing process |```

| Schedule generation timeout | Reduce scope or increase timeout value |

| Memory issues | Increase Docker RAM allocation to 4GB+ |**Shifts**

```

---GET    /shifts           - List shifts

POST   /shifts           - Create shift

## Support & DocumentationPUT    /shifts/:id       - Update shift

DELETE /shifts/:id       - Delete shift

- **Technical Reference**: [TECHNICAL.md](./TECHNICAL.md) - API docs, database schema, advanced configuration

- **Contributing**: [CONTRIBUTING.md](./CONTRIBUTING.md) - Development setup and code standardsGET    /shifts/templates        - List shift templates

- **Issues**: GitHub Issues for bug reports and feature requestsPOST   /shifts/templates        - Create template

- **Security**: Report vulnerabilities to security@example.com```



---**Schedules**

```

## LicenseGET    /schedules        - List schedules

POST   /schedules        - Create schedule

MIT License - See [LICENSE](./LICENSE) fileGET    /schedules/:id    - Get schedule

PUT    /schedules/:id    - Update schedule

---

POST   /schedules/generate      - Generate optimized schedule

**Version:** 1.0.0  ```

**Status:** Production Ready ✅  

**Created:** October 22, 2025  **Dashboard**

**Maintainer:** Luca Ostinelli```

GET    /dashboard/stats         - Dashboard KPIs
GET    /dashboard/activities    - Recent activities
GET    /dashboard/departments   - Department metrics
```

For complete API specification, see [TECHNICAL.md](./TECHNICAL.md).

---

## 🏗️ Architecture

### System Components

```
┌─────────────────────────────────────────────────────────────┐
│                    USER INTERFACE                            │
│  React SPA (port 3000)                                      │
│  ├── Authentication & Authorization                         │
│  ├── Employee Management                                    │
│  ├── Shift Management                                       │
│  ├── Schedule Visualization                                 │
│  └── Analytics Dashboard                                    │
└──────────────────┬──────────────────────────────────────────┘
                   │ REST API (JSON/HTTPS)
┌──────────────────▼──────────────────────────────────────────┐
│                BACKEND API SERVER                            │
│  Express.js + TypeScript (port 3001)                        │
│  ├── Authentication Layer (JWT)                             │
│  ├── Route Handlers                                         │
│  ├── Business Logic Services                                │
│  ├── Database Abstraction Layer                             │
│  └── Optimization Engine                                    │
└──────────────────┬──────────────────────────────────────────┘
                   │ SQL Queries (TCP 3306)
┌──────────────────▼──────────────────────────────────────────┐
│                  DATA PERSISTENCE                            │
│  MySQL 8.0 Database                                         │
│  ├── Users & Roles                                          │
│  ├── Employees & Skills                                     │
│  ├── Shifts & Templates                                     │
│  ├── Schedules & Assignments                                │
│  └── Departments & Hierarchies                              │
└─────────────────────────────────────────────────────────────┘
```

### Technology Stack

**Frontend**
- React 18.2.0 with TypeScript
- React Router v6 for routing
- Bootstrap 5.3 for responsive UI
- Context API for state management
- Fetch API for HTTP requests

**Backend**
- Express.js 4.18.2 framework
- TypeScript 5.1.6 for type safety
- JWT for authentication
- bcrypt for password hashing
- Connection pooling for database

**Database**
- MySQL 8.0
- Optimized indices for query performance
- Transaction support for data consistency
- Soft deletes for audit trail

**Infrastructure**
- Docker & Docker Compose
- Multi-stage builds for optimization
- Health checks for auto-recovery
- Volume management for persistence

---

## 🔧 Development

### Project Structure

```
StaffScheduler/
├── backend/
│   ├── src/
│   │   ├── index.ts              # Application entry point
│   │   ├── config/               # Configuration management
│   │   ├── routes/               # API route handlers
│   │   ├── services/             # Business logic layer
│   │   ├── middleware/           # Authentication & validation
│   │   ├── optimization/         # Scheduling algorithms
│   │   ├── types/                # TypeScript interfaces
│   │   └── __tests__/            # Test suites
│   ├── database/
│   │   └── init.sql              # Database schema
│   ├── scripts/
│   │   ├── init-database.ts      # Database initialization
│   │   └── demo-data.ts          # Demo data generator
│   ├── Dockerfile
│   └── package.json
│
├── frontend/
│   ├── src/
│   │   ├── index.tsx             # React entry point
│   │   ├── App.tsx               # Root component
│   │   ├── components/           # React components
│   │   ├── pages/                # Page components
│   │   ├── services/             # API service layer
│   │   ├── contexts/             # React contexts
│   │   ├── types/                # TypeScript interfaces
│   │   └── utils/                # Utility functions
│   ├── public/
│   ├── Dockerfile
│   └── package.json
│
├── mysql/
│   └── conf.d/                   # MySQL optimization config
│
├── start.sh                      # Production startup script
├── start-dev.sh                  # Development startup script
├── stop.sh                       # Shutdown script
├── build.sh                      # Build script
├── docker-compose.yml            # Container orchestration
├── .env.example                  # Environment template
├── README.md                     # This file
├── TECHNICAL.md                  # Technical documentation
└── LICENSE
```

### Development Workflow

**1. Setup Development Environment**
```bash
./start-dev.sh
```

**2. Make Code Changes**
- Backend changes auto-reload via nodemon
- Frontend changes auto-reload via React dev server

**3. Run Tests**
```bash
# Backend tests
docker-compose exec backend npm test

# Specific test file
docker-compose exec backend npm test -- api.test.ts

# With coverage
docker-compose exec backend npm run test:coverage
```

**4. Check Code Quality**
```bash
# Linting
docker-compose exec backend npm run lint

# Fix issues
docker-compose exec backend npm run lint:fix

# Format code
docker-compose exec backend npm run format
```

**5. View Logs**
```bash
docker-compose logs -f backend
docker-compose logs -f frontend
docker-compose logs -f mysql
```

### Git Workflow

```bash
# Create feature branch
git checkout -b feature/your-feature

# Make changes and commit
git add .
git commit -m "feat: description of changes"

# Push to repository
git push origin feature/your-feature

# Create pull request on GitHub
```

---

## 🐛 Troubleshooting

### Port Already in Use

**Problem**: Address already in use (port 3000, 3001, 3306, 8080)

**Solution**:
```bash
# Find process using port
lsof -i :3000  # macOS/Linux
netstat -ano | findstr :3000  # Windows

# Kill process
kill -9 <PID>  # macOS/Linux
taskkill /PID <PID> /F  # Windows

# Or use different ports in .env
BACKEND_PORT=3002
FRONTEND_PORT=3001
DB_PORT=3307
```

### Docker Connection Issues

**Problem**: Cannot connect to Docker daemon

**Solution**:
```bash
# Start Docker daemon
# macOS: Open Docker Desktop app
# Linux: sudo systemctl start docker

# Verify Docker is running
docker ps
```

### Database Connection Errors

**Problem**: Backend cannot connect to MySQL

**Solution**:
```bash
# Check MySQL health
docker-compose exec mysql mysqladmin -u root -p ping

# View MySQL logs
docker-compose logs mysql

# Restart MySQL
docker-compose restart mysql

# Reset database
./stop.sh -c
./start.sh
```

### Frontend Cannot Reach Backend API

**Problem**: 404 errors or CORS errors from frontend

**Solution**:
1. Verify `REACT_APP_API_URL` in `.env` matches backend address
2. Check backend is running: `curl http://localhost:3001/api/health`
3. Check CORS configuration in backend
4. Clear browser cache and refresh (Ctrl+Shift+R)

### Memory Issues

**Problem**: Docker containers run out of memory

**Solution**:
```bash
# Increase Docker resources
# Docker Desktop Preferences → Resources → Memory: 8GB+

# Or limit specific service
# In docker-compose.yml under service:
# mem_limit: 2g
```

### Database Initialization Failed

**Problem**: Tables not created, schema not applied

**Solution**:
```bash
# Reinitialize database
docker-compose down -v
docker-compose up -d

# Manually run init script
docker-compose exec -T mysql mysql -u root -p"${MYSQL_ROOT_PASSWORD}" "${MYSQL_DATABASE}" < backend/database/init.sql
```

---

## 📞 Support

### Documentation
- [Technical Documentation](./TECHNICAL.md) - Deep dive into architecture and implementation
- [API Reference](./TECHNICAL.md#api-specification) - Complete endpoint documentation
- [Configuration Guide](./TECHNICAL.md#configuration-management) - Environment and deployment setup

### Getting Help

**Local Issues**
1. Check [Troubleshooting](#troubleshooting) section
2. Review logs: `docker-compose logs`
3. Test health endpoints: `curl http://localhost:3001/api/health`

**Community Support**
- GitHub Issues: [Report bugs or request features](https://github.com/yourorg/StaffScheduler/issues)
- Discussions: [Ask questions or share ideas](https://github.com/yourorg/StaffScheduler/discussions)

**Professional Support**
- Email: support@yourorganization.com
- Documentation: [Full Technical Docs](./TECHNICAL.md)

---

## 📄 License

Staff Scheduler is released under the MIT License. See [LICENSE](LICENSE) file for details.

---

## 👥 Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

---

## 🎯 Roadmap

**Current Version (1.0)**
- ✅ Core scheduling engine
- ✅ Multi-level hierarchies
- ✅ Basic analytics
- ✅ Docker deployment

**Planned Features**
- 📅 Advanced constraint programming (Q2 2025)
- 🔔 Mobile notifications
- 📊 Enhanced reporting
- 🔗 Third-party integrations (HR systems, payroll)
- 🌍 Multi-language support
- 🤖 AI-powered recommendations

---

**Created by**: Luca Ostinelli  
**Last Updated**: October 22, 2025  
**Version**: 1.0.0

For the latest version and updates, visit: https://github.com/yourorg/StaffScheduler

About

Employee scheduling system with role-based coverage and rest rules.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published