Skip to content

PranjalSK03/Bed_Manager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

80 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Hospital Bed Management System

A comprehensive real-time hospital bed management platform that synchronizes patient data, bed availability, and emergency transfers across multiple systems. Built with microservices architecture featuring Hospital API and Bed Manager with real-time Socket.IO communication.

πŸ—οΈ System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Hospital Bed Management System                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Hospital API   │◄────────►│  Bed Manager     │◄────────►│  Frontend (React)β”‚
β”‚   (Port 5000)    β”‚ Webhooks β”‚  (Port 4000)     β”‚ Socket.IOβ”‚  (Port 5173)     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚                              β”‚                              β”‚
       β”‚                              β”‚                              β”‚
       β–Ό                              β–Ό                              β–Ό
  MongoDB (Hospital)            MongoDB (Bed Mgr)           Browser Clients
  - Patients                    - EncounterSnapshots         - Doctors
  - Staff                       - EmergencyRequests          - Nurses
  - Wards                       - TransferRequests           - Ward Managers
  - Beds                        - AlertNotifications         - Admins
  - Encounters                  - OccupancySnapshots

Communication Flow

  1. Hospital API β†’ Bed Manager (Webhooks)

    • Bed status changes
    • Patient admissions/discharges
    • Encounter updates
    • Real-time data synchronization
  2. Bed Manager β†’ Hospital API (REST API)

    • Patient transfers
    • Bed status updates
    • Emergency admissions
    • Periodic data sync (every 5 minutes)
  3. Bed Manager β†’ Frontend (Socket.IO)

    • Real-time alerts
    • Bed availability updates
    • Emergency notifications
    • Occupancy alerts

🎯 Key Features

Real-Time Operations

  • Live Bed Tracking: Instant updates on bed availability across all wards
  • Socket.IO Notifications: Real-time alerts for emergencies, transfers, and occupancy
  • Auto-Sync: Automatic 5-minute synchronization with Hospital API
  • Webhook Integration: Bi-directional data flow with loop prevention

Emergency Management

  • Smart Bed Allocation: Nearest available bed algorithm based on ward distances
  • Priority Routing: Critical patients prioritized for emergency wards
  • Auto-Approval: Automatic emergency request processing based on urgency
  • Multi-User Alerts: Notifications sent to all relevant ward managers and nurses

Analytics & Monitoring

  • Occupancy Tracking: 15-minute interval snapshots for trend analysis
  • Forecasting: Bed demand prediction using historical data
  • Alert System: Tiered urgency levels (low/medium/high/critical)
  • Activity Logging: Complete audit trail of all bed operations

User Management

  • Role-Based Access: Doctor, Nurse, Ward Manager, Admin roles
  • Ward Assignment: Staff assigned to specific wards
  • JWT Authentication: Secure token-based authentication
  • Permission System: Granular access control per role

πŸ“Š Technology Stack

Backend (Bed Manager)

  • Runtime: Node.js 18+
  • Framework: Express.js 5.x
  • Database: MongoDB with Mongoose 7.x
  • Real-time: Socket.IO 4.6
  • Authentication: JWT (jsonwebtoken)
  • Scheduling: node-cron
  • HTTP Client: node-fetch

Backend (Hospital API)

  • Runtime: Node.js 18+
  • Framework: Express.js 5.x
  • Database: MongoDB with Mongoose 8.x
  • Webhooks: HMAC-SHA256 signature verification
  • Data Seeding: Custom seed scripts

Frontend

  • Framework: React 18.2
  • Build Tool: Vite 7.2
  • UI Library: Custom medical-themed components
  • Charts: Recharts, D3.js
  • 3D Visualization: Three.js
  • Real-time: Socket.IO Client 4.8
  • Icons: React Icons

πŸš€ Quick Start

Prerequisites

# Required software
- Node.js >= 18.0.0
- MongoDB >= 4.4
- npm or yarn
- Git

Installation

  1. Clone Repository
git clone https://github.com/PranjalSK03/Bed_Manager.git
cd Bed_Manager
  1. Setup environment variables – create .env files in the backend, frontend of Bed Manager, and Hospital API folder, then add the following contents:

Bed Manager - backend (.env):

MONGODB_URI=mongodb+srv://ghelanimeet2002:Meet%405568@cluster0.uv2gcwr.mongodb.net/?appName=
PORT=4000
JWT_SECRET=bed_manager_secret_key_123
HOSPITAL_API_URL=http://localhost:5000/api/v1/hospital
AUTO_SYNC_INTERVAL_MINUTES=5
WEBHOOK_SHARED_SECRET=dev-webhook-secret

Bed Manager - frontend (.env):

VITE_API_BASE=http://localhost:4000/api/v1/bed_manager
HOSPITAL_API_URL=http://localhost:3000/api/v1/hospital

Hospital API (.env):

MongoDB_URL=mongodb+srv://ghelanimeet2002:Meet%405568@hospitaldata.rhee1rm.mongodb.net/?appN
PORT=5000
BED_MANAGER_WEBHOOK_URL=http://localhost:4000/api/v1/bed_manager/webhooks
WEBHOOK_SHARED_SECRET=dev-webhook-secret
  1. Open three separate terminals: one for Hospital API, one for backend, and one for frontend of Bed Manager.

  2. Install backend dependencies – run npm install (cd to Bed_manager/backend).

  3. Install frontend dependencies – run npm install (cd to Bed_manager/frontend).

  4. Install Hospital API dependencies – run npm install (cd to Hospital_API).

  5. Start the services:

# Terminal 1 - Hospital API
cd Hospital_API
npm run dev

# Terminal 2 - Bed Manager Backend
cd Bed_manager/backend
npm run dev

# Terminal 3 - Bed Manager Frontend
cd Bed_manager/frontend
npm run dev
  1. Access Application
Frontend: http://localhost:5173
Bed Manager API: http://localhost:4000
Hospital API: http://localhost:5000

Production Deployment (Optional)

If the above process feels tedious, you can use the hosted version instead (although it may have latency during some operations): https://bed-manager-frontend.onrender.com/

Default Login Credentials

Role Username Password
Admin admin Admin123
ICU Manager anuradha 123456
General Ward Manager karan 123456
Nurse Cardiology ICU Ward 1 nurse1 123456
Doctor Cardiology doc1 123456

Note: The Admin has the ability to assign or edit user credentials. For any credential changes, login as Admin and navigate to the Admin Panel.

πŸ“ Project Structure

End_sem/
β”œβ”€β”€ Hospital_API/              # Source of truth for patient data
β”‚   β”œβ”€β”€ app.js                # Express server setup
β”‚   β”œβ”€β”€ config/               # Database configuration
β”‚   β”œβ”€β”€ controllers/          # Request handlers
β”‚   β”œβ”€β”€ models/               # Mongoose schemas (Patient, Bed, Encounter, Ward, Staff)
β”‚   β”œβ”€β”€ routes/               # API endpoints
β”‚   β”œβ”€β”€ utils/                # Webhook sender utility
β”‚   └── scripts/              # Database seeding scripts
β”‚
β”œβ”€β”€ Bed_manager/
β”‚   β”œβ”€β”€ backend/              # Real-time bed management server
β”‚   β”‚   β”œβ”€β”€ app.js           # Express + Socket.IO server
β”‚   β”‚   β”œβ”€β”€ config/          # DB config, ward distances
β”‚   β”‚   β”œβ”€β”€ controllers/     # Business logic (14 controllers)
β”‚   β”‚   β”œβ”€β”€ middleware/      # JWT authentication
β”‚   β”‚   β”œβ”€β”€ models/          # Mongoose schemas (13 models)
β”‚   β”‚   β”œβ”€β”€ routes/          # API routes (14 route files)
β”‚   β”‚   β”œβ”€β”€ services/        # Core services
β”‚   β”‚   β”‚   β”œβ”€β”€ autoSync.js         # Periodic Hospital API sync
β”‚   β”‚   β”‚   β”œβ”€β”€ hospitalClient.js   # HTTP client for Hospital API
β”‚   β”‚   β”‚   β”œβ”€β”€ nearestBed.js       # Smart bed allocation
β”‚   β”‚   β”‚   β”œβ”€β”€ occupancyAlert.js   # Alert generation
β”‚   β”‚   β”‚   └── socket.js           # Socket.IO management
β”‚   β”‚   β”œβ”€β”€ schedulers/      # Cron jobs
β”‚   β”‚   └── scripts/         # Utility scripts
β”‚   β”‚
β”‚   └── frontend/            # React SPA
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ components/  # Reusable UI components
β”‚       β”‚   β”œβ”€β”€ pages/       # Main views (14 pages)
β”‚       β”‚   β”œβ”€β”€ theme/       # Medical color scheme
β”‚       β”‚   β”œβ”€β”€ api.js       # API client
β”‚       β”‚   β”œβ”€β”€ socket.js    # Socket.IO client
β”‚       β”‚   └── App.jsx      # Root component
β”‚       └── public/          # Static assets

πŸ”„ Data Synchronization

Periodic Sync (Pull from Hospital API)

// Runs every 5 minutes (configurable)
AutoSync Process:
1. Fetch all wards from Hospital API
2. Fetch all beds from Hospital API  
3. Fetch active encounters from Hospital API
4. Fetch patient data from Hospital API
5. Update/Create records in Bed Manager MongoDB
6. Track sync in SyncRun collection

Real-Time Webhooks (Push from Hospital API)

Hospital API Event β†’ Webhook Sent β†’ Bed Manager Processes β†’ Socket.IO Broadcast

Supported Events:
- bed.updated        β†’ Bed status/equipment changed
- bed.created        β†’ New bed added
- encounter.updated  β†’ Patient admission/transfer
- encounter.created  β†’ New patient encounter
- encounter.deleted  β†’ Patient discharged
- patient.deleted    β†’ Patient record removed

Loop Prevention Mechanism

// Bed Manager β†’ Hospital API request
Headers: { 'X-Sync-Source': 'bed_manager' }

// Hospital API checks before sending webhook
if (syncSource === 'bed_manager') {
  skip_webhook(); // Prevents infinite loop
}

🎨 Frontend Features

Pages & Views

  1. Landing Page: Marketing page with feature highlights
  2. Login: JWT authentication
  3. Dashboard: Main control center with navigation
  4. Beds: Real-time bed status grid with filters
  5. Wards: Ward management and occupancy overview
  6. Emergency Requests: Urgent admission queue with auto-allocation
  7. Patient Transfers: Transfer request workflow
  8. Analytics: Occupancy trends, forecasting charts
  9. Alerts: System notifications and warnings
  10. Users: User management (admin only)
  11. Profile: User settings and preferences
  12. 3D Hospital Map: Interactive ward visualization
  13. Encounter Snapshots: Patient encounter history
  14. Admin Panel: System configuration

UI Components

  • AlertToast: Real-time notification toasts
  • ECGLoader: Medical-themed loading animation
  • Icons: Custom medical icon set
  • Charts: Recharts for analytics
  • 3D Map: Three.js hospital visualization

πŸ” Security Features

Authentication

  • JWT token-based authentication
  • Secure password hashing with bcrypt
  • Token expiration and refresh
  • localStorage for token persistence

Authorization

  • Role-based access control (RBAC)
  • Ward-specific permissions
  • Protected API endpoints
  • Middleware authentication guards

Data Security

  • HMAC-SHA256 webhook signatures
  • Environment variable secrets
  • CORS configuration
  • Input validation and sanitization

πŸ“ˆ Monitoring & Alerts

Occupancy Alerts

Thresholds:
- 50-74%: Low urgency
- 75-79%: Medium urgency  
- 80-89%: High urgency
- 90%+:   Critical urgency

Alert Triggers:
βœ“ Occupancy increase β†’ Alert sent
βœ— Occupancy decrease β†’ No alert (improvement)
βœ— No change β†’ No alert (status quo)

Alert Notification System

  • User-specific Socket.IO rooms
  • Multi-recipient broadcasting
  • Seen/unseen tracking
  • Auto-dismissal based on urgency
  • Sound notifications

πŸ§ͺ Testing & Development

Running Tests

# Hospital API
cd Hospital_API
npm run verify

# Test specific routes
node test-routes.js

Development Mode

# All services use nodemon for hot reload
npm run dev

# Production mode
npm start

Database Seeding

# Hospital API - Create sample patients, wards, beds, encounters
cd Hospital_API
npm run seed

# Bed Manager - Create user accounts
cd Bed_manager/backend
npm run seed

🌐 API Documentation

Hospital API Endpoints

GET    /api/v1/hospital/patients          - List patients
POST   /api/v1/hospital/patients          - Create patient
GET    /api/v1/hospital/wards             - List wards
GET    /api/v1/hospital/beds              - List beds
PATCH  /api/v1/hospital/beds/:id          - Update bed
GET    /api/v1/hospital/encounters        - List encounters
PATCH  /api/v1/hospital/encounters/:id/transfer - Transfer patient
GET    /api/v1/hospital/sync/beds         - Sync endpoint
POST   /api/v1/hospital/sync/beds/patch   - Apply bed patch

Bed Manager API Endpoints

POST   /api/v1/bed_manager/auth/login                    - User login
GET    /api/v1/bed_manager/beds                          - List beds
PUT    /api/v1/bed_manager/beds/:id                      - Update bed
POST   /api/v1/bed_manager/beds/:id/update-and-push      - Update & sync to Hospital
GET    /api/v1/bed_manager/emergency-requests            - List emergency requests
POST   /api/v1/bed_manager/emergency-requests            - Create emergency
POST   /api/v1/bed_manager/emergency-requests/:id/accept - Accept request
GET    /api/v1/bed_manager/transfer-requests             - List transfers
POST   /api/v1/bed_manager/transfer-requests             - Create transfer
GET    /api/v1/bed_manager/alert-notifications           - Get alerts
PUT    /api/v1/bed_manager/alert-notifications/:id/mark-seen - Mark seen
POST   /api/v1/bed_manager/webhooks                      - Receive webhooks

πŸ”§ Configuration

Environment Variables

Hospital API (.env)

PORT=5000
MONGODB_URI=mongodb://127.0.0.1:27017/hospital_api
BED_MANAGER_WEBHOOK_URL=http://localhost:4000/api/v1/bed_manager/webhooks
WEBHOOK_SHARED_SECRET=your-webhook-secret
ALLOWED_ORIGINS=http://localhost:5173,*

Bed Manager Backend (.env)

PORT=4000
MONGODB_URI=mongodb://127.0.0.1:27017/bed_manager
JWT_SECRET=your-jwt-secret
WEBHOOK_SHARED_SECRET=your-webhook-secret
HOSPITAL_API_URL=http://localhost:5000/api/v1/hospital
AUTO_SYNC_INTERVAL_MINUTES=5
FRONTEND_ORIGIN=http://localhost:5173
OCCUPANCY_SNAPSHOT_INTERVAL=*/15 * * * *
OCCUPANCY_CLEANUP_DAYS=90

Frontend (.env)

VITE_API_BASE=http://localhost:4000/api/v1/bed_manager

πŸ“Š Database Schema

Hospital API Collections

  • patients: Patient demographics and medical records
  • staff: Hospital staff with role and ward assignments
  • wards: Ward configuration and metadata
  • beds: Bed inventory with equipment and status
  • encounters: Active patient admissions and encounters

Bed Manager Collections

  • users: System users (doctors, nurses, managers, admins)
  • wards: Synchronized ward data from Hospital API
  • beds: Synchronized bed data with sync status
  • encounterSnapshots: Patient encounter snapshots
  • emergencyRequests: Urgent admission requests
  • transferRequests: Patient transfer workflows
  • alertNotifications: User notifications and alerts
  • occupancySnapshots: Historical occupancy data
  • forecasts: Bed demand predictions
  • syncRuns: Sync operation logs
  • activityLogs: User action audit trail
  • webhookEvents: Webhook delivery tracking

πŸ› Troubleshooting

Common Issues

MongoDB Connection Failed

# Ensure MongoDB is running
sudo systemctl status mongod
sudo systemctl start mongod

Port Already in Use

# Kill process on port 4000
lsof -ti:4000 | xargs kill -9

# Or change PORT in .env file

Webhook Not Working

# Verify WEBHOOK_SHARED_SECRET matches in both APIs
# Check BED_MANAGER_WEBHOOK_URL is correct
# Ensure both servers are running

Socket.IO Not Connecting

# Check CORS configuration
# Verify frontend connects to correct port
# Check browser console for errors

πŸ“ Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/AmazingFeature)
  3. Commit changes (git commit -m 'Add AmazingFeature')
  4. Push to branch (git push origin feature/AmazingFeature)
  5. Open Pull Request

πŸ‘₯ Authors

This project was developed by Team 5:

πŸ™ Acknowledgments

This project was developed as part of the Software System Development course at International Institute of Information Technology, Hyderabad (IIIT Hyderabad) under the guidance of Professor Sai Anirudh Karre.

We would also like to acknowledge:

  • MongoDB for NoSQL database
  • Socket.IO for real-time communication
  • React team for frontend framework
  • Express.js for backend framework
  • Medical UI inspiration from healthcare systems

πŸ“ž Support

For issues and questions:

  • GitHub Issues: Create Issue
  • Email: Contact repository owner

Version: 1.0.0
Last Updated: December 2025
Node Version: >=18.0.0

About

project for SSD endsem by Team 5

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 5