Atenvia — Master Product Requirements Document
Version: 1.0 · Status: Living · Last updated: 2026-06-16 · Owner: TAS Team
⚠️ CRITICAL CONTEXT — READ FIRST
The current build is a 100% mock-data prototype. There is NO backend.
- All patient, clinical, user, and audit data is hard-coded in
src/data/mockData.ts— there is no API, no database, no server.- There is no real authentication (only a demo password gate) and no real authorisation (role gating is visual-only).
- Nothing persists — every change resets on page refresh.
- A backend / persistence layer has yet to be implemented and is the gating prerequisite for the RBAC work (§4). It must be designed and built before real auth, role enforcement, or patient scoping can exist.
- The backend must also include a dedicated ETL / data-handler service (§5.3) to ingest and process device data from the four vendor clouds (CloudPAT, NeXus360, PrismaCloud, AirView). This too is not yet built — real device data cannot flow in without it.
Read every "planned" capability in this document against that baseline: the clinical app is real and demoable today; everything requiring a server is design-only until the backend exists.
This is the consolidated master PRD for Atenvia. It merges the product overview, the shipped-feature catalogue, and the two forward-looking feature PRDs (Admin Dashboard and RBAC) into one document. The four source documents remain in place as the canonical, granular references; this master keeps them in sync and gives a single front door.
How to read this document (layered structure)
This PRD is written in two layers so it serves both audiences from one file:
- Part I — Product Narrative (§1–§8): plain-language, for product owners, clinical stakeholders, and management. No TypeScript, no Gherkin. Read this to understand what Atenvia is, what exists today, and what is planned.
- Part II — Technical Specifications (Appendices A–E): full engineering detail — data models, acceptance criteria (Gherkin), capability matrices, NFRs, and code references. Read this to build or review the work.
| If you are… | Read |
|---|---|
| A clinical / commercial stakeholder | Part I (§1–§8) |
| A product manager | Part I, then skim appendices |
| An engineer / reviewer | Part I §1, then the relevant appendix in full |
Source documents consolidated here
| Source PRD | Covers | Status | Detailed in |
|---|---|---|---|
overview.md |
Product summary | Shipped (prototype) | §1 |
features/FEATURES.md |
Shipped clinical app | Shipped, v01.x | §2 · Appendix A |
features/admin-dashboard/admin-dashboard.md |
Admin Dashboard | Draft (built, gated off) | §3 · Appendix B |
features/rbac/atenvia-rbac.md |
RBAC & patient scoping | Draft (not built) | §4 · Appendix C |
Status of the platform at a glance
| Capability area | State |
|---|---|
| Clinical dashboard, patient detail, alerts, search, PDF | ✅ Shipped (mock-data prototype) |
| Admin Dashboard (six panels) | 🟡 Built in src/app/components/admin/, mount
commented out in App.tsx pending RBAC |
| Authentication & real RBAC | 🔵 Planned — designed in §4 / Appendix C, not yet implemented (blocked on backend) |
| Backend / persistence | ⛔ NOT IMPLEMENTED — no API, no database, no
server. Hard prerequisite for auth, RBAC, and persistence. Today
everything is in-memory mock data
(src/data/mockData.ts). |
Note on prior docs:
FEATURES.mdlists "User Authentication" and "Role-based Access" under NOT Included in Current Build. That remains true of the shipped build, but both are now planned and specified here (§4). Treat the "NOT Included" list as "not in the current build" — not "never".
Part I — Product Narrative
1. Product Overview
What is Atenvia?
Atenvia is a sleep-therapy patient-management dashboard for healthcare clinicians. It gives sleep clinics a single place to monitor CPAP/PAP therapy patients across their treatment journey, surface the patients who need attention, and produce shareable clinical reports.
Today it is a single-page React prototype running entirely on mock data (no backend, no real authentication, no persistence). It is used for stakeholder demonstrations and as the reference implementation of the Atenvia Design System.
Core capabilities (shipped)
- KPI Dashboard — active patients, compliance rates, critical-alert summary, stage distribution.
- Patient Pipeline — the five-stage journey: Screening → Diagnose → Trial → Adoption → Compliance.
- Patient Detail — demographics, CPAP compliance, sleep-position reports, threaded clinical notes.
- Priority Alerts — critical / warning / info alerts driven by a compliance rules engine.
- Global Search — fuzzy search across patient names, IDs, device serials, and CPAP models.
- PDF Export — CPAP compliance reports and sleep-position reports.
Target users
Today: sleep-clinic staff (clinicians, therapists, clinical managers) managing CPAP/PAP patients. The planned RBAC work (§4) formally extends this to external referring doctors/clinicians, TAS internal operations staff, and TAS administrators, each with a different view of the data.
Where the product is heading
Two forward-looking initiatives turn the prototype into a governable, multi-tenant platform:
- Admin Dashboard (§3) — an administrative surface for managing users, auditing activity, monitoring system health, configuring alert thresholds, managing hospitals, and toggling feature flags.
- RBAC & Patient Scoping (§4) — real authentication and role-based access control with four organisation-aligned tiers, plus row-level patient scoping so each user sees only the patients they are entitled to.
These are sequential: the Admin Dashboard is already built but is switched off until RBAC exists to gate it properly.
2. Current State — Shipped Clinical App
This section summarises what exists in the build today. Full
per-feature functionality is catalogued in Appendix A
(and exhaustively in features/FEATURES.md).
2.1 Dashboard & monitoring
- KPI metrics — total active patients, stage distribution, critical-alert count, average compliance.
- Therapy-efficacy charts — usage trends, AHI progress, compliance rate, over selectable date ranges.
- Priority alerts listing — severity-sorted alerts (critical/warning/info) with acknowledge / assign / resolve actions.
2.2 Patient management
- Patient list & global search — fuzzy search (Fuse.js) across names, IDs, serials, models; stage and hospital filters; keyboard navigation.
- Patient detail (tabbed) — Patient Card (always visible), Sleep Report (from Diagnose), CPAP Report (from Trial, CPAP only), Clinical Notes (from Diagnose). Tabs appear only when clinically appropriate.
2.3 Clinical data surfaces
- CPAP Report tab — dual view (checkpoint-based Trial view; daily Compliance view), usage/AHI/leak metrics, device info, compliance thresholds (green ≥4h, amber 2–4h, red <2h).
- Sleep Report tab — position distribution + timeline, sleep efficiency, recommended position, clinical insights.
- Clinical Notes tab — threaded notes, @mentions, #hashtags, file attachments with zoom/pan preview, user assignment, search/filter.
2.4 Notifications & alerts
- Notification sheet — four categories (Critical
Clinical, Workflow/Process, System & Integrity, Passive Toast),
search, read/unread,
Cmd/Ctrl+Jto open. - Alert action menus & severity icons — dropdown actions, colour-coded severity with tooltips.
2.5 Reporting
- CPAP compliance PDF and Sleep report
PDF — branded, A4, charts embedded via html2canvas. Two
pipelines coexist (
pdfmakefor tabular,@react-pdf/rendererfor visual).
2.6 Platform / UX foundations
- Design-system compliance — CSS variables only; Inter (body) + Manrope (headings); no Tailwind text classes on semantic headings.
- Responsive layout, dark mode, keyboard navigation, loading skeletons.
- Compliance rules engine & KPI calculations — centralised thresholds and pure aggregation functions.
2.7 Explicitly NOT in the shipped build
Real-time sync · authentication · role-based access · report scheduling · native mobile app · external API integration · multi-language · backend database · data persistence (state resets on refresh).
Authentication and role-based access are specified as planned work in §4. The rest remain out of scope.
3. Planned — Admin Dashboard
Full specification: Appendix B and
features/admin-dashboard/admin-dashboard.md.
3.1 What & why
The Admin Dashboard adds a protected administrative section to Atenvia, giving administrators one place to manage clinician and patient accounts, review platform activity via an audit trail, monitor system health, configure clinical alert thresholds, manage hospital affiliations, and toggle prototype features. It lets stakeholders demonstrate the platform's governance and operational surface alongside the clinician-facing dashboard.
3.2 The six panels
| Panel | What it does |
|---|---|
| User Management | Invite / deactivate / edit clinicians and patients; assign hospitals; search & filter |
| Audit Trail | Timestamped log of every admin/clinical action; filter by user, action, date |
| System Health | PrismaCloud sync status, ETL run history, freshness badges |
| Notification Configuration | Per-hospital and global AHI / leak / compliance thresholds |
| Hospital / Org Management | Add/edit hospitals, assign clinicians, view patient counts |
| Feature Flags | Toggle GA4, Clarity, and experimental features at runtime |
3.3 Current build status
The module is already built under
src/app/components/admin/ (verified:
AdminDashboard.tsx + panels/). Its mount and
import in App.tsx are commented out (lines
33 and 5398) so the clinician-facing build ships without the admin
surface. It will be re-enabled behind the RBAC TAS-Admin tier (§4).
3.4 Important scope notes
- Prototype only — no real auth, no persistence; all mutations are in-memory and reset on reload. A persistent banner states "Prototype: changes do not persist".
- Role gating is visual-only in this phase
(
userRole: 'admin' | 'clinician' | 'readonly'). Real enforcement comes with RBAC (§4). - Audit log export was originally deferred to v2, but
auditExport.tsnow exists in the panels directory. ⚠️ Open reconciliation item — confirm whether export shipped or is scaffolding (see §7 Open Items).
4. Planned — RBAC & Patient Data Scoping
Full specification: Appendix C and
features/rbac/atenvia-rbac.md.
4.1 What & why
Atenvia today has no real authorisation: the admin surface is gated by a visual-only string prop, there is no authentication beyond a demo password gate, and every signed-in viewer can see every patient. That is fine for a prototype but unacceptable once real clinicians, TAS staff, and patient data are involved — it violates least-privilege and (for PHI) HIPAA-style minimum-necessary access.
RBAC introduces real role-based access control with four organisation-aligned tiers and row-level patient scoping, enforced server-side as defence-in-depth (gating both navigation and the underlying data), replacing the UI-hiding approach.
4.2 The four access tiers
| Tier | Who | Surface | Patient visibility |
|---|---|---|---|
| External Clinical | Referring doctors & clinicians (private/gov hospitals) | Clinical app | Only their own patients referred to TAS |
| TAS Internal Ops ("Sleep Tech") | TAS team: CS, CAS, Sales Execs, Sales Manager | Clinical app | All patients, all source groups |
| TAS Admin | TAS admin function (currently performed by Super Admin) | Admin Panel (six panels) | Manages users & ops; no patient-care browsing |
| Super Admin | IT / Digital Transformation + Digital Product | Super Admin surface | Platform governance; also performs TAS Admin for now |
Key clarifications:
- The Admin Panel is the TAS administrative tool, not the clinicians' — it manages external clinicians and TAS internal staff.
- "Sleep Tech" is the TAS internal ops team, not a clinical role.
- Super Admin is strictly the highest tier — the only party that can manage TAS admins and platform governance. Until dedicated TAS admins are appointed, Super Admin also fulfils the TAS Admin function.
4.3 Patient source groups (drives scoping)
Every patient record originates from one of three groups:
- Private hospital / clinic referral
(
private_referral) - Government / restructured hospital referral
(
gov_referral) - TAS direct — walk-in or onboarded via the TAS
website (
tas_direct)
External clinicians see only their own referred patients (groups 1–2 where they are the assigned clinician). TAS Internal Ops see all three groups in full.
4.4 The non-negotiable principle
Enforce on the server, deny by default. The client UI is a convenience layer only, never the enforcement point. Out-of-scope access by direct ID/URL/API is denied server-side and written to the audit trail.
4.5 Prerequisites
RBAC is the heaviest initiative because it requires foundations the prototype lacks:
- Real authentication & session management (recommended: Firebase Auth, given existing Firebase Hosting).
- A persistence layer for users, roles, and audit
events (today: mock
mockData.ts). - An ADR choosing the auth provider and where RBAC claims live.
- Patient data-model migration — add
sourceGroup,referredToTAS,assignedClinicianId.
5. Planned — External System Integrations
Status: 🔵 All pending — none implemented.
Atenvia must integrate with external systems for both its
clinical/device data and its patient-workflow
data. None exist today; all data is synthetic
(generate*.ts + mockData.ts).
Two integration classes:
- A. Device vendor clouds (§5.1–§5.6) — four manufacturer clouds supplying CPAP and HST telemetry, ingested via the backend ETL / data handler.
- B. ZohoCRM (§5.7) — TAS's system of record for patient stages and demographics, synced into Atenvia via webhook or API.
5.1 Device vendor clouds — why this matters
Atenvia's clinical value depends entirely on device telemetry — CPAP usage, AHI, leak rate, and home-sleep-test results. That data lives in manufacturer vendor clouds, not in Atenvia. Each vendor exposes its own cloud API, and Atenvia must ingest, normalise, and map that data to the right patient. Four integrations are planned across two device categories. Each is a separate vendor-cloud API integration with its own auth, schema, and sync cadence.
5.2 The four vendor cloud integrations
| Device category | Vendor cloud | Device(s) | Manufacturer | Status |
|---|---|---|---|---|
| Home Sleep Test (HST) | CloudPAT | WatchPAT | Itamar Medical (ZOLL) | 🔵 Pending |
| Home Sleep Test (HST) | NeXus360 | SomFit | Compumedics | 🔵 Pending |
| CPAP / PAP therapy | PrismaCloud | prisma series | Löwenstein Medical | 🔵 Pending |
| CPAP / PAP therapy | AirView | AirSense / AirCurve | ResMed | 🔵 Pending |
CPAP pairings (PrismaCloud→Löwenstein, AirView→ResMed) and the SomFit→Compumedics mapping were specified/corrected by the product owner. The WatchPAT→Itamar/ZOLL attribution is the best-known mapping — confirm during integration scoping.
5.3 Required backend component — ETL / Data Handler
⛔ Not yet built. Beyond the database and auth, the backend must include a dedicated ETL / data-handler service responsible for processing incoming data from each vendor cloud. This is a distinct component — it is the engine that pulls, transforms, normalises, de-duplicates, and persists device telemetry from CloudPAT, NeXus360, PrismaCloud, and AirView into Atenvia's common data model. Without it, no real device data can enter the system regardless of whether auth and the database exist.
Responsibilities of the ETL / data handler:
- Connect to each vendor cloud API (per-vendor credentials, rate limits, pagination).
- Extract new/changed records per scheduled run (or via webhook where the vendor supports push).
- Transform vendor-specific payloads → Atenvia's normalised patient / statistic / alarm shape.
- Map device serial → patient (resolving the serial→patient registry).
- Load into the persistence layer idempotently (safe re-runs, no duplicate ingestion).
- Record each run's outcome (records processed, duration, errors) for the System Health panel.
- Handle failure — partial syncs, vendor outages, schema drift — without corrupting prior data.
It is the gating piece between "vendor cloud has the data" and
"Atenvia can show it." The existing scripts/prismacloud/
work is the seed of this layer but covers only one of the four
vendors.
5.4 What each integration must do
For every vendor cloud, the ETL / data-handler layer (backend, once built) must:
- Authenticate to the vendor API (per-vendor credentials / OAuth — out of scope until backend exists).
- Pull new device records on a schedule (ETL run) — sleep studies (HST) or therapy/compliance data (CPAP).
- Normalise vendor-specific payloads into Atenvia's common patient/statistic/alarm shape.
- Map device → patient via device serial number (already a first-class search field in the shipped app).
- Surface sync health in the Admin Dashboard's System Health panel (§3.2 / Appendix B) — per-vendor last-sync time, records ingested, and Healthy/Degraded/Failed status.
5.5 Impact on existing specs
- System Health panel (Appendix B) currently models a
single
prismacloudsync source. It must generalise to one sync record per vendor cloud (CloudPAT, NeXus360, PrismaCloud, AirView), each with its own ETL run history and status badge. - Patient source groups (§4.3, RBAC) describe referral origin and are independent of device vendor. A patient referred privately could use a ResMed CPAP and an Itamar HST; vendor cloud ≠ source group. Keep the two axes separate in the data model.
- Clinical data tabs (CPAP Report, Sleep Report)
consume this ingested data; today they read from
generate*.ts. The ingestion layer replaces the generators as the data source once live.
5.6 Open scoping questions
- Per-vendor sync cadence (real-time webhook vs. scheduled poll)?
- Common normalised schema — reuse/extend
scripts/prismacloud/types.tsas the canonical shape, or define a vendor-neutral model first? - Device→patient mapping authority — does the vendor cloud hold the patient link, or does Atenvia/TAS own the serial→patient registry?
- Which integration is built first (likely the one with the largest installed device base)?
5.7 ZohoCRM — patient-stage & demographics sync
Status: 🔵 Pending. ZohoCRM is already the conceptual
system of record — the shipped Patient Card tab is
documented as a "read-only data twin of Zoho CRM" — but no live sync
exists; patient data is hard-coded in mockData.ts.
Purpose: Keep Atenvia's patient pipeline in step with ZohoCRM, which TAS uses to manage the patient relationship. The primary synced entity is patient stage (Screening → Diagnose → Trial → Adoption → Compliance) so the dashboard, KPIs, and pipeline reflect the CRM's current state.
Mechanism — TBD (webhook vs. API):
- Webhook (push) — ZohoCRM fires on a stage/field change; Atenvia's backend applies it in near-real-time. Preferred for freshness.
- API (poll) — Atenvia's backend periodically pulls changed records from the Zoho CRM API. Simpler, higher latency.
- Choice depends on Zoho webhook reliability and the acceptable staleness window — settled in the integration ADR.
Synced data fields — TBD: Patient
stage is confirmed in scope. The full set of
additional fields to sync (demographics, referral info,
assigned clinician, contact details, comorbidities) is not yet
defined. This overlaps with RBAC:
assignedClinicianId and referral origin (→
sourceGroup, §4.3) may originate from Zoho, so field
mapping should be agreed alongside the RBAC data model (§4).
Direction: Initial assumption is Zoho → Atenvia (inbound) for stages/demographics. Whether Atenvia writes anything back to Zoho (compliance status, alerts) is out of scope until defined.
Flows through the backend data handler (§5.3): like the device clouds, CRM sync is processed by the backend's ETL / data-handler layer (receive → normalise → map → persist), never by the client.
Open questions:
- Webhook vs. poll (above).
- Exact field set and the authoritative direction per field.
- Shared patient identity key between Zoho and Atenvia (CRM record ID ↔︎ patient ID).
- Conflict resolution if a field is editable in both systems.
6. Consolidated Roadmap
| Phase | Initiative | Depends on | State |
|---|---|---|---|
| Shipped | Clinical app (dashboard, patients, alerts, search, PDF) | — | ✅ Live (prototype) |
| Phase 1 | Admin Dashboard — six panels, mock data, visual role gating | — | 🟡 Built, gated off |
| Phase 2 | Admin enhancements — audit export (CSV/PDF), bulk invite, per-user flags, virtualised tables, threshold preview | Phase 1 | 🔵 Planned |
| Phase 3 | RBAC & patient scoping — real auth, four tiers, row-level scoping, re-home Admin Panel, Super Admin surface | Backend + auth ADR | 🔵 Planned |
| Phase 3 (parallel) | External integrations — device clouds (CloudPAT, NeXus360, PrismaCloud, AirView) + ZohoCRM patient-stage sync → System Health monitoring | Backend + ETL | 🔵 Planned (§5) |
| Phase 3+ | Dedicated TAS admins, MFA, SSO / hospital federation, care-team multi-owner ownership | Phase 3 | 🔵 Future |
| Security & compliance | Engage CyberSafe + secure grant (now) → penetration testing (after RBAC live) → HIPAA & SOC 2 audits | RBAC live for pen-test/audits | 🔵 Cross-cutting — see roadmap |
Critical path: backend (no server today) → in parallel: (a) auth + RBAC → re-enable the (already built) Admin Dashboard behind the TAS-Admin tier; (b) vendor cloud ingestion → real device data replacing the mock generators. Everything non-clinical-UI is blocked on the backend.
7. Open Items & Cross-Document Reconciliation
These are unresolved points surfaced when consolidating the four source docs:
- Audit export status — Admin PRD §1 lists audit
export as out-of-scope (v2), but
src/app/components/admin/panels/auditExport.tsexists. Confirm whether it shipped or is scaffolding; update scope accordingly. - Version drift across source docs — overview (v01.2.0), FEATURES (v01.1.5), admin & RBAC (1.0). This master is the single dated reference (2026-06-16); align the others or let this supersede their headers.
- Persistence / auth provider (RBAC) — Firebase Auth + Firestore vs. dedicated API backend. To be settled in an ADR before any RBAC implementation.
- Existence-leak rule (RBAC) — out-of-scope direct
patient access returns
403(with audit) vs404. Decision documented as403; confirm and apply consistently. - TAS Admin appointment — when dedicated TAS admins are appointed, confirm the exact split of capabilities retained by Super Admin.
- Ownership granularity (RBAC) — single
assignedClinicianIdnow; care-team / multi-owner deferred. Confirm deferral is acceptable for Phase 1.
8. Glossary
| Term | Meaning |
|---|---|
| AHI | Apnea-Hypopnea Index — apnea events per hour; primary therapy-efficacy metric |
| CPAP / PAP / BIPAP / APAP | Positive-airway-pressure therapy device types |
| OSA | Obstructive Sleep Apnea |
| ESS | Epworth Sleepiness Scale |
| Compliance | Meeting usage thresholds (≥4h/night target; ≥70% of nights with ≥4h) |
| PHI | Protected Health Information |
| RBAC | Role-Based Access Control |
| TAS | The administering organisation operating Atenvia |
| Sleep Tech | The TAS internal-ops team (CS, CAS, Sales Execs, Sales Manager) |
| Source group | A patient's origin: private referral / gov referral / TAS-direct |
| Home Sleep Test (HST) | At-home diagnostic sleep study (vs. in-lab polysomnography) |
| WatchPAT | Itamar Medical (ZOLL) HST device; data via CloudPAT |
| SomFit | Compumedics HST device; data via NeXus360 |
| CloudPAT | Itamar/ZOLL vendor cloud for WatchPAT HST data |
| NeXus360 | Compumedics vendor cloud for SomFit HST data |
| PrismaCloud | Löwenstein Medical vendor cloud for prisma-series CPAP data |
| AirView | ResMed vendor cloud for AirSense/AirCurve CPAP data |
| Löwenstein / ResMed | CPAP device manufacturers feeding PrismaCloud / AirView respectively |
| ETL / Data Handler | Backend service that Extracts, Transforms, and Loads vendor-cloud device data into Atenvia (§5.3) — not yet built |
| ZohoCRM | TAS's CRM; system of record for patient stages & demographics, synced into Atenvia via webhook/API (§5.7) |
| ADR | Architecture Decision Record |
Part II — Technical Specifications (Appendices)
Engineering detail. Part I above is the readable summary; these appendices carry the full data models, acceptance criteria, capability matrices, NFRs, and code references. Where an appendix would simply restate a source doc verbatim, it inlines the high-value structured artifacts and points to the source for exhaustive UI-level functionality.
Appendix A — Shipped Feature Catalogue (reference)
The complete, per-feature catalogue (descriptions, user stories,
functionality bullets, technical details, related components) lives in
features/FEATURES.md and is the canonical
reference for the shipped build. Summary of feature areas and their
status:
| Feature | Status | Priority | Location |
|---|---|---|---|
| KPI Metrics | ✅ Production | High | App.tsx + utils/kpiCalculations.ts |
| Therapy Efficacy Charts | ✅ Production | High | App.tsx (Recharts) |
| Priority Alerts Listing | ✅ Production | Critical | components/AlertsListing.tsx |
| Patient List & Global Search | ✅ Production | High | App.tsx (Fuse.js) |
| Patient Detail (tabbed) | ✅ Production | High | components/patient/PatientDetail.tsx |
| Patient Card Tab | ✅ Production | High | patient/tabs/PatientCardTab.tsx |
| CPAP Report Tab | ✅ Production | Critical | patient/tabs/CPAPComplianceTab.tsx |
| Sleep Report Tab | ✅ Production | Medium | patient/tabs/SleepReportTab.tsx |
| Clinical Notes Tab | ✅ Production | High | patient/tabs/ClinicalNotesTab.tsx |
| Notification Sheet | ✅ Production | Medium | notifications/NotificationSheet.tsx |
| Alert Action Menus / Severity Icons | ✅ Production | Critical | AlertsListing.tsx,
patient/MetricStatusIcon.tsx |
| Stage / Hospital Filtering | ✅ Production | Medium | App.tsx (inline dropdowns) |
| CPAP / Sleep PDF Export | ✅ Production | Medium | components/pdf/ |
| Design System / Dark Mode / Responsive / Keyboard / Skeletons | ✅ Production | — | styles/, all components |
| Compliance Rules Engine | ✅ Production | High | utils/complianceRules.ts,
therapyThresholds.ts |
| KPI Calculations | ✅ Production | High | utils/kpiCalculations.ts |
| Data Generation | ✅ Production | — | patient/generate*.ts, mockData.ts |
Key clinical thresholds (from the compliance rules engine):
- Compliant ≥4h; partial 2–4h; non-compliant <2h.
- Alert triggers: 3 consecutive days <4h (warning); 5 consecutive days <2h (critical); AHI increase >20% (clinical); leak >24 L/min (equipment).
- Targets: ≥4h/night; ≥70% nights with ≥4h; AHI <5 events/hr; leak <24 L/min.
Appendix B — Admin Dashboard (full technical spec)
Source of truth:
features/admin-dashboard/admin-dashboard.md. The
non-functional requirements, acceptance criteria, data models, and
component tree below are the load-bearing artifacts.
B.1 Non-functional requirements
- Performance: admin first paint <500ms after sidebar click; ≤200-row lists scroll ≥50 FPS; filter response <100ms.
- Security: visual role scoping only (no real auth in
this phase); PHI cells carry
data-clarity-mask="true"; destructive actions gated by mock role. - Accessibility: WCAG 2.1 AA — keyboard-navigable,
<th scope>headers,aria-labelon toggles, focus rings honourvar(--ring). - Scalability: render up to 500 users / 1,000 audit events / 50 hospitals without virtualisation (beyond → v2).
- Consistency: CSS variables only; no hardcoded colour/spacing/typography; no Tailwind text classes on headings.
B.2 Acceptance criteria (Gherkin)
Scenario: Enter the admin dashboard
Given I am viewing the main clinician dashboard
And I have the "Admin" role assigned (mock)
When I click the "Admin" entry in the sidebar
Then the main content area replaces the patient list with the Admin Dashboard
And the active sidebar item is "Admin"
And the URL fragment changes to "#admin" for shareable demo links
Scenario: User Management — invite a clinician
Given I am on the Admin Dashboard, User Management panel, Clinicians tab
When I click "Invite clinician"
And I enter name, email, role "Clinician", hospitals ["RAFFLES","MEH"]
And I click "Send invite"
Then a new clinician row appears with status "Invited"
And a toast reads "Invite sent to <email>"
And an audit event "clinician.invited" is appended
Scenario: User Management — deactivate a clinician
Given clinician "Dr John Lim" has status "Active"
When I select "Deactivate" from the row menu and confirm
Then his status changes to "Deactivated" (reduced opacity + badge)
And an audit event "clinician.deactivated" is appended
Scenario: Audit Trail — filter by user and action
Given the Audit Trail shows 1000 mock events
When I filter user="Dr John Lim" and action="patient.viewed"
Then the list updates within 100ms to matching events only (AND, not OR)
And the result count reads "<n> events"
Scenario: System Health — display sync status
Given the System Health panel is open
Then I see a "PrismaCloud Sync" card with last-sync (relative), records synced, and a Healthy/Degraded/Failed badge
And an "ETL run history" table of the last 30 runs
And a failed last run uses var(--warning) styling
Scenario: Notification Configuration — adjust a threshold
Given the global AHI threshold is 10 events/hr
When I set RAFFLES AHI to 8 and Save
Then RAFFLES shows 8, the global default stays 10
And an audit event "threshold.updated" is appended
Scenario: Hospital Management — assign a clinician
Given I selected "Mount Elizabeth Hospital"
When I add "Dr Jane Tan" to its assigned clinicians
Then her User Management record shows MEH
And an audit event "clinician.assigned" is appended
Scenario: Feature Flags — toggle GA4
Given the "GA4 Analytics" flag is enabled
When I toggle it off
Then the badge reads "Disabled", a toast confirms, getFeatureFlag('ga4') returns false
And an audit event "flag.toggled" is appended
Scenario: Empty state — no audit events
Given no events match the current filters
Then an empty state renders (Lucide ScrollText, heading, body, "Clear filters")
Scenario: Error handling — invalid threshold value
When I enter "-5" or non-numeric in the AHI field
Then the input shows a var(--destructive) border, inline error, and Save is disabled
Scenario: Permission gating — Read-only role
Given my mock role is "Read-only"
Then all mutating buttons are hidden, a banner reads "Read-only access — actions disabled"
And flag switches are disabled (aria-disabled="true")
Scenario: Exit the admin dashboard
When I click any non-admin sidebar entry or press Escape
Then the Admin Dashboard unmounts and the previous view (scroll + selected patient) restores
B.3 Business rules
- Admin sidebar entry visible only when
userRole === 'admin'. - Every mutating action appends a
mockAuditEventsentry (timestamp, actor, action, target). - Mutations are non-persistent; banner states "Prototype: changes do not persist".
- Threshold validation: AHI ≥ 0, leak L/min ≥ 0, compliance % 0–100; per-hospital overrides global; clearing falls back to global.
- A user cannot deactivate themselves (disabled + tooltip).
- Feature-flag toggles take effect immediately via
FeatureFlagsContext/useFeatureFlag(key). - Audit events older than 90 days hidden by default; "Show all" reveals full history.
B.4
Data models (mock TypeScript — additions to
mockData.ts)
export type UserRole = 'admin' | 'clinician' | 'readonly'
export type UserStatus = 'active' | 'invited' | 'deactivated'
export interface MockClinician {
id: string // CLN-XXXXXXXX
firstName: string; lastName: string; email: string
role: UserRole; status: UserStatus
hospitalIds: string[] // FK → MockHospital.id
lastLoginAt: string | null; invitedAt: string; invitedBy: string | null
}
export interface MockHospital {
id: string // HOSP-XXXX
code: string // 'RAFFLES','MEH','NUH'
name: string; region: string // 'Singapore' | 'Malaysia'
patientCount: number; clinicianIds: string[]
}
export interface MockAuditEvent {
id: string; timestamp: string // ISO-8601 UTC
actorId: string; actorName: string
action: AuditAction
targetType: 'clinician'|'patient'|'hospital'|'threshold'|'flag'
targetId: string; targetLabel: string
metadata?: Record<string, unknown>
}
export type AuditAction =
| 'clinician.invited' | 'clinician.deactivated' | 'clinician.role_changed' | 'clinician.assigned'
| 'patient.viewed' | 'patient.note_added' | 'patient.note_edited' | 'patient.pdf_exported'
| 'hospital.created' | 'hospital.edited'
| 'threshold.updated' | 'flag.toggled'
| 'user.login' | 'user.logout'
export interface MockSyncStatus {
// NOTE: generalise `source` to all four vendor clouds (§5) — one record per vendor:
source: 'cloudpat' | 'nexus360' | 'prismacloud' | 'airview'
lastSyncAt: string
status: 'healthy'|'degraded'|'failed'
recordsLastRun: { patients: number; statistics: number; alarms: number }
errorMessage: string | null; runHistory: MockEtlRun[]
}
export interface MockEtlRun {
id: string; startedAt: string; durationMs: number
recordsTotal: number; status: 'success'|'partial'|'failed'; errorMessage: string | null
}
export interface MockNotificationThreshold {
metric: 'ahi'|'leakMedian'|'leakHighPortion'|'compliancePct'
scope: 'global' | string // 'global' or hospitalId
value: number; updatedAt: string; updatedBy: string
}
export interface MockFeatureFlag {
key: string // 'ga4','clarity','experimental_tabs','pdf_v2'
label: string; description: string; enabled: boolean
scope: 'global'|'per_user'; updatedAt: string; updatedBy: string | null
}Initial seed: 25 clinicians · 8 hospitals (2 regions) · 200 audit events (90 days) · 1 sync status + 30 ETL runs · 12 thresholds · 5 feature flags.
B.5 Component tree
src/app/components/admin/
AdminDashboard.tsx Composition root + vertical tab nav
AdminRoleBanner.tsx
panels/
UserManagementPanel.tsx ClinicianListTable, PatientListTable, InviteClinicianDialog,
DeactivateUserDialog, EditRoleDialog
AuditTrailPanel.tsx AuditEventTable, AuditFilters, AuditEventDetailDrawer
SystemHealthPanel.tsx SyncStatusCard, EtlRunHistoryTable
NotificationConfigPanel.tsx ThresholdTable, ThresholdEditDialog
HospitalManagementPanel.tsx HospitalListTable, HospitalDetailDrawer, AddHospitalDialog
FeatureFlagsPanel.tsx FeatureFlagToggleList
context/ FeatureFlagsContext.tsx provider + useFeatureFlag(key)
utils/ appendAuditEvent.ts, formatRelativeTime.ts
B.6 Architecture & rationale
- New child-component module under
src/app/components/admin/, mirroringpatient/. viewanduserRolestate live inApp.tsx, passed as props (ADR-001, ADR-002).- One exception to prop-drilling:
FeatureFlagsContext(cross-cutting concern consumed by many leaves). - Lazy-mount panels; only the active panel renders. Memoise filter results; debounce search 200ms.
B.7 Testing (key cases)
- Unit:
appendAuditEvent,formatRelativeTime,useFeatureFlag,validateThreshold, seed-data role/status coverage, Fuse.js matches. - Integration: sidebar→AdminDashboard swap; invite appends row + audit
in one cycle;
ga4toggle re-runsinitializeAnalytics(); audit filters compose AND; read-only hides all mutators. - Coverage target ≥80% for
admin/utils/andcontext/.
Appendix C — RBAC & Patient Scoping (full technical spec)
Source of truth: features/rbac/atenvia-rbac.md. This
is the heaviest initiative and the gating dependency for re-enabling the
Admin Dashboard.
C.1 Non-functional requirements
- Performance: authz check <30ms p95; scoped patient reads <300ms p95 (≤500 patients); first authenticated paint <1.5s.
- Security: deny-by-default; every protected route and data access checked server-side; short-lived tokens with refresh; signed/verified RBAC claims (never client-trusted); all denials logged; PHI keeps Clarity masking.
- Accessibility: WCAG 2.1 AA on sign-in / error / access-denied states.
- Scalability: ≥5,000 users, ≥50,000 patients without
full-table scans (indexed
assignedClinicianId/sourceGroup/referredToTAS).
C.2 Acceptance criteria (Gherkin)
Scenario: External clinician sees only their referred patients
Given I am role "doctor"; P1,P2 referred to TAS with me as assigned clinician
And P3 referred to TAS but assigned elsewhere; P4 not referred to TAS
When I load list, search, KPIs, or alerts
Then I see only P1 and P2; P3 and P4 never appear anywhere
Scenario: Direct ID/URL access to an out-of-scope patient is denied
Given I am scoped to P1,P2
When I request P3 by ID, deep link, or PDF-export route
Then the server returns 403 (not 404) and logs the denied attempt (user, target, ts)
Scenario: TAS internal ops has full cross-source visibility
Given I am role "cas"; patients exist across all three source groups
When I load list or search
Then I see every patient across all sources
But I cannot open the Admin Panel or Super Admin surface
Scenario: Tier isolation — clinical/ops cannot reach admin surfaces
Given I am any of doctor/clinician/cs/cas/sales_exec/sales_manager
When I attempt the Admin Panel or Super Admin by nav, URL, or API
Then access is denied server-side, no admin data returned, attempt logged
Scenario: TAS Admin manages users but not platform governance
Given I have "tas_admin"
Then I can manage clinicians/ops users and the six panels
But I cannot reach the Super Admin surface or manage other TAS admins
Scenario: Super Admin governs platform and currently fulfils TAS Admin
Given I am super_admin
When I sign in
Then I land on the Super Admin surface, manage TAS admins/roles/config
And I can also operate the Admin Panel (fulfilling tas_admin for now)
Scenario: Unauthenticated access is rejected
Given no valid session
Then navigation redirects to sign-in; API returns 401; no data returned
Scenario: Session expiry mid-use
Given my token expired
When I perform an authorised action
Then the request fails 401 and the client prompts re-auth without losing nav context where feasible
C.3 Business rules
- Deny by default — no matching grant ⇒ denied.
- Server is the source of truth; UI gating is cosmetic.
- External clinicians scoped to
referredToTAS === true && assignedClinicianId === currentUser.id. - TAS internal ops see all patients; barred from Admin Panel & Super Admin.
- TAS Admin manages users/panels; cannot reach Super Admin or manage other TAS admins.
- Super Admin is the only tier managing TAS admins/platform config;
fulfils
tas_adminuntil dedicated TAS admins exist. - Tier escalation impossible via client; role changes are server-enforced + audited.
- Out-of-scope direct access denied server-side and logged.
C.4 Data models
// Replaces: export type UserRole = 'admin'|'clinician'|'readonly' (mockData.ts:3452)
export type Role =
| 'doctor' | 'clinician' // External Clinical
| 'cs' | 'cas' | 'sales_exec' | 'sales_manager' // TAS Internal Ops
| 'tas_admin' // modelled; initially fulfilled by super_admin
| 'super_admin'; // IT/Digital Transformation + Digital Product
export type AccessTier = 'external_clinical' | 'tas_internal_ops' | 'tas_admin' | 'super_admin';
export const ROLE_TIER: Record<Role, AccessTier> = {
doctor: 'external_clinical', clinician: 'external_clinical',
cs: 'tas_internal_ops', cas: 'tas_internal_ops',
sales_exec: 'tas_internal_ops', sales_manager: 'tas_internal_ops',
tas_admin: 'tas_admin', super_admin: 'super_admin',
};
export type PatientSourceGroup = 'private_referral' | 'gov_referral' | 'tas_direct';
export interface AuthUser {
id: string; email: string; role: Role
status: 'active'|'invited'|'deactivated'
displayName: string; createdAt: string; updatedAt: string
}
// Patient record extensions (existing patient shape in mockData.ts)
export interface PatientAccessFields {
sourceGroup: PatientSourceGroup; // derived from referralInfo.referralOrigin
referredToTAS: boolean; // visibility gate for External Clinical
assignedClinicianId: string | null; // owning external clinician
}Ownership model: single
assignedClinicianId per patient. External Clinical scope =
referredToTAS === true && assignedClinicianId === currentUser.id.
Care-team / multi-owner deferred.
C.5 Capability matrix
| Capability | doctor / clinician | cs / cas / sales_* | tas_admin | super_admin |
|---|---|---|---|---|
| View own referred patients | ✅ | ✅ (all) | — | — |
| View all patients (all sources) | ❌ | ✅ | — | — |
| Open Admin Panel (six panels) | ❌ | ❌ | ✅ | ✅ |
| Manage external clinicians + TAS ops users | ❌ | ❌ | ✅ | ✅ |
| Open Super Admin surface | ❌ | ❌ | ❌ | ✅ |
| Manage TAS admins / platform config | ❌ | ❌ | ❌ | ✅ |
C.6 Authorisation decision (reference, server-side, deny-by-default)
function patientScopePredicate(user: AuthUser): (p: PatientAccessFields) => boolean {
const tier = ROLE_TIER[user.role];
switch (tier) {
case 'tas_internal_ops': return () => true;
case 'external_clinical': return (p) => p.referredToTAS && p.assignedClinicianId === user.id;
default: return () => false; // admin tiers don't browse patient-care data here
}
}
function canAccessSurface(user: AuthUser, surface: 'clinical'|'admin_panel'|'super_admin'): boolean {
const tier = ROLE_TIER[user.role];
if (surface === 'clinical') return tier === 'external_clinical' || tier === 'tas_internal_ops';
if (surface === 'admin_panel') return tier === 'tas_admin' || tier === 'super_admin';
if (surface === 'super_admin') return tier === 'super_admin';
return false;
}Note:
super_adminfulfils the TAS-Admin capability viacanAccessSurfacegranting itadmin_panel— there is no dedicatedtas_adminholder yet. (Open item §7.5.)
C.7 Three-layer enforcement
- Authentication — provider-issued short-lived token
+ refresh (recommended Firebase Auth);
rolecarried as a verified custom claim. - Authorisation middleware — resolves
role → tier → allowed surfaces/actions; rejects with 401/403. - Data scoping — every patient query filtered by the caller's scope predicate before results return. No client-side filtering of a full dataset.
C.8 API (if a backend API is chosen)
GET /api/patients→ patients already scoped to caller;401/403.GET /api/patients/:id→ one patient if in scope; out-of-scope403(per existence-leak rule) + audit.POST /api/admin/users→ TAS Admin / Super Admin only;401/403/422.POST /api/super-admin/roles→ Super Admin only;401/403.
C.9 Firestore security rules (if Firestore chosen)
match /patients/{patientId} {
allow read: if isTasInternalOps()
|| (isExternalClinical()
&& resource.data.referredToTAS == true
&& resource.data.assignedClinicianId == request.auth.uid);
allow write: if isTasAdminOrSuper();
}
match /adminUsers/{uid} { allow read, write: if isTasAdminOrSuper(); }
match /platformConfig/{doc} { allow read, write: if isSuperAdmin(); }
C.10 Audit events added
auth.login · auth.login_failed ·
auth.logout · authz.denied ·
role.granted / role.revoked.
C.11 Testing (key cases)
- Unit:
patientScopePredicateper role;ROLE_TIERcompleteness;canAccessSurfacefull matrix;sourceGroupderivation perreferralOrigin. - Integration: scoped list/
:id(out-of-scope → 403 + audit); admin endpoints reject non-admin tiers; super-admin role-grant rejectstas_admincallers. - E2E: tier isolation; clinician scoped across list/search/KPIs/alerts/detail/PDF; session expiry → re-auth, no leak.
- Targets: 0 cross-tier/cross-scope leaks; 100% patient-read paths through scope predicate; ≥90% unit coverage on scope/capability logic.
Appendix D — Cross-Cutting Architecture & Code References
D.1 Verified code references (as of 2026-06-16)
| Reference | Location | Verified |
|---|---|---|
UserRole enum (to be replaced by
Role) |
src/data/mockData.ts:3452 |
✅ present |
| Admin module | src/app/components/admin/
(AdminDashboard.tsx + panels/) |
✅ built |
| AdminDashboard import (commented out) | src/app/App.tsx:33 |
✅ commented |
| AdminDashboard mount (commented out) | src/app/App.tsx:5398 |
✅ commented |
| App.tsx size | src/app/App.tsx (~5,485 lines) |
✅ monolith |
RBAC types (tas_admin, sourceGroup,
…) |
src/data/mockData.ts |
⛔ not yet present (RBAC unbuilt) |
D.2 Architectural decisions in force
- ADR-001 — single
App.tsxcomposition root, no router. - ADR-002 — prop drilling only; no global state for
app data (cross-cutting concerns may use
useContext, e.g.FeatureFlagsContext). - ADR-003 — dual PDF pipelines (
pdfmaketabular +@react-pdf/renderervisual); no third library. - ADR-004 — CSS variables mandatory; no hardcoded values; no Tailwind text classes on semantic headings.
- ADR-005 —
src/data/mockData.tsis the only data source (until RBAC introduces persistence).
D.3 Styling tokens (admin surfaces)
Panel bg var(--card) · border var(--border)
· active badge var(--success) /
var(--success-foreground) · invited
var(--warning) · deactivated var(--muted) ·
destructive var(--destructive) · spacing
var(--spacing-md|lg|xl) · radius
var(--radius-md|lg).
D.4 Integration dependencies
src/data/mockData.ts— types + seed (admin);Rolereplacement + patient extensions (RBAC).src/utils/hospitalConfig.ts— reconcile withMockHospital.src/utils/analytics.ts— consume flags viauseFeatureFlag('ga4'|'clarity')instead ofimport.meta.env.src/app/App.tsx—viewstate + sidebar entry (admin); tier-aware routing + re-enable Admin mount (RBAC).
Appendix E — Consolidated Risks
| Risk | Source | Impact | Likelihood | Mitigation |
|---|---|---|---|---|
| Stakeholders mistake prototype for production | Admin | H | M | Persistent "Demo mode" banner + one-time explainer dialog |
| Mock data diverges from real PrismaCloud shape | Admin | M | M | Reuse scripts/prismacloud/types.ts where shapes
overlap |
App.tsx grows further (~5,485 lines) |
Admin | M | H | All admin code in components/admin/; only
view state + one conditional in App.tsx |
| Feature-flag toggle breaks live analytics mid-session | Admin | L | M | initializeAnalytics() idempotent / safe to re-run |
| No backend exists; RBAC needs a server source-of-truth | RBAC | H | H | ADR first; Firebase Auth + Firestore (rules-based) or dedicated API as prerequisite |
Patient records lack
assignedClinicianId/sourceGroup/referredToTAS |
RBAC | H | H | Data-model migration + backfill (derive sourceGroup
from referralOrigin) |
| Client-only enforcement bypass | RBAC | H | M | Mandatory server-side checks; UI gating cosmetic; direct-API security tests |
| Existence leakage (404 vs 403) | RBAC | M | M | Decide + document one rule (currently 403 + audit); verify in tests |
| Claim-propagation latency on role change | RBAC | M | M | Force token refresh on role change; short TTL; handle stale claims |
References
docs/prd/overview.md·docs/prd/features/FEATURES.mddocs/prd/features/admin-dashboard/admin-dashboard.md(+mockups/)docs/prd/features/rbac/atenvia-rbac.mddocs/architecture/design-system.md·docs/architecture/Guidelines.mddocs/data/clinical-logic.md- ADRs:
docs/architecture/decisions/ - PrismaCloud:
scripts/prismacloud/types.ts·docs/testing/test-plans/prismacloud-api-test-plan.md
This master PRD is a living document. When the source PRDs change, update the relevant section here (or vice-versa) and bump the date. Standards (HIPAA-style minimum-necessary, OWASP A01 Broken Access Control) drive the RBAC server-side enforcement model.