Skip to content

zainabraza06/Healix

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

43 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MERN Stack Node.js Next.js MongoDB Socket.IO TypeScript

Healix β€” Remote Healthcare Management System

A full-stack telemedicine platform enabling virtual consultations, appointment management,
real-time patient–doctor communication, and health monitoring.


Table of Contents

  1. Overview
  2. System Architecture
  3. Tech Stack
  4. Feature Flows & Diagrams
  5. Database Schema
  6. Project Structure
  7. Getting Started
  8. Environment Variables
  9. API Reference
  10. Security
  11. Author

Overview

Healix is a comprehensive telemedicine system with three distinct user roles:

Role Key Capabilities
Patient Book appointments, pay online, track vitals, view medical records, chat with doctors, send emergency alerts
Doctor Manage appointments, complete consultations, issue prescriptions, respond to alerts, request reschedule
Admin Approve/reject doctors, review emergency cancellations, monitor system logs, manage alerts

System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        CLIENT LAYER                             β”‚
β”‚   Next.js 14 (App Router)  Β·  TypeScript  Β·  Tailwind CSS       β”‚
β”‚   Zustand (state)  Β·  React Three Fiber (3D UI)  Β·  Recharts    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚  HTTP (REST) + WebSocket
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        SERVER LAYER                             β”‚
β”‚   Node.js 18  Β·  Express.js  Β·  Socket.IO                       β”‚
β”‚   JWT Auth  Β·  bcrypt  Β·  express-validator  Β·  multer          β”‚
β”‚   Nodemailer  Β·  PDFKit  Β·  Stripe  Β·  node-cron               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚  Mongoose ODM
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        DATA LAYER                               β”‚
β”‚   MongoDB  Β·  Collections: Users, Patients, Doctors, Admins,    β”‚
β”‚   Appointments, Payments, Prescriptions, MedicalRecords,         β”‚
β”‚   Vitals, Alerts, Messages, Logs, Tokens                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Request Flow

Browser β†’ Next.js page β†’ apiClient (Axios) β†’ Express router
       β†’ Auth middleware (JWT verify) β†’ Controller
       β†’ Service (business logic) β†’ Mongoose model β†’ MongoDB
       ← JSON response ← Controller ← Service
       (Socket.IO events fire in parallel for real-time updates)

Tech Stack

Frontend

Technology Version Purpose
Next.js 14 React framework (App Router)
TypeScript 5 Type-safe development
Tailwind CSS 3 Utility-first styling
Framer Motion 12 Page & component animations
React Three Fiber 8 3D animated backgrounds
Socket.IO Client 4 Real-time events & chat
Zustand 4 Global auth state
Recharts 2 Vitals & dashboard charts
Stripe.js 8 Payment UI integration
Lucide React 0.294 Icon library

Backend

Technology Version Purpose
Node.js 18+ JavaScript runtime
Express.js 4 HTTP server & routing
MongoDB 6 NoSQL database
Mongoose 8 MongoDB object modeling
Socket.IO 4 WebSocket server
JWT 9 Stateless authentication
bcryptjs 2 Password hashing
Nodemailer 6 Transactional email
Stripe 20 Payment processing
PDFKit 0.15 Prescription PDF generation
node-cron 3 Scheduled background tasks
express-validator 7 Request input validation

Feature Flows & Diagrams

1. Authentication Flow

flowchart TD
    A([Visitor]) --> B{Register or Login?}

    %% Registration path
    B -->|Register| C[Fill registration form\nPatient or Doctor]
    C --> D[POST /api/auth/register-patient\nor /register-doctor]
    D --> E[Backend: hash password\ncreate User + Patient/Doctor\ngenerate VerificationToken]
    E --> F[Send verification email]
    F --> G[User clicks link\nGET /api/auth/verify-email?token=...]
    G --> H{Doctor?}
    H -->|Yes| I[Status: PENDING\nAwaits admin approval]
    H -->|No| J[Account active\nRedirect to login]

    %% Login path
    B -->|Login| K[POST /api/auth/login]
    K --> L{Credentials valid?}
    L -->|No| M[401 Invalid credentials]
    L -->|Yes| N[Generate accessToken 7d\n+ refreshToken 30d\nSet HTTP-only cookies]
    N --> O{Role?}
    O -->|PATIENT| P[/patient/dashboard]
    O -->|DOCTOR| Q[/doctor/dashboard]
    O -->|ADMIN| R[/admin/dashboard]

    %% Token refresh
    N --> S[Axios interceptor\nauto-refresh on 401]
    S --> T[POST /api/auth/refresh-token\n→ new accessToken in cookie]

    %% Password reset
    A --> U[Forgot password]
    U --> V[POST /api/auth/forgot-password]
    V --> W[Email with reset link\nPasswordResetToken TTL 1h]
    W --> X[POST /api/auth/reset-password\ntoken + newPassword]
    X --> J
Loading

Key security decisions:

  • Access token stored in both HTTP-only cookie and localStorage (cookie for SSR, localStorage for client API calls)
  • Refresh token is HTTP-only cookie only β€” never accessible to JavaScript
  • Password reset always returns 200 even if email not found (prevents email enumeration)

2. Doctor Application & Approval Flow

flowchart TD
    A[Doctor registers\nPOST /api/auth/register-doctor] --> B[application_status: PENDING\nAccount inactive]
    B --> C[Verify email]
    C --> D[Admin reviews\nGET /api/admin/pending-doctors]
    D --> E{Admin decision}
    E -->|Approve| F[PUT /api/admin/doctors/:id/approve\nstatus β†’ APPROVED\nis_active β†’ true\nEmail notification sent]
    E -->|Reject| G[PUT /api/admin/doctors/:id/reject\nstatus β†’ REJECTED\nEmail with reason sent]
    F --> H[Doctor can now log in\nand accept appointments]

    %% Deactivation flow
    H --> I{Doctor requests\ndeactivation?}
    I -->|Yes| J[PUT /api/doctor/status/request\nstatus β†’ DEACTIVATION_REQUESTED]
    J --> K[Admin reviews\nand approves deactivation]
    K --> L[is_active β†’ false\nDoctor cannot take new bookings]

    %% Reactivation
    L --> M[Doctor requests\nreactivation]
    M --> N[Admin approves\nis_active β†’ true]
    N --> H
Loading

3. Appointment Lifecycle Flow

This is the most complex flow in the system. Appointments move through these states:

REQUESTED β†’ CONFIRMED β†’ PAST β†’ COMPLETED
              ↓             ↓
           RESCHEDULE_REQUESTED
              ↓
           CANCELLED

3a. Booking & Confirmation

sequenceDiagram
    actor P as Patient
    actor D as Doctor
    participant S as Backend

    P->>S: GET /api/patient/doctors (browse)
    S-->>P: Doctor list with specializations

    P->>S: GET /api/patient/appointments/available-slots?doctorId&date
    S-->>P: Available 30-min slots (09:00–17:00, no weekends, no break 13:00–14:00)

    P->>S: POST /api/patient/appointments\n(doctorId, date, time, type, reason)
    Note over S: Validates: 3–30 days advance,\nweekday, slot available
    S->>S: Create Appointment status=REQUESTED
    S-->>D: Socket event appointment:requested
    S-->>D: Email notification

    D->>S: PUT /api/doctor/appointments/:id/confirm\n(meetingLink if ONLINE)
    S->>S: status β†’ CONFIRMED\nGenerate challan number\nCreate Payment record (PENDING)
    S-->>P: Socket event appointment:confirmed\n(challan number, amount Rs.1000)
    S-->>P: Email with payment instructions

    Note over S: Conflicting REQUESTED slots\nfor same doctor/time\nauto-cancelled
Loading

3b. Payment & Completion

sequenceDiagram
    actor P as Patient
    actor D as Doctor
    participant S as Backend

    P->>S: POST /api/patient/appointments/:id/pay\n(challan number)
    S->>S: payment_status β†’ PAID\nUpdate Payment record β†’ COMPLETED

    Note over S: Cron job (every 6h):\nCancel CONFIRMED+PENDING appointments\nwith < 24h remaining

    Note over S: Appointment time passes
    S->>S: Cron marks status β†’ PAST

    D->>S: POST /api/doctor/appointments/:id/complete\n(medications[], instructions)
    S->>S: Create Prescription\nstatus β†’ COMPLETED\nchat_enabled β†’ true
    S-->>P: Socket event appointment:completed\n(prescription, instructions)
    S-->>P: Email with prescription details

    P->>S: GET /api/patient/chat/:doctorId\n(chat now available)
Loading

3c. Cancellation & Reschedule Rules

flowchart TD
    A[Appointment Status] --> B{Who cancels / reschedules?}

    B -->|Patient: REQUESTED| C[Withdraw β€” no payment\nstatus β†’ CANCELLED]

    B -->|Patient: CONFIRMED + PAID\n> 24h remaining| D[Cancel with Rs.250 deduction\nRefund Rs.750\nstatus β†’ CANCELLED + PARTIAL_REFUND]

    B -->|Patient: CONFIRMED + PAID\n< 24h remaining| E[BLOCKED β€” cannot cancel\nMust request emergency via admin]

    B -->|Patient: reschedule CONFIRMED + PAID| F[status β†’ RESCHEDULE_REQUESTED\nreschedule_requested_by = PATIENT]
    F --> G{Doctor responds}
    G -->|Approve| H[New slot CONFIRMED\nno extra payment]
    G -->|Reject| I[Patient chooses:\nKeep original OR Cancel Rs.750]

    B -->|Doctor: REQUESTED| J[Permanent cancel\nNo refund\nstatus β†’ CANCELLED]

    B -->|Doctor: CONFIRMED + UNPAID| K[Permanent cancel\nstatus β†’ CANCELLED]

    B -->|Doctor: CONFIRMED + PAID| L[Cannot cancel!\nMust reschedule]
    L --> M[POST /api/doctor/appointments/:id/reschedule-request\nstatus β†’ RESCHEDULE_REQUESTED\nreschedule_requested_by = DOCTOR]
    M --> N{Patient responds}
    N -->|Select new slot| O[Doctor approves\nstatus β†’ CONFIRMED\nno new payment]
    N -->|Cancel| P[Full refund Rs.1000\nstatus β†’ CANCELLED + REFUNDED]

    B -->|Emergency < 24h\nAdmin reviewed| Q[Admin approves\nFull refund Rs.1000\nstatus β†’ CANCELLED + REFUNDED]
    B -->|Emergency < 24h\nAdmin reviewed| R[Admin rejects\nAppointment stands]
Loading

4. Payment Flow

flowchart LR
    A[Appointment REQUESTED] --> B[Doctor CONFIRMS]
    B --> C[Challan number generated\nPayment record created\nstatus = PENDING]
    C --> D[Patient pays\nPOST /api/patient/appointments/:id/pay]
    D --> E[payment_status β†’ PAID\nPayment record β†’ COMPLETED]

    E --> F{Cancellation?}
    F -->|No cancellation| G[Appointment proceeds normally]
    F -->|Patient cancels > 24h| H[Refund Rs.750\nDeduction Rs.250\npayment_status β†’ PARTIAL_REFUND]
    F -->|Doctor reschedule\nPatient declines| I[Full refund Rs.1000\npayment_status β†’ REFUNDED]
    F -->|Emergency approved\nby admin| I
    F -->|System auto-cancel\nunpaid < 24h| J[payment_status β†’ PENDING\nAppointment CANCELLED\nno refund]
Loading

Payment amounts:

Scenario Fee
Appointment fee Rs. 1,000
Patient cancellation (> 24h) Rs. 750 refund (Rs. 250 deduction)
Doctor-initiated reschedule declined Rs. 1,000 full refund
Emergency cancellation approved Rs. 1,000 full refund
System auto-cancel (unpaid) Rs. 0 (never paid)

5. Real-Time Communication Flow

Socket.IO Room Architecture

Server rooms:
  user:{userId}       ← every connected user joins this
  doctor:{doctorId}   ← doctors join this
  patient:{patientId} ← patients join this

Chat Flow

sequenceDiagram
    actor P as Patient
    actor D as Doctor
    participant IO as Socket.IO Server

    Note over P,D: Chat only available after appointment COMPLETED

    P->>IO: emit('join', { userId, role:'PATIENT', patientId })
    D->>IO: emit('join', { userId, role:'DOCTOR', doctorId })
    IO-->>IO: onlineUsers Map updated

    P->>IO: emit('chat:send', { senderId, recipientId, message })
    IO->>IO: Look up recipientId in onlineUsers
    IO-->>D: emit('chat:receive', { senderId, message })

    D->>IO: emit('chat:typing', { senderId, recipientId, isTyping:true })
    IO-->>P: emit('chat:typing', { senderId, isTyping:true })

    P->>IO: emit('chat:checkStatus', { userId: doctorUserId })
    IO-->>P: emit('chat:statusResponse', { userId, isOnline:true })

    P->>IO: disconnect
    IO-->>IO: Remove from onlineUsers
    IO-->>D: emit('user:offline', { userId, role:'PATIENT' })
Loading

Real-Time Event Catalogue

Event Direction Trigger
appointment:requested Server β†’ Doctor Patient books
appointment:confirmed Server β†’ Patient Doctor confirms
appointment:cancelled Server β†’ Patient/Doctor Either party cancels
appointment:completed Server β†’ Patient Doctor marks complete
reschedule:rejected Server β†’ Patient Doctor rejects reschedule
reschedule:doctor_cancelled Server β†’ Patient Doctor cancels reschedule
chat:receive Server β†’ Recipient Message sent
chat:typing Server β†’ Recipient Typing indicator
chat:statusResponse Server β†’ Requester Online status check
doctor:online / patient:online Server β†’ All User joins
user:offline Server β†’ All User disconnects

6. Emergency Alert Flow

flowchart TD
    A[Patient observes abnormal vitals\nor health emergency] --> B{Alert type}

    B -->|General alert to doctor| C[POST /api/patient/alerts\ncreates Alert record]
    C --> D[Doctor receives alert\nGET /api/doctor/alerts]
    D --> E{Doctor responds}
    E -->|Resolve| F[PUT /api/doctor/alerts/:id/resolve\nalert resolved + instructions provided\nAppointment completed + prescription issued]

    B -->|Emergency appointment cancellation\n< 24h remaining| G[POST /api/patient/appointments/:id/emergency-cancel\nreason provided]
    G --> H{Has active pending request?}
    H -->|Yes| I[Error: request already exists]
    H -->|No| J[EmergencyCancellationRequest\nstatus = PENDING\nexpires 12h before appointment]
    J --> K[Admin reviews\nGET /api/admin/emergency-requests]
    K --> L{Admin decision}
    L -->|Approve| M[Appointment CANCELLED\nFull refund Rs.1000\nEmail to patient + doctor]
    L -->|Reject| N[Appointment stands\nEmail to patient with notes]
Loading

7. Vitals & Medical Records Flow

flowchart TD
    A[Patient dashboard] --> B{Input method}

    B -->|Manual entry| C[POST /api/patient/vitals\nbloodPressure, heartRate,\ntemperature, weight, etc.]
    B -->|CSV upload| D[POST /api/patient/vitals/upload\nParse CSV rows β†’ batch insert]

    C --> E[Vitals stored in MongoDB]
    D --> E

    E --> F[GET /api/patient/vitals\nhistory with date filters]
    F --> G[Recharts line/area graphs\non patient dashboard]

    G --> H{Abnormal reading?}
    H -->|Yes| I[Patient sends alert\nto assigned doctor]

    A --> J[GET /api/medical-records\npatient's full history]
    J --> K[View prescriptions,\nappointment notes,\ndiagnoses]

    L[Doctor completes appointment] --> M[Create Prescription record\nmedications + dosage + instructions]
    M --> N[Linked to MedicalRecord\npatient can download PDF]
Loading

8. Scheduled Jobs Flow

flowchart LR
    subgraph "node-cron Scheduler"
        A["Every hour (0 * * * *)"]
        B["Every 6 hours (0 0,6,12,18 * * *)"]
        C["Daily 9 AM (0 9 * * *)"]
    end

    A --> D[cleanupExpiredRequests\nFind REQUESTED appointments\ncreated > 24h ago\n→ status CANCELLED\nEmail patient]

    B --> E[cancelUnpaidConfirmedAppointments\nFind CONFIRMED + PENDING payment\nwith < 24h remaining\n→ status CANCELLED\nEmail patient]

    C --> F[scheduleAppointmentReminders\nFind CONFIRMED for tomorrow\nwhere reminder_sent = false\n→ Email patient with details\n→ reminder_sent = true]
Loading

Database Schema

Collections & Relationships

User (base auth)
 β”œβ”€β”€ Patient (1:1)        β†’ Vitals (1:many)
 β”œβ”€β”€ Doctor  (1:1)        
 └── Admin   (1:1)

Appointment
 β”œβ”€β”€ patient_id β†’ Patient
 β”œβ”€β”€ doctor_id  β†’ Doctor
 └── prescription_id β†’ Prescription (set on COMPLETE)

Payment
 └── appointment_id β†’ Appointment

MedicalRecord
 β”œβ”€β”€ patient_id β†’ Patient
 └── doctor_id  β†’ Doctor

Message
 β”œβ”€β”€ sender_id   β†’ User
 └── receiver_id β†’ User

Alert
 β”œβ”€β”€ patient_id β†’ Patient
 └── doctor_id  β†’ Doctor

EmergencyCancellationRequest
 └── appointment_id β†’ Appointment

DoctorEmergencyRescheduleRequest
 └── appointment_id β†’ Appointment

Log             (system audit trail)
VerificationToken
PasswordResetToken

Appointment Status Reference

Status Description
REQUESTED Patient submitted, awaiting doctor confirmation
CONFIRMED Doctor confirmed, patient must pay
RESCHEDULE_REQUESTED Either party requested a new slot
PAST Appointment time has passed (auto-set by cron)
COMPLETED Doctor marked complete, prescription issued
CANCELLED Cancelled by patient, doctor, admin, or system

Project Structure

Healix/
β”œβ”€β”€ backend/
β”‚   └── src/
β”‚       β”œβ”€β”€ config/
β”‚       β”‚   β”œβ”€β”€ db.js            # MongoDB connection
β”‚       β”‚   β”œβ”€β”€ email.js         # Nodemailer transporter
β”‚       β”‚   β”œβ”€β”€ index.js         # Environment config loader
β”‚       β”‚   β”œβ”€β”€ jwt.js           # Token generation & verification
β”‚       β”‚   └── socket.js        # Socket.IO server + room management
β”‚       β”œβ”€β”€ controllers/         # Thin HTTP handlers β€” delegate to services
β”‚       β”‚   β”œβ”€β”€ authController.js
β”‚       β”‚   β”œβ”€β”€ adminController.js
β”‚       β”‚   β”œβ”€β”€ appointmentController.js
β”‚       β”‚   β”œβ”€β”€ doctorController.js
β”‚       β”‚   β”œβ”€β”€ medicalRecordController.js
β”‚       β”‚   └── patientController.js
β”‚       β”œβ”€β”€ middleware/
β”‚       β”‚   β”œβ”€β”€ auth.js          # JWT verify + role check
β”‚       β”‚   β”œβ”€β”€ chatGuard.js     # Blocks chat unless appointment COMPLETED
β”‚       β”‚   β”œβ”€β”€ errorHandler.js  # Global error formatter
β”‚       β”‚   └── validator.js     # express-validator runner
β”‚       β”œβ”€β”€ models/              # Mongoose schemas
β”‚       β”‚   β”œβ”€β”€ User.js          # Base auth document
β”‚       β”‚   β”œβ”€β”€ Patient.js / Doctor.js / Admin.js
β”‚       β”‚   β”œβ”€β”€ Appointment.js   # Full lifecycle model
β”‚       β”‚   β”œβ”€β”€ Payment.js       # Transaction records
β”‚       β”‚   β”œβ”€β”€ Prescription.js
β”‚       β”‚   β”œβ”€β”€ MedicalRecord.js
β”‚       β”‚   β”œβ”€β”€ Vitals.js
β”‚       β”‚   β”œβ”€β”€ Alert.js
β”‚       β”‚   β”œβ”€β”€ Message.js
β”‚       β”‚   β”œβ”€β”€ EmergencyCancellationRequest.js
β”‚       β”‚   β”œβ”€β”€ DoctorEmergencyRescheduleRequest.js
β”‚       β”‚   β”œβ”€β”€ Log.js
β”‚       β”‚   β”œβ”€β”€ VerificationToken.js
β”‚       β”‚   └── PasswordResetToken.js
β”‚       β”œβ”€β”€ routes/
β”‚       β”‚   β”œβ”€β”€ index.js         # Mounts all route groups under /api
β”‚       β”‚   β”œβ”€β”€ authRoutes.js
β”‚       β”‚   β”œβ”€β”€ adminRoutes.js
β”‚       β”‚   β”œβ”€β”€ doctorRoutes.js
β”‚       β”‚   β”œβ”€β”€ patientRoutes.js
β”‚       β”‚   β”œβ”€β”€ medicalRecordRoutes.js
β”‚       β”‚   β”œβ”€β”€ chatRoutes.js
β”‚       β”‚   └── logRoutes.js
β”‚       β”œβ”€β”€ services/            # All business logic lives here
β”‚       β”‚   β”œβ”€β”€ authService.js
β”‚       β”‚   β”œβ”€β”€ appointmentService.js  # 2500+ line core service
β”‚       β”‚   β”œβ”€β”€ adminService.js
β”‚       β”‚   β”œβ”€β”€ doctorService.js
β”‚       β”‚   β”œβ”€β”€ patientService.js
β”‚       β”‚   β”œβ”€β”€ medicalRecordService.js
β”‚       β”‚   β”œβ”€β”€ logService.js
β”‚       β”‚   β”œβ”€β”€ schedulerService.js    # node-cron jobs
β”‚       β”‚   β”œβ”€β”€ stripeService.js
β”‚       β”‚   └── userService.js
β”‚       β”œβ”€β”€ utils/
β”‚       β”‚   β”œβ”€β”€ helpers.js
β”‚       β”‚   β”œβ”€β”€ logger.js        # Writes to Log collection
β”‚       β”‚   └── response.js      # Standardised success/error wrappers
β”‚       β”œβ”€β”€ validators/
β”‚       β”‚   └── authValidators.js
β”‚       β”œβ”€β”€ scripts/
β”‚       β”‚   └── initDatabase.js  # Seed admin account
β”‚       └── server.js            # Express app + HTTP server bootstrap
β”‚
β”œβ”€β”€ frontend/
β”‚   └── src/
β”‚       β”œβ”€β”€ app/                 # Next.js 14 App Router
β”‚       β”‚   β”œβ”€β”€ page.tsx         # Landing page
β”‚       β”‚   β”œβ”€β”€ login/
β”‚       β”‚   β”œβ”€β”€ register/
β”‚       β”‚   β”œβ”€β”€ verify-email/
β”‚       β”‚   β”œβ”€β”€ forgot-password/
β”‚       β”‚   β”œβ”€β”€ reset-password/
β”‚       β”‚   β”œβ”€β”€ admin/
β”‚       β”‚   β”‚   β”œβ”€β”€ dashboard/
β”‚       β”‚   β”‚   β”œβ”€β”€ pending-doctors/
β”‚       β”‚   β”‚   β”œβ”€β”€ doctors/
β”‚       β”‚   β”‚   β”œβ”€β”€ patients/
β”‚       β”‚   β”‚   β”œβ”€β”€ appointments/
β”‚       β”‚   β”‚   β”œβ”€β”€ emergency-requests/
β”‚       β”‚   β”‚   β”œβ”€β”€ alerts/
β”‚       β”‚   β”‚   β”œβ”€β”€ logs/
β”‚       β”‚   β”‚   └── add/
β”‚       β”‚   β”œβ”€β”€ doctor/
β”‚       β”‚   β”‚   β”œβ”€β”€ dashboard/
β”‚       β”‚   β”‚   β”œβ”€β”€ appointments/
β”‚       β”‚   β”‚   β”œβ”€β”€ patients/
β”‚       β”‚   β”‚   └── alerts/
β”‚       β”‚   └── patient/
β”‚       β”‚       β”œβ”€β”€ dashboard/
β”‚       β”‚       β”œβ”€β”€ appointments/
β”‚       β”‚       β”œβ”€β”€ vitals/
β”‚       β”‚       β”œβ”€β”€ medical-records/
β”‚       β”‚       β”œβ”€β”€ alerts/
β”‚       β”‚       β”œβ”€β”€ profile/
β”‚       β”‚       └── chat/[doctorId]/
β”‚       β”œβ”€β”€ components/
β”‚       β”‚   β”œβ”€β”€ canvas/          # React Three Fiber 3D backgrounds
β”‚       β”‚   β”œβ”€β”€ charts/          # Recharts wrappers
β”‚       β”‚   β”œβ”€β”€ ProtectedLayout.tsx   # Role-based route guard
β”‚       β”‚   β”œβ”€β”€ ChatModal.tsx
β”‚       β”‚   β”œβ”€β”€ Navbar.tsx
β”‚       β”‚   └── ...
β”‚       β”œβ”€β”€ hooks/
β”‚       β”‚   β”œβ”€β”€ useApi.ts        # Generic data-fetching hook
β”‚       β”‚   β”œβ”€β”€ useForm.ts
β”‚       β”‚   β”œβ”€β”€ usePagination.ts
β”‚       β”‚   └── usePatientAlerts.ts
β”‚       β”œβ”€β”€ lib/
β”‚       β”‚   β”œβ”€β”€ apiClient.ts     # Typed Axios wrapper for all endpoints
β”‚       β”‚   β”œβ”€β”€ authStore.ts     # Zustand auth store
β”‚       β”‚   β”œβ”€β”€ socket.ts        # Socket.IO client singleton
β”‚       β”‚   └── validation.ts
β”‚       └── types/
β”‚           └── index.ts         # Shared TypeScript interfaces
β”‚
β”œβ”€β”€ .gitignore
└── README.md

Getting Started

Prerequisites

Requirement Version
Node.js β‰₯ 18.0
MongoDB local or Atlas
npm β‰₯ 9
Gmail account for email notifications
Stripe account for payment integration

Installation

1. Clone the repository

git clone https://github.com/zainabraza06/Remote_HealthCare_Management_System.git
cd Remote_HealthCare_Management_System

2. Set up backend

cd backend
npm install
cp .env.example .env
# Fill in your values in .env

3. Set up frontend

cd ../frontend
npm install
cp .env.local.example .env.local
# Fill in your values in .env.local

4. Seed the database

cd ../backend
npm run init-db

5. Start development servers

Terminal 1 β€” Backend:

cd backend
npm run dev       # nodemon on port 8080

Terminal 2 β€” Frontend:

cd frontend
npm run dev       # Next.js on port 3000

6. Access the application

Service URL
Frontend http://localhost:3000
Backend API http://localhost:8080/api
Health check http://localhost:8080/api/health

Environment Variables

Backend β€” backend/.env

# Server
PORT=8080
NODE_ENV=development

# MongoDB
MONGODB_URI=mongodb://localhost:27017/healix

# JWT (use strong random secrets in production)
JWT_SECRET=your_jwt_secret_key
JWT_REFRESH_SECRET=your_refresh_secret_key
JWT_EXPIRES_IN=7d
JWT_REFRESH_EXPIRES_IN=30d

# Email (Gmail with App Password)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your_email@gmail.com
EMAIL_PASS=your_gmail_app_password

# Stripe
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# CORS
FRONTEND_URL=http://localhost:3000

Frontend β€” frontend/.env.local

NEXT_PUBLIC_API_URL=http://localhost:8080/api
NEXT_PUBLIC_SOCKET_URL=http://localhost:8080
NEXT_PUBLIC_APP_NAME=Healix
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key

API Reference

Authentication β€” /api/auth

Method Endpoint Auth Description
POST /register-patient β€” Register new patient
POST /register-doctor β€” Submit doctor application
POST /login β€” Login (sets HTTP-only cookies)
POST /logout JWT Clear session cookies
POST /refresh-token Cookie Issue new access token
GET /me JWT Get current user profile
GET /verify-email?token= β€” Verify email address
POST /forgot-password β€” Send password reset email
POST /reset-password β€” Reset password with token
PUT /change-password JWT Change password (logged in)

Patient β€” /api/patient

Method Endpoint Description
GET /dashboard Dashboard stats & upcoming appointments
GET /doctors Search available approved doctors
GET /appointments All patient appointments (with filters)
POST /appointments Book new appointment
PUT /appointments/:id/pay Process appointment payment
PUT /appointments/:id/cancel Cancel appointment
POST /appointments/:id/reschedule Request reschedule
POST /appointments/:id/emergency-cancel Request emergency cancellation
GET /vitals Vitals history
POST /vitals Add vitals entry
POST /vitals/upload Batch upload via CSV
GET /alerts View sent alerts
POST /alerts Send emergency alert to doctor
GET /profile Patient profile
PUT /profile Update profile

Doctor β€” /api/doctor

Method Endpoint Description
GET /dashboard Dashboard stats
GET /appointments All doctor appointments
PUT /appointments/:id/confirm Confirm appointment (+ meeting link for online)
PUT /appointments/:id/reject Reject appointment request
POST /appointments/:id/complete Complete with prescription
PUT /appointments/:id/reschedule-request Request patient reschedule
PUT /appointments/:id/approve-reschedule Approve patient's reschedule
PUT /appointments/:id/reject-reschedule Reject patient's reschedule
GET /patients Assigned patients list
GET /alerts Incoming patient alerts
PUT /alerts/:id/resolve Resolve alert
GET /profile Doctor profile
PUT /status/request Request activation/deactivation

Admin β€” /api/admin

Method Endpoint Description
GET /dashboard System-wide statistics
GET /pending-doctors Doctors awaiting review
PUT /doctors/:id/approve Approve doctor application
PUT /doctors/:id/reject Reject doctor application
GET /doctors All doctors (with filters)
GET /patients All patients
GET /appointments All appointments
GET /emergency-requests Pending emergency cancellations
PUT /emergency-requests/:id/review Approve or reject
GET /alerts System alerts
POST /alerts Create system alert
DELETE /alerts/:id Delete alert
GET /logs System activity logs

Chat β€” /api/chat

Method Endpoint Description
GET /patient/:doctorId/history Chat history (patient view)
GET /doctor/:patientId/history Chat history (doctor view)
POST /send Persist a chat message

Medical Records β€” /api/medical-records

Method Endpoint Description
GET / Patient's full medical history
GET /:id Single record detail
GET /:id/prescription/pdf Download prescription PDF

Security

Feature Implementation
Password hashing bcryptjs, 10 salt rounds
Access tokens JWT, 7-day expiry, HTTP-only cookie + Authorization header
Refresh tokens JWT, 30-day expiry, HTTP-only cookie only
CORS Restricted to configured origins
Input validation express-validator on all mutation endpoints
Role-based access auth.js middleware enforces role per route group
Chat guard chatGuard.js blocks chat unless appointment is COMPLETED
Email enumeration Password reset always returns 200 regardless of email existence
Secret env vars .env / .env.local excluded from version control

Author

Zainab Raza Malik


Made with care for better healthcare accessibility

About

A full-stack MERN application for remote patient-doctor consultations featuring real-time chatting, appointment scheduling, medical records management, and secure payment processing.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors