CO2060 Project · Semester 3 & 4
University of Peradeniya

Modernizing Outpatient Care with Real-Time Clinical Agility

NexClinic is an enterprise-grade outpatient healthcare and practice management platform. Engineered with Django REST Framework, Next.js, and PostgreSQL, it seamlessly unifies Patients, Doctors, and Clinic Administrators into a secure, responsive digital ecosystem.

2-Tier RBAC Security (Edge & API)
Pessimistic Row-Level Lock Booking
3 Roles Patient, Doctor, Admin
Authentication
HttpOnly JWT + OTP
Concurrency
Zero Double-Booking
Clinical Operational Context

The Challenge of Modern Outpatient Operations

Healthcare facilities often battle fragmented schedules, telephone bottlenecks, and data silos that degrade patient satisfaction and exhaust medical staff.

Traditional Clinic Bottlenecks

Manual appointment coordination and disparate physical registries cause severe clinical overhead:

  • Opaque Availability: Patients cannot view real-time physician schedules across hospital branches.
  • High No-Show & Collision Rates: Simultaneous booking requests lead to accidental duplicate bookings and empty time slots.
  • Fragmented Medical Records: Consultations occur without immediate, consolidated access to patient diagnostic attachments.
  • Administrative Fatigue: Hospital staff spend critical hours reconciling doctor calendars and managing paper queues.

The NexClinic Digital Standard

An integrated, multi-tenant outpatient operating system engineered for clinical precision:

  • Real-Time Doctor Discovery: Comprehensive directory with filtering by medical specialization, hospital branch, and live slot status.
  • Concurrency-Safe Booking: DB-level transactional locking guarantees that slots cannot be double-booked during concurrent requests.
  • Secure Document Lifecycle: Patients securely upload diagnostic files and prescriptions via validated multipart form pipelines.
  • Automated Shift Generation: Celery workers automate 14-day rolling appointment availability based on hospital slot templates.
Role-Based Capabilities

Engineered for Every Clinical Stakeholder

Tailored user experiences designed to empower patients, streamline physician workflows, and give hospital administrators comprehensive oversight.

Physician Discovery & Availability Filtering

Patients search verified practitioners across hospitals by medical discipline, consultation fee, and active slot availability. The Next.js client renders dynamic cards with optimistic state updates to ensure responsive browsing.

Search & Filter Real-Time Slots Hospital Affiliation

Dynamic Appointment Booking

Book, reschedule, or cancel consultation slots. State transitions update immediately in the UI with toast feedback.

Instant Booking Self-Service Rescheduling

Digital Health Records & Attachments

Securely store and manage historical visit summaries, lab reports, and prescriptions. Strict multipart form handling protects binary files.

Diagnostic Storage Prescription History

Real-Time Text Consultations & Health News Feed

Engage in one-on-one consultation threads powered by Django Channels WebSockets. Stay up to date with automated healthcare news fetched dynamically via the integrated GNews API.

ASGI WebSockets AdviceChatThread GNews Feed

Slot & Shift Management

Define recurring weekly availability blocks across affiliated hospitals. Configure patient limits and buffer times per consultation block.

Recurring Templates Patient Limits

Controlled Appointment Lifecycle State Machine

Enforce strict clinical state transitions: PENDING → ACCEPTED or REJECTED → COMPLETED or CANCELLED. Prevents invalid states and automatically notifies patients via email alerts.

State Machine IsDoctor Permissions Email Alerts

Patient Diagnostic History & Consultation Review

Inspect patient medical history, previous clinic visits, and uploaded medical documentation prior to confirming consultations, ensuring informed clinical assessments.

Clinical History Medical Record Viewer

Multi-Hospital Association

Request associations with multiple clinical institutions, tracking verification statuses (PENDING, VERIFIED, REJECTED).

Hospital Verification

Doctor Verification & Credentialing Queue

Hospital administrative staff review incoming medical practitioner registrations, verify professional credentials, and activate clinical booking privileges.

Credential Approval DoctorHospitalVerification

Slot Blueprint Oversight

Manage hospital `SlotTemplates` defining operating shifts, physical clinic rooms, and room capacities.

Capacity Rules Shift Templates

Operational Analytics

Monitor clinic occupancy, appointment throughput, cancellation frequency, and active text consultation loads.

Throughput Metrics

Comprehensive Audit Trail (`UserActivityLog`)

All clinical modifications, user authentications, and slot bookings generate structured records with actor IDs, IP metadata, and JSON state diffs for regulatory audit compliance.

Audit Trail HIPAA/GDPR Foundation Actor Attribution
Interface Design & UX

Authentic Product Experience

Real interfaces built with Next.js App Router and Tailwind CSS, prioritizing clarity, trust, and zero cognitive load.

01 / SECURE ACCESS

Unified Authentication & Two-Factor OTP

A single, secure login gateway serving Patients, Doctors, and Administrators. After credential validation, the system enforces email-gated 6-digit OTP verification. Tokens are delivered strictly via HttpOnly, Secure cookies to prevent XSS session hijacking.

  • Temporary `PendingUser` holding state prevents unverified database bloat.
  • Rate-limited OTP dispatch via SendGrid / SMTP with live cooldown timers.
nexclinic.local / login / otp-challenge
NexClinic OTP Verification Screen
02 / PATIENT PORTAL

Optimistic Booking & Practice Management

Patients experience instant, zero-lag interface responses. When a slot is selected, the client-side state reflects the reservation immediately while a background database transaction verifies capacity using row-level locking.

  • Instant feedback with standardized toast notifications for edge cases.
  • Seamless role-specific redirects managed by Next.js Edge Middleware.
nexclinic.local / user-self / book-appointment
NexClinic Patient Booking Experience
Engineering Deep Dive

Production-Grade Asynchronous Architecture

Designed for strict security, high concurrency, and rapid edge response times.

End-to-End System Topology
Edge / Middleware
Next.js UI
Django REST / Channels
PostgreSQL / Redis
01 / Edge Layer

Next.js Edge Proxy

Intercepts incoming browser requests, decodes HttpOnly session cookies, and enforces route boundaries before server-rendering.

File: src/proxy.ts
02 / UI Layer

React Client & RSC

Next.js 15 App Router with Tailwind CSS. Utilizes React Context and Zustand for optimistic UI mutation handling.

React 19 · TypeScript
03 / Business API

Django REST + ASGI

WSGI handles transactional REST endpoints; Daphne (ASGI) powers persistent WebSockets for live consultations.

DRF · Channels · Celery
04 / Storage & Cache

PostgreSQL & Redis

Relational data integrity with pessimistic row-locking. Redis manages WebSocket channel layers and Celery task queues.

PostgreSQL · Redis 7

Dual-Engine Routing

HTTP REST traffic (`/api/*`) is directed through standard WSGI workers for relational business operations, while WebSocket streams (`/ws/*`) route directly to ASGI Daphne servers, isolating long-lived chat connections from request pools.

Asynchronous Slot Generation

Instead of calculating slot intervals on the fly, Celery Beat runs scheduled routines reading hospital `SlotTemplates` to physically stamp out rolling 14-day booking records in PostgreSQL, keeping query response times below 30ms.

Stateless Edge Token Validation

The Next.js Edge proxy decrypts JWTs in memory to reject unauthorized cross-role attempts with a 307 redirect before reaching the origin Django server, dramatically decreasing server workload.

Technical Foundation

Verified Technologies & Frameworks

Built strictly with modern, production-proven tools ensuring performance, type-safety, and maintainability.

Next.js 15 (App Router)
Frontend & Edge Proxy
TypeScript 5
End-to-End Type Safety
Tailwind CSS
Design System & Utility UI
Django REST Framework
Python 3.12 Backend Core
PostgreSQL
Relational Data & ACID Locks
Redis & Channels
WebSocket Layer & Task Broker
Celery & Celery Beat
Scheduled Slot Generation
Playwright E2E
Cross-Browser Automation
Security & Data Integrity

Built-in Defense & Concurrency Protection

Healthcare platforms demand strict confidentiality and faultless operational integrity. NexClinic guarantees data security across layers.

HttpOnly JWT Cookie Pipeline

Authentication tokens (access and refresh) are written to client browsers strictly via `Set-Cookie` with HttpOnly, Secure, and SameSite=Lax attributes. Client-side JavaScript cannot access the tokens, completely mitigating Cross-Site Scripting (XSS) session theft.

Set-Cookie: access_token=***; HttpOnly; Secure; SameSite=Lax; Path=/

Pessimistic Concurrency Locking

To prevent race conditions during peak booking periods, appointment creation uses PostgreSQL row-level locks (select_for_update). Concurrent booking requests are queued deterministically at the database engine level.

slot = AppointmentAvailableSlot.objects.select_for_update().get(id=slot_id)

Two-Tier RBAC Verification

Role boundaries are verified twice: first at the Next.js edge router (`src/proxy.ts`), and definitively inside Django via granular permission classes (IsPatient, IsDoctor, IsHospitalAdmin).

permission_classes = [IsAuthenticated, IsDoctor]

Cross-Browser E2E Quality Assurance

Crucial clinical user journeys are continuously validated using an automated Playwright test suite spanning Desktop Chromium, Microsoft Edge, and Mobile Chrome profiles to guard against UX regressions.

npx playwright test --project=chromium,edge,mobile-chrome
Evolution & Milestones

Development Roadmap & Status

Transparent separation of implemented foundational capabilities, active QA improvements, and future milestone enhancements.

v1.0 · Implemented & Verified

Core Practice Management & Booking Platform

The complete functional foundation connecting all three user roles with real-time operations:

  • Unified Multi-Role Auth + 2FA OTP
  • Doctor Directory & Specialization Filter
  • Dynamic Slot Booking & Concurrency Locks
  • Medical Record Attachment Uploads
  • Doctor Shift & Availability Management
  • Hospital Admin Doctor Verification
  • WebSocket Text Consultation Threads
  • Dynamic GNews Health Articles Integration
v2.0 · Planned Enhancements

Telehealth Expansion & Clinical Intelligence

Targeted enhancements planned for subsequent academic and production releases:

  • WebRTC Encrypted Video Consultations
  • Production Stripe & PayPal Gateway Integration
  • AI-Assisted Triage & Slot Recommendations
  • Hospital Predictive Wait-Time Analytics
Academic Engineering Team

Team NexAura

Undergraduate student software engineers at the Department of Computer Engineering, Faculty of Engineering, University of Peradeniya.

DS

S.M.D.S.B. Samarakoon

E/23/336
GM

J.G.G. Methmaka

E/23/226
UP

H.M.U.A. Perera

E/23/266
TD

M.T. Dineth

E/23/076

CO2060 — Software Systems Development Project

Department of Computer Engineering · Faculty of Engineering · University of Peradeniya, Sri Lanka

Launch Live App User Manual (PDF) Dev Guide (PDF)