TAS Portal

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.

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:

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.md lists "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)

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:

  1. Admin Dashboard (§3) — an administrative surface for managing users, auditing activity, monitoring system health, configuring alert thresholds, managing hospitals, and toggling feature flags.
  2. 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

2.2 Patient management

2.3 Clinical data surfaces

2.4 Notifications & alerts

2.5 Reporting

2.6 Platform / UX foundations

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


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:

4.3 Patient source groups (drives scoping)

Every patient record originates from one of three groups:

  1. Private hospital / clinic referral (private_referral)
  2. Government / restructured hospital referral (gov_referral)
  3. 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:


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:

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:

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:

  1. Authenticate to the vendor API (per-vendor credentials / OAuth — out of scope until backend exists).
  2. Pull new device records on a schedule (ETL run) — sleep studies (HST) or therapy/compliance data (CPAP).
  3. Normalise vendor-specific payloads into Atenvia's common patient/statistic/alarm shape.
  4. Map device → patient via device serial number (already a first-class search field in the shipped app).
  5. 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

5.6 Open scoping questions

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):

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:


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:

  1. Audit export status — Admin PRD §1 lists audit export as out-of-scope (v2), but src/app/components/admin/panels/auditExport.ts exists. Confirm whether it shipped or is scaffolding; update scope accordingly.
  2. 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.
  3. Persistence / auth provider (RBAC) — Firebase Auth + Firestore vs. dedicated API backend. To be settled in an ADR before any RBAC implementation.
  4. Existence-leak rule (RBAC) — out-of-scope direct patient access returns 403 (with audit) vs 404. Decision documented as 403; confirm and apply consistently.
  5. TAS Admin appointment — when dedicated TAS admins are appointed, confirm the exact split of capabilities retained by Super Admin.
  6. Ownership granularity (RBAC) — single assignedClinicianId now; 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):


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

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

  1. Admin sidebar entry visible only when userRole === 'admin'.
  2. Every mutating action appends a mockAuditEvents entry (timestamp, actor, action, target).
  3. Mutations are non-persistent; banner states "Prototype: changes do not persist".
  4. Threshold validation: AHI ≥ 0, leak L/min ≥ 0, compliance % 0–100; per-hospital overrides global; clearing falls back to global.
  5. A user cannot deactivate themselves (disabled + tooltip).
  6. Feature-flag toggles take effect immediately via FeatureFlagsContext / useFeatureFlag(key).
  7. 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

B.7 Testing (key cases)


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

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

  1. Deny by default — no matching grant ⇒ denied.
  2. Server is the source of truth; UI gating is cosmetic.
  3. External clinicians scoped to referredToTAS === true && assignedClinicianId === currentUser.id.
  4. TAS internal ops see all patients; barred from Admin Panel & Super Admin.
  5. TAS Admin manages users/panels; cannot reach Super Admin or manage other TAS admins.
  6. Super Admin is the only tier managing TAS admins/platform config; fulfils tas_admin until dedicated TAS admins exist.
  7. Tier escalation impossible via client; role changes are server-enforced + audited.
  8. 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_admin fulfils the TAS-Admin capability via canAccessSurface granting it admin_panel — there is no dedicated tas_admin holder yet. (Open item §7.5.)

C.7 Three-layer enforcement

  1. Authentication — provider-issued short-lived token + refresh (recommended Firebase Auth); role carried as a verified custom claim.
  2. Authorisation middleware — resolves role → tier → allowed surfaces/actions; rejects with 401/403.
  3. 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)

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)


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

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


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


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.