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

> Dokitab is a cloud-native, multi-tenant EMR platform engineered for clinical efficiency, inpatient tracking, pharmacy inventory control, and HMO claims management.

---

## 1. System Architecture Overview

### 1.1 Backend Infrastructure
- **Framework**: Go (Gin Web Framework) flat-package architecture (`main` package).
- **Database**: PostgreSQL 15+ with PostgreSQL Row-Level Security (RLS) policies enforcing multi-tenant isolation per `hospital_id`.
- **Authentication & Context**: JWT bearer tokens containing user ID, role, and tenant `hospital_id`. Middleware (`RequireAuth`, `RequireDB`, `RunInRLSTransaction`) enforces tenant isolation on all database queries.
- **Clock Drift Safeguards**: `ValidateClockDrift` middleware verifies client timestamps against server clock to reject malformed or skewed clinical records.
- **Patient Identity Resolution**: `ResolvePatientID` handles merged patient records transparently, redirecting rapid emergency records to master patient records.

### 1.2 Web Admin Frontend (`clinical-sanctuary`)
- **Stack**: React 18, TypeScript, Vite, TailwindCSS, Axios.
- **Role-Based Access Control (RBAC)**: Enforced via `roleAllowedPaths` map in `Sidebar.tsx`.
- **Supported Roles**: `admin`, `doctor`, `nurse`, `receptionist`, `pharmacist`, `lab_tech`.

---

## 2. Inpatient & Nursing Care Module

### 2.1 Fluid Balance Tracking (`/api/inpatient/io`)
- **Endpoints**:
  - `POST /api/inpatient/io`: Record fluid intake or output entry.
  - `GET /api/inpatient/io?patientId=<uuid>`: Fetch fluid balance history ordered by `recordedAt DESC`.
- **Validation**:
  - Requires positive non-zero volume (`volume > 0`).
  - Types: `intake` | `output`.
  - Categories: `IV Fluids`, `Oral`, `Urine`, `Vomit`, `Drainage`, `Blood`.

### 2.2 Wound Care Documentation (`/api/inpatient/wound`)
- **Endpoints**:
  - `POST /api/inpatient/wound`: Record wound assessment and dressing changes.
  - `GET /api/inpatient/wound?patientId=<uuid>`: List assessments.
- **Parameters**: `woundLocation`, `woundType`, `sizeCm`, `depth`, `appearance`, `drainage`, `dressingApplied`, `nextDressingDue`.

### 2.3 Medication Administration Record (MAR)
- Tracks planned vs. administered medication doses for admitted patients.
- Includes correction workflow: submitting a correction entry referencing incorrect `doseId` with mandatory clinical reason.

### 2.4 Nursing Handovers
- Handovers record shift transition details between outgoing and incoming nursing staff.
- Includes JSONB snapshots of patient vitals and pending orders at the time of handover.

---

## 3. Emergency Triage & Rapid Registration

- **Categories**:
  - `RED`: Immediate / Life-threatening (Target response: 0 min).
  - `ORANGE`: Urgent (Target response: <15 min).
  - `YELLOW`: Delayed (Target response: <60 min).
  - `GREEN`: Minor (Target response: <120 min).
- **Rapid Emergency Registration**: Allows admitting unconscious or unidentified patients in <30 seconds with minimal fields (`isUnknown`, estimated age, gender, broughtBy), generating temporary MRN.
- **Patient Record Merging**: `POST /api/patients/:id/merge` safely merges temporary emergency records into master patient files with audit logging.

---

## 4. Pharmacy Inventory & FEFO Depletion

- **Depletion Strategy**: First-Expiring, First-Out (FEFO) prioritizing batches ordered by `expiry_date ASC, received_date ASC`.
- **Reorder Warnings**: Automated alerts triggered when batch stock drops below `reorder_level`.
- **Dispensing Workflow**: `PENDING` -> `DISPENSED` -> `ADMINISTERED`.

---

## 5. Nigerian HMO Claims & Billing Module

- **Currency**: All financial billing is denominated in Nigerian Naira (₦).
- **Tariff & Coding**:
  - Integration with ICD-10 diagnosis coding and standard HMO procedure tariffs.
- **Claim Lifecycle**: `DRAFT` -> `SUBMITTED` -> `IN_REVIEW` -> `APPROVED` / `REJECTED` -> `PAID`.
- **Validation**: Automatic timely filing rule checks and diagnosis-to-procedure compatibility scrubbing.

---

## 6. Security, Compliance & Auditability

- **Multi-Tenancy**: Enforced at the database engine level via PostgreSQL Row-Level Security (RLS). Every transaction is wrapped in `RunInRLSTransaction(ctx, db, hospitalID, fn)`.
- **Audit Logs**: Immutable audit log entries (`audit_logs` table) recorded for every clinical write, patient merge, and PHI access.
- **No Silent Failures**: All clinical web and API components surface errors to operators rather than masking network or database exceptions.
