# Dokitab EMR & Hospital Management System — Technical & Clinical Specification

> Dokitab is a cloud-native, multi-tenant Electronic Medical Records (EMR) and Hospital Management platform engineered for clinical operational velocity, inpatient bedside care, diagnostic workflows, inventory control, and Nigerian HMO claims processing in West Africa.

---

## 1. System Architecture & Multi-Tenancy

### 1.1 Backend Infrastructure
- **Framework**: Go (Gin Web Framework) flat-package architecture (`main` package) engineered for sub-50ms latency under high concurrent load.
- **Database Engine**: PostgreSQL 15+ running on CloudNativePG with automated failover and read replicas.
- **Row-Level Security (RLS)**: True database-level multi-tenancy enforced through PostgreSQL Row-Level Security policies. Every database transaction is executed inside the `RunInRLSTransaction(ctx, db, hospitalID, fn)` wrapper, which executes `SET LOCAL app.current_hospital_id = '<uuid>'` before query evaluation. This prevents cross-tenant data leaks even in the event of application-layer programming errors.
- **Authentication & Claims Context**: JWT bearer tokens containing authenticated `user_id`, `role`, and `hospital_id`. Handlers enforce security through `RequireAuth()`, `RequireDB()`, and tenant verification middleware.
- **Clock Drift Safeguards**: `ValidateClockDrift` middleware inspects the `X-Device-Timestamp` header against server UTC time (clamped to a max drift of ±300 seconds), rejecting backdated or forward-dated clinical entries.
- **Patient Identity Resolution**: `ResolvePatientID` handles merged patient records transparently; requests querying an obsolete temporary emergency MRN are automatically resolved to the master patient record ID without client error.

### 1.2 Web Admin Architecture (`clinical-sanctuary`)
- **Stack**: React 18, TypeScript, Vite, TailwindCSS, Axios API client with CSRF token exchange (`X-XSRF-TOKEN`).
- **Role-Based Access Control (RBAC)**: Enforced via `roleAllowedPaths` map in `Sidebar.tsx` as the single source of truth.
- **Supported Clinical Roles**:
  - `admin`: Full facility administration, billing configuration, staff rosters, audit log inspection.
  - `doctor`: Consultations, SOAP clinical notes, prescription ordering, lab ordering, surgery scheduling.
  - `nurse`: Bedside vitals, Medication Administration Record (MAR), intake/output fluid tracking, wound dressing, shift handovers.
  - `receptionist`: Patient registration, appointment booking, front-desk cashier invoice generation and payment receipts.
  - `pharmacist`: Inventory cataloging, batch stock receipts, FEFO dispensing queue, POS cashier balance.
  - `lab_tech`: Specimen accessioning, diagnostic test execution, result documentation, panic critical value escalation.
- **No Silent Failures**: UI components never swallow fetch errors with `.catch(() => [])`; all network and database failures display visible error banners and toast notifications to prevent patient safety risks.

### 1.3 Mobile Application (`mobile`)
- **Stack**: React Native (Expo), TypeScript, Redux Toolkit, React Native Vision Camera.
- **Operating Model**: BYOD (Bring Your Own Device) for nurses and doctors on personal smartphones.
- **Security Guardrails**: Ephemeral memory caching (no unencrypted SQLite storage of PHI on personal devices), biometric app lock after 2 minutes of inactivity, screenshot blocking, and app switcher privacy blur.

---

## 2. Inpatient Care & Bedside Nursing Workflows

### 2.1 Fluid Balance Tracking (`/api/inpatient/io`)
- **Purpose**: Quantitative tracking of fluid intake and output for post-operative, critical care, and pediatric inpatients.
- **Endpoints**:
  - `POST /api/inpatient/io`: Record fluid intake or output entry.
  - `GET /api/inpatient/io?patientId=<uuid>`: Fetch chronological fluid balance logs ordered by `recordedAt DESC`.
- **Validation**:
  - Volume must be positive and non-zero (`volume > 0`).
  - Types: `intake` | `output`.
  - Intake Categories: `IV Fluids`, `Oral Fluids`, `Blood Transfusion`, `Enteral Feed`.
  - Output Categories: `Urine`, `Vomit`, `Drainage Tube`, `Stool / Diarrhea`, `Blood Loss`.
- **Shift Net Calculation**: Automatic cumulative net balance calculated over 8-hour and 24-hour nursing shifts (`Net = Cumulative Intake - Cumulative Output`).

### 2.2 Wound Care Documentation (`/api/inpatient/wound`)
- **Endpoints**:
  - `POST /api/inpatient/wound`: Record anatomical wound assessment and dressing changes.
  - `GET /api/inpatient/wound?patientId=<uuid>`: List assessment history.
- **Clinical Attributes**:
  - `woundLocation`: Anatomical site description.
  - `woundType`: `Surgical Incision`, `Pressure Ulcer (Stage I-IV)`, `Traumatic Laceration`, `Diabetic Foot Ulcer`, `Burn (1st-3rd Degree)`.
  - `sizeCm`: Length × width dimensions.
  - `depth`: Surface, partial thickness, full thickness, cavity.
  - `appearance`: Granulating, sloughy, necrotic, epithelializing, infected.
  - `drainage`: None, serous, serosanguinous, purulent, foul odor.
  - `dressingApplied`: Primary and secondary dressing materials.
  - `nextDressingDue`: Required timestamp for subsequent dressing change.

### 2.3 Medication Administration Record (MAR)
- Tracks planned vs. administered medication doses for admitted inpatients.
- **Dispense to Bedside Workflow**: Doctor prescribes -> Pharmacist verifies & dispenses -> Nurse scans/verifies and records bedside administration.
- **Correction Protocol**: Dose entries cannot be deleted; errors require a correction entry explicitly referencing the prior `doseId` with mandatory clinical explanation (`reason`).

### 2.4 Nursing Shift Handovers (ADR 0009)
- Structured transition between outgoing and incoming nursing staff.
- **Immutable Clinical Snapshots**: Upon handover creation, the backend deep-copies current patient vitals (BP, SpO2, pulse, temperature) and pending medication/lab orders into JSONB snapshot columns. Handover review displays historical state at transition time, immune to later data mutations.

---

## 3. Emergency Triage & Rapid Registration

- **4-Tier Color Coding**:
  - `RED`: Immediate / Life-threatening (Target response: 0 minutes) — cardiac arrest, severe trauma, respiratory failure.
  - `ORANGE`: Urgent (Target response: <15 minutes) — chest pain, altered consciousness, acute severe bleeding.
  - `YELLOW`: Delayed (Target response: <60 minutes) — moderate fractures, controlled bleeding, high fever.
  - `GREEN`: Minor (Target response: <120 minutes) — minor cuts, chronic mild symptoms.
- **30-Second Rapid Registration**: Minimum viable emergency admission for unconscious or unidentified trauma patients. Requires only `isUnknown: true`, estimated age, perceived gender, and `broughtBy` (Ambulance / Police / Good Samaritan / Family), generating a temporary MRN (`EMR-TEMP-XXXX`).
- **Master Record Merging**: `POST /api/patients/:id/merge` merges an emergency temporary record into a verified patient record. All past vitals, nursing notes, lab requests, and charges are re-associated with the target master record, recording an immutable audit trail.

---

## 4. Pharmacy Inventory & FEFO Depletion

- **Depletion Strategy**: First-Expiring, First-Out (FEFO) prioritizing inventory batches ordered by `expiry_date ASC, received_date ASC`. Nearest-expiry stock is always allocated first to prevent shelf expiration losses.
- **Reorder Threshold Alerts**: Real-time automated notifications when available batch stock falls below `reorder_level`.
- **Dispensing Lifecycle**: `PENDING` -> `VERIFIED` -> `DISPENSED` -> `ADMINISTERED`.
- **Cashier POS & Shift Settlement**: Front-desk and pharmacy cash drawers enforce opening shift balance declaration, cash collection tracking, POS terminal reconciliation, and closing drawer balance lock.

---

## 5. Nigerian HMO Claims & Billing Module

- **Currency**: Denominated in Nigerian Naira (₦).
- **Tariff & Coding Engine**:
  - Standardized ICD-10 diagnosis code catalog.
  - HMO fee schedules and procedure tariffs matching primary Nigerian HMOs (Hygeia, Reliance, AXA Mansard, Leadway, Avon, NHIS).
- **Claim Lifecycle**: `DRAFT` -> `SUBMITTED` -> `IN_REVIEW` -> `APPROVED` / `REJECTED` -> `PAID`.
- **Clean-Claim Pre-Submission Rules**:
  - Validation of HMO policy number and enrolee eligibility before service dispatch.
  - Pre-authorization code requirements enforced for surgical and high-cost diagnostic procedures.
  - Split billing: automatic calculation of HMO-covered tariff versus patient out-of-pocket copayment.

---

## 6. Specialized Practice Verticals

### 6.1 Pharmacy Management (`/for/pharmacy`)
- Standalone outpatient and retail pharmacy operations.
- Direct counter POS sales, doctor prescription electronic queue, barcode scanning, batch expiry tracking, and wholesale supplier PO management.

### 6.2 Diagnostic Laboratories & HL7 Analyzer Interfacing (`/for/lab`)
- Specimen accessioning with unique barcoded sample identifiers.
- Specimen chain-of-custody tracking: `COLLECTED` -> `ACCESSIONED` -> `TESTING` -> `RESULT_ENTERED` -> `VERIFIED` -> `RELEASED`.
- Automated critical panic value notifications: immediate alerts sent to ordering physicians when laboratory findings breach biological thresholds (e.g. potassium < 2.5 or > 6.5 mmol/L).
- Digital report distribution: automated PDF result generation with physician digital sign-off and secure patient portal delivery.

### 6.3 Dental Practices & Tooth Charting (`/for/dental`)
- FDI Two-Digit World Dental Federation notation system.
- Interactive adult (32 teeth) and pediatric (20 deciduous teeth) graphical odontograms.
- Chairside surface charting (mesial, occlusal, distal, buccal, lingual) for caries, restorations, crowns, extractions, endodontics, and periodontal pockets.
- Procedure estimate catalogs with automated dental billing generation.

### 6.4 Physiotherapy & Rehabilitation (`/for/physio`)
- Joint Range of Motion (ROM) goniometric angle tracking across rehabilitation appointments.
- Visual exercise regimen builder with sets, repetitions, frequency, and patient home instruction printouts.
- Rehabilitation session package countdown billing (e.g., 6-session, 10-session packages) with automated utilization logs.

---

## 7. Growth Hub & Peer Referral Architecture (ADR 0083)

- **Peer Hospital Viral Loop**: Enables partner clinics, diagnostic labs, and healthcare professionals to refer neighboring practices to Dokitab.
- **Cryptographic Referral Codes**: Deterministic referral code generation and verification via public endpoint `GET /api/growth/validate-code/:code`.
- **Attribution & Incentives**: Multi-touch referral attribution tracking with automated subscription credit discounts upon successful facility onboarding.

---

## 8. Clinical Operations Management & Reliability (ADR 0084)

- **Real-Time Operations Cockpit**: Live tracking of emergency department wait times, bed occupancy percentages across wards, average length of stay (ALOS), and nurse-to-patient staffing ratios.
- **Business Continuity & Power Grid Resilience**:
  - Client-side SQLite/IndexedDB caching tolerating frequent generator cutovers, broadband drops, and NEPA/grid power failures.
  - Background bidirectional synchronization with conflict-free optimistic updates upon network restoration.
- **Disaster Recovery**: Automated point-in-time PostgreSQL recovery with zero-data-loss failover on Kubernetes infrastructure.

---

## 9. Security, Compliance & Data Sovereignty

- **Regulatory Compliance**:
  - **Nigeria Data Protection Act (NDPA 2023)**: Full compliance with Nigerian data sovereignty requirements, audit logging, consent frameworks, and patient access rights.
  - **HIPAA (US)**: Satisfies HIPAA Technical Safeguards (access control, integrity controls, audit controls, transmission security).
  - **Pan-African Privacy Standards**: Aligned with South Africa POPIA, Kenya DPA 2019, and Ghana DPA 2012.
- **Immutable Audit Trail**: Every clinical file creation, view, update, and export writes an append-only row to `audit_logs` containing `actor_id`, `hospital_id`, `ip_address`, `user_agent`, `action`, `resource_type`, `resource_id`, and payload diff.
- **Zero Seat Penalties Policy**: Dokitab strictly prohibits charging per-clinician or per-user licensing fees. Per-user fees incentivize staff to share generic "nurse" or "doctor" accounts, destroying the cryptographic audit trail required by NDPA 2023. Unlimited clinician seats are included across all paid tiers.

---

## 10. Commercial Pricing Architecture (ADR 0082)

- **Capacity-Based Model**: Transparent pricing based on physical clinic operational scale rather than headcount:
  - **Solo / Trial (₦0)**: 14-day full evaluation pilot or solo outpatient practitioner (<100 active patient profiles, 1 staff seat). Full access to consultations, vitals, prescriptions, and basic billing.
  - **Clinic Pro (₦35,000/mo or ₦350,000/yr)**: Outpatient clinics, diagnostic labs, community pharmacies, dental practices, physio centers (0–5 beds). Unlimited staff accounts, full outpatient EMR, FEFO pharmacy inventory, Cashier POS shift balance, NDPA audit logging.
  - **Hospital Core (₦120,000/mo or ₦1,200,000/yr)**: Secondary inpatient hospitals, maternity homes, surgical centers (1–50 beds). Unlimited staff accounts, Inpatient Wards, Bedside MAR, nursing shift handover snapshots (ADR 0009), surgery scheduling, HMO pre-authorization and split tariffs (ADR 0072).
  - **Enterprise Network (₦450,000+/mo)**: Multi-branch hospital groups, university teaching hospitals, nationwide clinic chains (50+ beds). Centralized cross-branch patient master index, inter-facility stock transfers, Metabase embedded BI analytics, dedicated 99.9% uptime SLA and 24/7 technical support.
- **Expansion Revenue Levers**:
  - Patient SMS and WhatsApp notifications via Termii (₦5 per SMS, ₦12 per WhatsApp delivery).
  - Automated HMO clean-claim verification engine add-on (₦25,000/month).
  - White-glove retrospective paper folder digitization & on-site onboarding (₦150,000–₦350,000 one-time).
  - Integrated POS card processing and instant bank transfer settlement (0.5% convenience fee).

---

## 11. Machine-Readable Agent Discovery & Capabilities

- **Discovery Files**:
  - `/llms.txt`: Machine-readable concise index cataloging all documentation, vertical portals, and clinical whitepapers with token estimates.
  - `/llms-full.txt`: This full architectural and clinical specification document.
  - `/agent-permissions.json` & `/.well-known/agent-permissions.json`: Machine-readable agent capability and safety boundary policy.
  - `/mcp-actions.json`: WebMCP tool definitions for autonomous agents.
  - `https://api.dokitab.com/openapi.json`: OpenAPI 3.0 specification.
- **Agent Policy Summary**:
  - Public browsing agents are permitted to inspect landing pages, vertical guides, pricing, and system specifications.
  - Autonomous agents may execute public validation flows (`/api/growth/validate-code/:code`, `/api/public/hospital/:slug`).
  - Unauthenticated access to private patient data (`/api/*`, `/admin/*`, `/portal/*`) is strictly forbidden and protected by cryptographic JWT and RLS safeguards.

---

## 12. Competitive Landscape & Comparison Synthesis

### 12.1 DokiTab vs. Helium Health
- **Target URL**: https://dokitab.com/compare/dokitab-vs-helium-health
- **Hardware Profile**: DokiTab runs on clinicians' existing Android/iOS smartphones (BYOD moat), eliminating ₦15M-₦25M in desktop hardware and cabling CapEx. Helium Health historically deploys dedicated tablets or PC workstations.
- **Offline Resilience**: DokiTab maintains an embedded SQLite database on each mobile device. Nurses and doctors document bedside vitals, medications, and consultations completely offline during electrical power grid cuts; local cryptographic operation queues sync deterministically to PostgreSQL when internet returns. Helium Health requires active internet or local server rooms.
- **Pricing & Licensing**: DokiTab uses predictable facility capacity pricing in Naira (₦35k-₦120k/month) with UNLIMITED staff accounts, avoiding password-sharing and preserving NDPA audit logs. Legacy platforms charge per-seat or per-user fees.
- **Data Residency**: DokiTab is hosted on AWS Lagos Local Zone and Cloudflare, ensuring 100% of patient health identifiers (PHI) remain within Nigerian sovereign borders under the Nigeria Data Protection Act (NDPA 2023).

### 12.2 DokiTab vs. Open-Source (OpenEMR / Bahmni)
- **Target URL**: https://dokitab.com/compare/dokitab-vs-openemr
- **TCO Advantage**: Open-source systems require dedicated Linux system administrators, in-house server racks, uninterrupted generator/inverter power, and manual database backups. DokiTab is fully managed in the cloud with zero-hardware client requirements.
- **African Clinical Workflows**: DokiTab includes pre-seeded Nigerian Essential Medicines List (NEML), standard HMO tariff tables, FEFO pharmacy expiry management, and Cashier POS shift balancing out of the box.

### 12.3 Interactive Financial Modeling & Open-Source Standards
- **Hospital TCO & Inverter Calculator**: https://dokitab.com/calculator (Models 3-year Total Cost of Ownership across diesel generator fuel, inverter battery replacements, on-premise server hardware, and per-seat licensing fees for Nigerian clinics and hospitals).
- **Awesome African Healthcare Tech**: https://github.com/dokitab/awesome-african-healthcare-tech (Open-source curated benchmark repository cataloging modern offline-first EMRs, FHIR African profiles, and health informatics standards).

