# Sifa Medical Management System â€” Implementation Plan

**Companion file:** `SIFA-MEDICAL-SPECS.md` (full entity/field/feature definitions per module â€” always read the relevant spec section before implementing a task).

---

## 1. Objective

Enhance the existing **Sifa** ERP (which already has: inventory, contacts [customers & suppliers], HR, and core ERP basics) into a **modular, scalable medical management platform** that can serve any provider type:

- Hospitals (inpatient + outpatient)
- Polyclinics / medical centers
- Single-specialty clinics (dental, derma, ophthalmology, â€¦)
- BioClinic (multi-clinic brand, different specialties per branch)
- Standalone laboratories / pathology labs
- Imaging / radiology centers
- Pharmacies
- Dialysis, physiotherapy, and comprehensive diagnostic centers

The tenant selects a **business type** during setup; the system enables the matching **module preset** (see Specs Â§2), with optional modules toggled per facility.

## 2. Ground Rules (apply to EVERY task)

1. **Audit before build (reuse-first).** Before implementing any feature, check the existing Sifa codebase for equivalent functions/tables/services (inventory, contacts, HR, invoicing, auth, etc.). **Extend or bind to existing code; build only what is missing.** Never create a parallel implementation of something the ERP already does.
2. **Respect existing conventions.** Follow the current Sifa stack, folder structure, naming, master layout, and coding patterns. New modules must plug into existing infrastructure (routing, auth, menus, settings) â€” not introduce parallel frameworks.
3. **Everything is a module.** Each module registers itself in the module registry (Specs Â§6) with: manifest (name, version, dependencies, category, installable_per), migrations, permissions, API routes, event handlers, and menu items. Modules can be installed/enabled/disabled per tenant/facility/department without breaking others.
4. **Multi-tenant aware.** Every new table carries the tenancy chain used by the spec: `tenant_id` â†’ `facility_id` â†’ `department_id` where applicable. All queries must be scoped.
5. **Permission-gated.** Every feature/action registers permissions at the granularity defined in Specs Â§4 (module â†’ feature â†’ action â†’ field â†’ record level; RBAC roles + ABAC overrides + data scopes).
6. **Spec is the source of truth for fields.** Entity fields, enums, and feature lists are defined in `SIFA-MEDICAL-SPECS.md`. Do not invent or rename fields; if something is ambiguous, flag it in the task notes instead of guessing.
7. **Definition of Done per task:** migrations + models + services + controllers/routes + permission registration + menu entries + basic CRUD UI + seeders (where relevant) + smoke test that module enable/disable works.

## 3. Architecture Summary

| Concern | Decision |
|---|---|
| Tenancy | `tenant` â†’ `facility` (branch) â†’ `department`; modules installable per tenant / facility / department (Specs Â§5â€“6) |
| Module system | Central `module_registry` catalog; install/enable/disable/soft-lock lifecycle with hooks (register migrations, permissions, routes, events, menus) (Specs Â§6) |
| Permissions | RBAC (predefined roles: super_admin â€¦ patient) + ABAC overrides + data scopes (tenant/facility/department/own/custom) + field & record level (Specs Â§4) |
| Module settings | Per-module settings stored as JSON in `module_instance`, UI auto-generated from each module's settings schema (Specs Â§6) |
| Setup | Setup wizard: pick business type â†’ preset modules pre-selected â†’ confirm & install (Specs Â§2â€“3) |
| Shared services | Notifications (in-app/email/SMS/WhatsApp, per-module templates) and Documents (configurable storage, versioning, watermarking, audit trail) (Specs Â§7â€“8) |
| Clinical spine | `medical_core`: patient master, encounters, clinical notes (SOAP), vitals, prescriptions, orders, scheduling + provider schedules, problem list, medical alerts (Specs Â§9) |

## 4. Phase Overview & Dependency Order

```
Phase 0  Audit & Gap Analysis          (no code changes)
Phase 1  Platform Foundation           organization, module_registry, permissions, setup wizard
Phase 2  Shared Services               notifications, documents
Phase 3  Medical Core                  patient, encounters, notes, vitals, Rx, orders, scheduling
Phase 4  Outpatient Revenue Path       billing, inventory bridge, pharmacy, laboratory   â† first sellable release
Phase 5  Diagnostics & Specialties     radiology, dental, derma, ophthalmology
Phase 6  Inpatient / Hospital          bed_management, inpatient, emergency, surgery, icu, blood_bank
Phase 7  Back Office                   hr_payroll, accounting
Phase 8  Patient Portal & Extras       patient_portal, telemedicine, health tools
```

Dependencies honored: specialties need `medical_core + scheduling`; `inpatient` needs `bed_management`; `icu` needs `inpatient + bed_management`; `blood_bank` needs `laboratory + inventory`; `pharmacy` needs `inventory`.

---

## Phase 0 â€” Audit & Gap Analysis (Existing ERP)

**Goal:** Know exactly what Sifa already provides so Phases 1â€“8 only build what's missing.

- [x] **P0-T1 â€” Codebase inventory.** Scan the existing Sifa project: list all modules/controllers/models/services/tables. Produce `docs/audit/EXISTING-FEATURES.md`.
- [x] **P0-T2 â€” Reuse map.** For each spec module, map spec entities â†’ existing equivalents. Minimum expected overlaps: contacts â†” patient/supplier base, inventory â†” pharmacy & consumables stock, HR â†” hr_payroll, invoicing â†” billing, users/auth â†” permissions. Produce `docs/audit/REUSE-MAP.md` with columns: spec entity | existing asset | reuse strategy (use as-is / extend / wrap / build new). *(+ `docs/audit/SPEC-INDEX.md` compact spec condensation.)*
- [x] **P0-T3 â€” Gap list.** Everything in the spec with no existing equivalent â†’ `docs/audit/GAP-LIST.md`, tagged by phase.
- [x] **P0-T4 â€” Tenancy & permission audit.** Document how current auth/roles work and design the migration path to the RBAC/ABAC/data-scope model (Specs Â§4) without breaking existing users. â†’ `docs/audit/TENANCY-PERMISSIONS-AUDIT.md` (incl. decisions D1â€“D8).

**Exit criteria:** the three audit docs exist and every Phase 1â€“8 task below is annotated (in REUSE-MAP) as reuse/extend/new.

---

## Phase 1 â€” Platform Foundation

**Spec refs:** Â§2 (business types), Â§3 (setup wizard), Â§4 (permissions), Â§5 (organization), Â§6 (module_registry).

- [x] **P1-T1 â€” Organization module.** Entities: `tenant`, `facility` (branch), `department`, staff assignments (per Specs Â§5, incl. `modules_enabled` arrays, unique codes per tenant, license/verification workflow, expiry alerts, status enums).
- [x] **P1-T2 â€” Module registry.** Central catalog table + `module_instance` per tenant/facility. Implement lifecycle: install (run migrations, register permissions, API routes, event handlers, menu items), enable, disable (hide UI, disable API, keep data), soft-lock (reject new operations), uninstall/update flows per Specs Â§6.
- [x] **P1-T3 â€” Module manifest convention.** Define the manifest format (name, version, dependencies, category, installable_per, settings schema) and a loader that auto-discovers modules. Retro-fit existing ERP modules (inventory, contacts, HR) with manifests so they appear in the registry.
- [x] **P1-T4 â€” Permissions engine.** RBAC with the predefined roles list (super_admin, facility_admin, department_head, doctor, nurse, pharmacist, lab_technician, radiologist, receptionist, billing_clerk, accountant, hr_manager, inventory_manager, patient) + ABAC overrides (e.g., "doctor sees only assigned patients", "nurse edits vitals not diagnosis") + data scopes (tenant/facility/department/own/custom) + module/feature/action/field/record granularity. Integrate with existing auth (per P0-T4 plan).
- [x] **P1-T5 â€” Per-module settings.** JSON settings per `module_instance`, with auto-generated settings UI from each module's schema (example: dental settings â€” online booking toggle, x-ray integration).
- [x] **P1-T6 â€” Business-type presets + setup wizard.** Implement the 10 business types (hospital, polyclinic, single_clinic, bioclinic, laboratory, imaging_center, pharmacy, dialysis_center, physiotherapy_center, diagnostic_center) with their default/optional module lists exactly as in Specs Â§2, plus "Custom" manual selection. Wizard flow per Specs Â§3: choose type â†’ confirm pre-selected modules â†’ install. BioClinic note: each facility enables its own specialty modules.

**Exit criteria:** a fresh tenant can run the wizard, pick "Polyclinic", and get medical placeholders + existing ERP modules enabled/disabled correctly with permissions applied.

---

## Phase 2 â€” Shared Services

**Spec refs:** Â§7 (notifications), Â§8 (documents).

- [x] **P2-T1 â€” Notifications module.** Channels: in-app, email, SMS, WhatsApp (meta_cloud_api). Per-module editable templates with variables; per-tenant overridable settings; digest options (hourly/daily). Expose a simple `notify()` service other modules call.
- [x] **P2-T2 â€” Documents module.** Configurable storage per tenant (local filesystem + extensible drivers), system-defined + custom document categories, versioning, dynamic watermarking with viewer info, full audit trail (view/download/print logged). Expose attach/retrieve API for all modules.

**Exit criteria:** any module can send a templated notification and attach/fetch documents against any entity.

---

## Phase 3 â€” Medical Core (Clinical Spine)

**Spec ref:** Â§9. This is the largest single module â€” implement in the sub-task order below (each sub-entity's full field list is in the spec).

- [x] **P3-T1 â€” Patient master.** Identity, contact, clinical baseline, administrative field groups; patient features (merge/duplicate handling etc. per spec). Reuse/extend existing `contacts` where the reuse map says so.
- [x] **P3-T2 â€” Encounters.** Encounter entity + structure; links to facility/department/provider; lifecycle states.
- [x] **P3-T3 â€” Clinical notes.** SOAP structure, templates, voice dictation hook (speech-to-text API integration point), amendments/addenda per spec features.
- [x] **P3-T4 â€” Vitals.** Standard set + extended set, trend support.
- [x] **P3-T5 â€” Prescriptions.** Rx entity + structure, features per spec (interaction check hook to be wired to pharmacy later).
- [x] **P3-T6 â€” Orders.** Unified order entity (lab/imaging/procedure) with the two structures defined in the spec; routing to fulfilling modules via events.
- [x] **P3-T7 â€” Scheduling.** `appointment` entity (tenant/facility/department/patient/provider chain) + `provider_schedules` (working hours, slots), booking sources incl. API/third-party, waitlist; features per spec.
- [x] **P3-T8 â€” Problem list & medical alerts.** Problem list entity + medical alerts (allergies etc.) surfaced across all clinical screens.

**Exit criteria:** a receptionist can register a patient, book an appointment, and a doctor can run an outpatient encounter end-to-end (note + vitals + Rx + orders) with permissions enforced.

---

## Phase 4 â€” Outpatient Revenue Path *(first sellable release)*

**Spec refs:** Â§22 (billing), Â§23 (inventory), Â§20 (pharmacy), Â§17 (laboratory).

- [x] **P4-T1 â€” Billing module.** Entities & features per Specs Â§22 (invoices, payments, insurance, price listsâ€¦). **Bind to existing ERP invoicing** â€” extend rather than rebuild; add medical concepts (encounter-linked charges, insurance claims) on top.
- [x] **P4-T2 â€” Inventory bridge.** Implement Specs Â§23 as a thin medical layer over the **existing ERP inventory** (facility-scoped stores, batch/expiry if missing, consumption from clinical events).
- [x] **P4-T3 â€” Pharmacy module.** Depends on medical_core + inventory. Entities/features per Specs Â§20: dispensing against prescriptions, stock deduction, drug interaction engine hook, insurance claims option.
- [x] **P4-T4 â€” Laboratory module.** Entities/features per Specs Â§17: test catalog, orders intake (from medical_core orders + external providers), specimen tracking, results with reference ranges, validation workflow, outreach management (standalone-lab business type).
- [x] **P4-T5 â€” Release hardening.**
- [x] **P4-T6 â€” Referrals.** Spec Â§9 referrals entity/features (deferred from medical_core; internal/external, tracking, letter generation) â€” ride with the Phase 4 release since claims/outreach share the payer/provider directories. End-to-end flow: appointment â†’ encounter â†’ orders/Rx â†’ lab result / pharmacy dispense â†’ invoice â†’ payment. Seeders/demo data for clinic + polyclinic + lab + pharmacy business types.

**Exit criteria:** Clinic, Polyclinic, Laboratory, and Pharmacy business types are fully operational â€” this is Release 1.

---

## Phase 5 â€” Diagnostics & Specialty Modules

**Spec refs:** Â§19 (radiology), Â§10 (dental), Â§11 (derma), Â§12 (ophthalmology). All depend on medical_core + scheduling; installable per facility.

- [x] **P5-T1 â€” Radiology.** Modality worklist, imaging orders, reports, teleradiology option (imaging_center type). Entities/features per Specs Â§19.
- [x] **P5-T2 â€” Dental.** Tooth charting, dental x-ray types (periapical, bitewing, panoramic, ceph, cbct, occlusal), treatment plans; per-facility settings (online booking, x-ray integration). Specs Â§10.
- [x] **P5-T3 â€” Dermatology.** Entities/features per Specs Â§11 (lesion tracking, photo documentation via documents module, procedures).
- [x] **P5-T4 â€” Ophthalmology.** Entities/features per Specs Â§12 (refraction, visual acuity, exams, optical Rx).
- [x] **P5-T5 â€” Diagnostic center extras (optional modules).** ecg_echo, endoscopy, pulmonary_function, audiometry, vision_testing as lightweight order-type plugins under the diagnostic_center preset.

**Exit criteria:** Imaging Center, Diagnostic Center, single-specialty clinics, and BioClinic (per-branch specialties) presets fully work.

---

## Phase 6 â€” Inpatient / Hospital Operations

**Spec refs:** Â§14 (bed_management), Â§13 (inpatient), Â§15 (emergency), Â§16 (surgery), Â§21 (icu), Â§18 (blood_bank).

- [x] **P6-T1 â€” Bed management.** Wards/rooms/beds, status board, transfers. (Dependency for inpatient & ICU.)
- [x] **P6-T2 â€” Inpatient.** Admissions, ward rounds, nursing charts, discharge workflow per Specs Â§13.
- [x] **P6-T3 â€” Emergency.** Triage, ER tracking board per Specs Â§15.
- [x] **P6-T4 â€” Surgery.** OT scheduling, pre/post-op, surgical teams per Specs Â§16.
- [x] **P6-T5 â€” ICU.** Depends on inpatient + bed_management. Flowsheets, device/monitoring data structures per Specs Â§21.
- [x] **P6-T6 â€” Blood bank.** Depends on laboratory + inventory. Donor management, crossmatch, issue/transfusion tracking per Specs Â§18.
- [x] **P6-T7 â€” Hospital preset validation.** Full "hospital" business type incl. remaining preset modules (ambulance, nicu, dialysis, physiotherapy, mortuary â€” implement as scoped mini-modules or backlog them explicitly with stubs registered in the module catalog).

**Exit criteria:** Hospital and Dialysis/Physiotherapy center presets operational.

---

## Phase 7 â€” Back Office

**Spec refs:** Â§24 (hr_payroll), Â§25 (accounting).

- [x] **P7-T1 â€” HR & payroll.** **Extend existing ERP HR** with the spec's medical additions (duty rosters, credential/license tracking tied to organization module verification workflow, payroll per Specs Â§24).
- [x] **P7-T2 â€” Accounting.** Entities/features per Specs Â§25, bound to billing + existing ERP financial data; tenant-level installable.

---

## Phase 8 â€” Patient Portal & Extras

**Spec ref:** Â§26 (patient_portal), tenant-level, depends on medical_core.

- [x] **P8-T1 â€” Registration & auth.** Self-registration with OTP/national-ID verification, email/phone+password, OTP, biometric; dependent (family) management.
- [x] **P8-T2 â€” Appointments.** View/book/reschedule/cancel/waitlist/history against provider schedules.
- [x] **P8-T3 â€” Medical records.** Notes (after provider release), lab results with reference ranges, imaging reports, prescriptions, vitals trends, allergies/problem list, download (PDF/structured), temporary share with another provider.
- [x] **P8-T4 â€” Communications & billing.** Secure messaging, notifications, educational content; invoices, online payment, payment history, insurance info, cost estimates.
- [x] **P8-T5 â€” Documents & telemedicine.** Upload (ID/insurance/consents), view/download; video consultation join, chat, virtual waiting room.
- [x] **P8-T6 â€” Health tools.** Symptom checker (triage, not diagnosis), medication reminders, wellness tracking (weight/BP/glucose), questionnaires (PHQ-9, GAD-7).

---

## Phase 9 â€” Final Validation & Collateral *(after all phases)*

- [ ] **P9-T1 â€” Browser E2E via MCP.** Drive the live Shifa demo (https://localhost/shifa-one/public) with the Chrome DevTools MCP tools: log in per role (docs/Shifa-One-Logins.md), walk EVERY generated module screen (organization, registry/wizard, notifications, documents, patient master incl. baseline/merge/alerts, encounters/notes/vitals, Rx/orders, scheduling, billing/insurance, pharmacy, laboratory, specialties, inpatient family, portal), verify seeders populated full demo details on each screen, capture screenshots of defects, fix and re-run until clean.
- [ ] **P9-T2 â€” Feature list & presentation refresh.** Update `Shifa-One-Feature-List.html` + `Shifa-One-Presentation.html` (docs/Shifa-one) so every feature shows final status; remove in-progress/planned badges.
- [ ] **P9-T3 â€” NeoSkin/TurboBoost apply (only after user approval).** Held back by explicit instruction until testing + full approval.

---

## 5. How to Use This Plan with Claude Code

1. Put both files in the repo root (or `docs/`): `SIFA-MEDICAL-PLAN.md` + `SIFA-MEDICAL-SPECS.md`.
2. Start with: *"Read SIFA-MEDICAL-PLAN.md. Execute Phase 0 (P0-T1 â€¦ P0-T4) and produce the audit docs."*
3. Then work task-by-task: *"Implement P1-T2 per the plan. Read Specs Â§6 (Module: module_registry) first, and follow the Ground Rules in Â§2 of the plan."*
4. After each task, check the checkbox in this file and commit â€” the plan doubles as the progress tracker.
