A polished, healthcare-grade web application for monitoring surgical patients through their post-operative recovery. AfterCare provides role-based experiences for patients, surgeons, caregivers, and practice administrators — powered by Supabase and a deterministic AI engine.
- Overview
- Tech Stack
- Design System
- Getting Started
- Application Structure
- Directory Layout
- Route Reference
- Data Layer
- Library Utilities
- Component Architecture
- Mock Personas
AfterCare simulates a complete post-surgical monitoring platform with three distinct portals:
| Portal | Audience | URL Prefix | Theme |
|---|---|---|---|
| Patient App | Recovering patients & caregivers | /app |
White + Blue |
| Surgeon Portal | Surgeons & care teams | /portal |
Dark Navy |
| Admin Console | Practice administrators | /admin |
Slate 900 |
The landing page at / serves as the product marketing page with role-based entry points.
Core capabilities:
- Daily check-in flow with pain scoring, symptom logging, and CAM-ICU delirium screening
- Wound photo upload simulation with AI-powered analysis (deterministic, not a real model)
- Medication tracking with adherence monitoring and opioid trend analysis
- Mobility and PT exercise logging with step tracking
- Secure messaging between patients and care teams with automated triage labeling
- Recovery guide with procedure-specific milestones and warning signs
- Surgeon patient panel with real-time triage color sorting (Red / Amber / Green)
- Analytics dashboard with cohort metrics and population-level trend charts
- Configurable alert thresholds per metric
- EHR integration status display (Epic, Cerner, Meditech, Allscripts — mock FHIR R4)
- HIPAA-grade audit log viewer with user/action/resource/IP tracking
- ML model registry with status, accuracy, and feature listings
- Patient onboarding workflow simulation
| Layer | Technology | Version |
|---|---|---|
| Framework | Next.js (App Router) | 16.2.1 |
| Language | TypeScript | ^5 |
| Styling | Tailwind CSS v4 | ^4 |
| Charts | Recharts | ^3.8.0 |
| Icons | lucide-react | ^0.577.0 |
| Class merging | clsx + tailwind-merge | ^2.1.1 / ^3.5.0 |
| Date utilities | date-fns | ^4.1.0 |
| Runtime | React 19 | 19.2.4 |
No backend. All state is client-side; data is imported from static TypeScript modules.
# Install dependencies
npm install
# Start development server
npm run dev
# Build for production
npm run build
# Start production server
npm startOpen http://localhost:3000 to see the landing page.
Note: next.config.ts sets typescript.ignoreBuildErrors: true to suppress a false-positive type error in Next.js 16's generated .next/types/app/page.ts file. All application code is fully typed.
/ Landing page — product marketing + role entry points
├── /app Patient-facing application
│ ├── /app Patient dashboard (default patient: Margaret Chen)
│ ├── /app/checkin Multi-step daily check-in flow
│ ├── /app/pain Pain history with trend charts
│ ├── /app/symptoms Symptom log with severity tracking
│ ├── /app/wounds Wound photo upload + AI analysis results
│ ├── /app/medications Medication list, schedule, and adherence gauge
│ ├── /app/mobility PT exercises, step tracking, mobility chart
│ ├── /app/messages Patient ↔ care team messaging
│ ├── /app/guide Procedure-specific recovery guide by day range
│ └── /app/settings Patient profile and notification preferences
│
├── /portal Surgeon-facing portal
│ ├── /portal Patient panel with triage color sorting
│ ├── /portal/patients/[id] Individual patient deep-dive
│ ├── /portal/wounds Wound review queue across all patients
│ ├── /portal/messages Surgeon messaging inbox with triage labels
│ └── /portal/analytics Cohort analytics and outcome trend charts
│ └── /portal/alerts Alert threshold configuration
│
└── /admin Practice admin console
├── /admin System overview with key metrics
├── /admin/ehr EHR integration status (Epic, Cerner, etc.)
├── /admin/onboarding Patient onboarding workflow
├── /admin/audit HIPAA audit log with filters
└── /admin/models ML model registry and status
AfterCare/
│
├── app/ Next.js App Router root
│ ├── layout.tsx Root layout — fonts (Playfair Display + Source Sans 3), metadata
│ ├── page.tsx Landing page (/)
│ ├── globals.css Global styles, Tailwind @theme, custom CSS variables
│ │
│ ├── app/ Patient app segment
│ │ ├── layout.tsx Patient layout — mounts PatientNav, sets left padding for sidebar
│ │ ├── page.tsx Patient dashboard
│ │ ├── checkin/page.tsx Multi-step daily check-in
│ │ ├── pain/page.tsx Pain history and trend charts
│ │ ├── symptoms/page.tsx Symptom log and history
│ │ ├── wounds/page.tsx Wound photo upload and AI analysis
│ │ ├── medications/page.tsx Medication tracker and adherence gauge
│ │ ├── mobility/page.tsx PT exercises and step chart
│ │ ├── messages/page.tsx Patient messaging interface
│ │ ├── guide/page.tsx Recovery guide by procedure and day
│ │ └── settings/page.tsx Patient settings and profile
│ │
│ ├── portal/ Surgeon portal segment
│ │ ├── layout.tsx Portal layout — mounts PortalNav
│ │ ├── page.tsx Patient panel with triage sorting
│ │ ├── patients/[id]/page.tsx Dynamic patient detail page
│ │ ├── wounds/page.tsx Wound review queue
│ │ ├── messages/page.tsx Surgeon messaging inbox
│ │ ├── analytics/page.tsx Cohort analytics dashboard
│ │ └── alerts/page.tsx Alert threshold configuration
│ │
│ └── admin/ Admin console segment
│ ├── layout.tsx Admin layout — mounts AdminNav
│ ├── page.tsx System overview
│ ├── ehr/page.tsx EHR integration management
│ ├── onboarding/page.tsx Patient onboarding workflow
│ ├── audit/page.tsx Audit log viewer
│ └── models/page.tsx ML model registry
│
├── components/
│ ├── ui/
│ │ └── index.tsx Shared UI primitives (see Component Architecture)
│ ├── navigation/
│ │ ├── PatientNav.tsx Patient sidebar + top bar (blue/white)
│ │ ├── PortalNav.tsx Surgeon sidebar + top bar (dark navy)
│ │ └── AdminNav.tsx Admin sidebar + top bar (slate-900)
│ └── charts/
│ ├── PainTrendChart.tsx AreaChart + sparkline for pain scores
│ ├── OpioidChart.tsx BarChart for daily opioid doses
│ ├── MobilityChart.tsx AreaChart for daily step counts
│ └── AdherenceChart.tsx RadialBarChart gauge + PieChart breakdown
│
├── data/
│ ├── mockPatients.ts 6 seeded patients with full clinical profiles
│ ├── fakeData.ts Pain entries, symptoms, CAM assessments, wound photos,
│ │ medication logs, and mobility data (200+ records)
│ ├── mockMessages.ts 6 message threads, 30 messages total
│ ├── mockAlerts.ts 17 clinical alerts across all patients
│ └── mockBenchmarks.ts Recovery benchmarks (105 records) + cohort metrics
│
├── lib/
│ ├── helpers.ts Formatting, color mapping, and utility functions
│ ├── triage.ts Clinical triage and risk scoring logic
│ └── fakeAI.ts Deterministic AI response engine + wound analysis + recovery guide
│
├── types/
│ └── index.ts All TypeScript interfaces and type aliases
│
├── next.config.ts Next.js config (ignoreBuildErrors: true)
├── tailwind.config.ts (Tailwind v4 — config lives in globals.css @theme)
├── tsconfig.json TypeScript config
└── package.json
The product marketing page. Features:
- Hero section with animated headline and dual CTA buttons
- Feature cards with staggered vertical offset (3-column grid on desktop)
- Role-based entry point cards: Patient App, Surgeon Portal, Admin Console
- Paper grain texture overlay on hero background
- Procedure type chips (knee, hip, spine, appendectomy, cholecystectomy, colectomy)
All patient pages share the PatientNav layout: sticky top bar + left sidebar (desktop) or drawer (mobile).
- Recovery progress header: Day post-op, triage color badge, procedure label
- Today's summary cards: pain score, steps, medication adherence
- Active alerts banner with severity color coding
- Pain trend sparkline (last 7 days)
- Next scheduled medications widget
- Quick action links to each section
Multi-step wizard:
- Pain — 0–10 slider with color feedback, location and character selectors
- Symptoms — Multi-select symptom checklist with severity rating
- CAM-ICU — 4-criterion delirium screening (acute onset, inattention, disorganized thinking, altered consciousness)
- Wound — Photo upload simulation with instant AI analysis result card
- Medications — Mark each scheduled medication as taken or skipped
- Mobility — PT exercise completion checkboxes + steps entry
- Summary — Confirmation screen with submission toast
- Current pain score card with color-coded label
- Area chart of pain scores over all post-op days
- Benchmark overlay showing expected pain range for the patient's procedure
- Pain entry history table with timestamp, location, and character columns
- Symptom frequency bar chart
- Severity distribution pills
- Chronological symptom entry history with expandable notes
- Wound photo gallery with day-by-day thumbnails
- AI analysis result for each photo: redness, drainage, dehiscence, swelling, risk level
- Healing trajectory status card
- Upload new photo button (simulated)
- Active medication cards with dosage, frequency, route, and instructions
- Today's schedule: taken / skipped / due / overdue status per dose
- Adherence gauge (RadialBarChart) — overall compliance percentage
- Medication category breakdown (PieChart): opioid vs NSAID vs antibiotic, etc.
- Opioid usage trend BarChart
- Daily step count AreaChart
- PT exercise checklist with sets/reps/completion state
- Assistance level tracker (independent → dependent scale)
- Walking distance log
- Thread list with unread count badges and triage color labels
- Message thread view with sender role badges
- Compose new message form with subject and body
- Real-time-style message display (timestamps, read receipts)
- Procedure-specific milestone cards organized by day ranges (e.g., Days 1–3, Days 4–7, Days 8–14)
- Each card covers: pain expectations, mobility targets, wound care, medications, warning signs, when to call doctor
- Current day highlighted
- Patient profile display (name, MRN, DOB, procedure, surgeon)
- Notification preferences toggles
- Emergency contact information
- Account details
All portal pages share the PortalNav layout: dark navy sidebar + header with Dr. Sarah Chen profile.
- Triage-sorted patient list (Red → Amber → Green)
- Each patient card shows: name, procedure, day post-op, triage badge, active alert count, last check-in time
- Filter by triage color, procedure type, or alert status
- Click-through to individual patient detail
Dynamic route for each of the 6 seeded patients. Sections:
- Patient header: name, MRN, procedure, surgeon, day post-op, triage color
- Alert timeline: all active alerts with severity and action required
- Pain trend chart with benchmark overlay
- CAM assessment history table
- Wound photo review with AI analysis results
- Medication adherence summary
- Mobility progress
- Message thread with patient
- All recent wound photos across all patients sorted by risk level
- Each entry shows patient name, day post-op, AI risk level badge, and key findings
- Filter by risk level (critical / high / moderate / low)
- Bulk acknowledge workflow
- Full message thread list with patient name, triage label, unread count
- Thread view with full message history
- Compose reply or new message
- Auto-triage label assignment based on message content
- Cohort overview metrics: avg days to discharge, readmission rate, opioid duration, satisfaction score
- Population pain trend chart (all patients overlaid)
- Procedure comparison BarChart
- Compliance rate trend over time
- Risk distribution PieChart
- List of all configurable alert thresholds (pain score, step count, CAM positive, etc.)
- Each threshold: metric name, operator (>, <, >=, <=, =), value, severity level, enabled toggle
- Add / edit / delete threshold forms
All admin pages share the AdminNav layout: slate-900 sidebar + header with Jordan Reed (Practice Admin) profile.
- System health metrics: total patients, active alerts, EHR sync status, model accuracy
- Recent activity feed
- Quick links to all admin sections
- Connection cards for Epic, Cerner, Meditech, Allscripts
- Each card shows: status badge (connected / syncing / error / disconnected), last sync time, patients imported, FHIR version, endpoint URL
- Sync now and disconnect actions (simulated)
- Multi-step onboarding wizard for adding new patients
- Steps: patient demographics → procedure details → care team assignment → EHR import → portal access setup
- Confirmation screen with generated credentials
- Paginated table of all system events
- Columns: timestamp, user, role, action, resource, resource ID, IP address, status (success / failure / warning)
- Filter by user, role, action type, date range, and status
- Export to CSV (simulated)
- Cards for each ML model (wound risk classifier, pain trajectory predictor, readmission risk, delirium screener)
- Each card: name, version, status (active / training / staged / deprecated), last trained date, accuracy score, feature list
- Promote / deprecate / retrain actions (simulated)
| Function | Description |
|---|---|
cn(...classes) |
Merge class names with clsx + tailwind-merge |
formatDate(dateStr) |
Human-readable date string |
getDaysSinceDate(dateStr) |
Days elapsed since a given date |
formatTime(dateStr) |
HH:MM AM/PM |
getPainColor(score) |
Tailwind color class based on pain score (0–10) |
getPainLabel(score) |
"None" / "Mild" / "Moderate" / "Severe" / "Extreme" |
getTriageColor(triage) |
Hex color for Red / Amber / Green triage |
getSeverityColor(severity) |
Color class for alert severity levels |
formatProcedureName(type) |
"knee_replacement" → "Knee Replacement" |
getRecoveryPercentage(day, total) |
Progress 0–100 given day and estimated total recovery days |
truncateText(text, len) |
Ellipsis truncation |
generateId() |
Random string ID for new records |
| Function | Description |
|---|---|
calculateTriageColor(patient, painEntries, alerts) |
Derives Red/Amber/Green from recent data |
assessPainTrend(entries) |
"improving" / "stable" / "worsening" based on slope |
isCAMPositive(assessments) |
True if any recent CAM assessment is positive |
calculateAdherenceRate(logs) |
Percentage of medications taken on schedule |
getOpioidUsageTrend(logs, medications) |
Daily opioid dose counts for chart |
assessWoundRisk(photos) |
Most recent wound risk level |
generateRiskScore(patient, ...) |
Composite 0–100 risk score |
getAIResponse(input: string): AIResponse
Keyword-matching response engine covering 14 clinical categories:
- Pain management, wound care, medications, fever, swelling, mobility, diet, bleeding, infection signs, delirium, when to call 911, discharge criteria, opioid safety, and general recovery
Every response includes a medical disclaimer. Severity is tagged as info, warning, or urgent.
generateWoundAnalysis(patientId, dayPostOp): WoundAnalysis
Deterministic wound analysis seeded from patientId + dayPostOp. Returns redness, drainage, dehiscence, swelling, risk level, findings array, healing stage, and recommendation — consistent across renders.
recoveryGuide: Record<ProcedureType, RecoveryGuideEntry[]>
5 entries per procedure type, each covering a day range with expected pain, mobility targets, wound guidance, medication notes, warning signs, and doctor call criteria.
Shared primitive components used across all three portals:
| Component | Description |
|---|---|
Button |
Variants: primary, secondary, ghost, danger. Always rounded-full. |
Card |
Container with rounded-3xl, border, shadow. |
CardHeader / CardTitle / CardContent |
Card sub-components. CardTitle uses font-serif. |
Badge |
Inline label with color variants. |
StatCard |
Metric display card. Value rendered in font-serif. |
AlertBanner |
Colored alert with icon and dismiss. |
Input / Textarea / Select |
Form controls with rounded-xl, consistent focus ring. |
Spinner |
Loading indicator. |
Modal / ModalHeader / ModalBody / ModalFooter |
Full-screen overlay with backdrop blur. |
Toast |
Temporary notification with severity coloring. |
Tabs / TabList / Tab / TabPanel |
Accessible tab interface. |
ProgressBar |
Horizontal progress with color variants. |
Skeleton |
Loading placeholder shimmer. |
All charts use Recharts with custom tooltips styled to match the design system (rounded-2xl, subtle shadow).
| Component | Chart Type | Usage |
|---|---|---|
PainTrendChart |
AreaChart | Pain history with benchmark shading |
PainSparkline |
AreaChart (mini) | Compact 7-day pain spark on dashboard |
OpioidChart |
BarChart | Daily opioid doses over time |
StepsChart |
AreaChart | Daily step count with gradient fill |
AdherenceGauge |
RadialBarChart | Medication adherence % as arc gauge |
MedicationBreakdown |
PieChart | Dose count by medication category |
| Component | Portal | Style | Features |
|---|---|---|---|
PatientNav |
Patient App | White + Blue | Mobile drawer, sticky top bar, +Daily Check-In CTA button |
PortalNav |
Surgeon Portal | Slate-900 | Mobile drawer, notification bell with badge, doctor profile |
AdminNav |
Admin Console | Slate-900 | No mobile drawer, admin profile, violet accent |
All nav components use usePathname() from Next.js for active link detection.
The app ships with three hardcoded user personas visible in the navigation:
| Persona | Portal | Role | Avatar Initials |
|---|---|---|---|
| Margaret Chen | Patient App | Patient (Knee Replacement, Day 4) | MC |
| Dr. Sarah Chen | Surgeon Portal | Orthopedic Surgeon | SC |
| Jordan Reed | Admin Console | Practice Admin | JR |