# Shifa One — Reuse Map (P0-T2)

> For each spec module: spec entity/feature → existing asset → **reuse strategy**.
> Strategies: **use-as-is** · **extend** (add columns/satellite tables/features to existing asset) · **wrap** (new thin service/UI over existing engine) · **bind** (integrate via FK/events, no schema change) · **build-new**.
> Ground rule honored: **never re-implement what the ERP already does; new schema lives in new modules — the core stays untouched** (module-only rule).

## Canonical terminology mapping

| Spec term | Platform equivalent | Notes |
|---|---|---|
| tenant | `business` | one row per provider organization |
| facility (branch) | `business_locations` (+ `clc_clinic_locations` link) | leaf-level today; hierarchy = gap |
| department | `clc_departments` | exists in ClinicCore, business-scoped |
| provider (doctor) | `clc_doctors` (optional `users` link) | |
| patient | `contacts` (type customer) ↔ 1:1 `clc_patients` | ERP invoicing works out of the box |
| module install per tenant | Superadmin subscription `package_details` flags | declared via `DataController::superadmin_package()` |
| module version/install | `system.{module}_version` + module InstallController | |
| encounter | `clc_appointments` (appointment+encounter combined) | see medical_core notes |

---

## §5 organization

| Spec entity | Existing asset | Strategy |
|---|---|---|
| tenant | `business` (name, currency, tz via settings, logo in core settings) | **use-as-is**; missing branding/legal fields → satellite `org_tenant_profiles` in new module only if a task needs them |
| facility | `business_locations` | **extend** via satellite table (1:1 `business_location_id`): type enum, parent_facility_id (nesting), working_hours, capacity, geo, modules_enabled[] — new `Organization`-scope tables live in the new module, core untouched |
| department | `clc_departments` | **extend**: add code, type enum, parent_department_id, head_user_id, working_hours, location link, modules_enabled[] (additive migration inside a new module or ClinicCore) |
| room | — | **build-new** (`org_rooms`), FK to department |
| user_management (assignment m2m) | `users` + Spatie roles + `permission.location.{id}` | **extend**: m2m user↔department table; license/credential tracking → new tables + expiry alerts via existing reminder/cron patterns |
| license/credential verification workflow | Essentials employee documents (storage only) | **build-new** workflow on top of existing document storage |

## §6 module_registry

| Spec concern | Existing asset | Strategy |
|---|---|---|
| central catalog | `module.json` manifests + `modules_statuses.json` + `Nwidart\Modules` | **wrap**: catalog table seeded from manifests + medical metadata (category, installable_per, dependencies) |
| per-tenant install | Superadmin `subscriptions.package_details` + `hasThePermissionInSubscription()` | **use-as-is** as the tenant gate; wizard writes these flags |
| per-facility/department instance | `business_locations.modules_enabled`? (absent), `clc_module_settings` | **build-new** `module_instances` (module × business × location/department, status, settings JSON) checked by a helper alongside the subscription gate |
| lifecycle install/enable/disable/soft-lock | module InstallControllers + `system.{module}_version` + statuses JSON | **wrap**: registry service orchestrates existing install endpoints; disable = hide UI/deny API via existing gates; soft-lock = new status in `module_instances` |
| manifest convention | `module.json` (`requires`, providers, alias) | **extend** convention: add `extra.medical` block (category, installable_per, settings_schema, preset keys) — read by registry seeder; retro-fit = seed rows for existing modules, no code changes to them |
| settings schema → auto UI | ad-hoc JSON settings everywhere | **build-new** generic schema-driven settings renderer storing into `module_instances.settings` |

## §4 permissions

| Spec concern | Existing asset | Strategy |
|---|---|---|
| RBAC roles | Spatie roles per business (`Admin#`, `Cashier#`) | **extend**: seed the 14 predefined medical roles per business (suffix pattern kept); map to module `user_permissions()` |
| module/feature/action perms | Spatie permissions registered in module migrations | **use-as-is** (naming convention `module.feature.action`) |
| location/facility scope | `permission.location.{id}` + `permitted_locations()` | **use-as-is** for facility scope |
| department scope | — | **build-new**: user↔department assignments + query scope helper |
| own scope | `*.view_own` pattern | **use-as-is**, replicate for clinical entities (assigned doctor) |
| ABAC overrides | — | **build-new** policy layer (Gate/Policy classes + config-driven rules) — see [TENANCY-PERMISSIONS-AUDIT.md](TENANCY-PERMISSIONS-AUDIT.md) |
| field-level | — | **build-new selectively** (sparse `field.{entity}.{group}` permissions consumed by Blade/API transformers; only where spec demands, e.g. nurse vitals-only) |
| record-level | `clc_authorized_vets` (per-patient grants), `user_contact_access` | **extend** into generic patient-access policy |

## §2–3 business types & setup wizard

| Spec concern | Existing asset | Strategy |
|---|---|---|
| 10 presets + custom | — (Superadmin packages are manual) | **build-new** preset definitions (config) mapping to existing module flags + specialty selections |
| wizard UI | `/business/register` + `BusinessUtil::newBusinessDefaultResources()` | **extend**: post-registration wizard step (new module route) that applies preset → writes subscription flags / module_instances → runs installs |
| BioClinic per-facility specialties | `clc_specialties` registry (45 seeded) + per-facility instance table | **bind**: `module_instances` scoped to location |

## §7 notifications

| Spec concern | Existing asset | Strategy |
|---|---|---|
| email/SMS templates + auto-send | `notification_templates` + `NotificationUtil` | **wrap** behind `notify()` service |
| WhatsApp (meta_cloud_api) | WhatsApp module (`WaSender`, templates, channels) | **use-as-is** via service |
| in-app center | Laravel `notifications` table (used ad-hoc by modules) | **extend**: notification center UI + read tracking |
| per-module template registry | fixed `template_for` list in core | **build-new** registry table for module events (additive; core templates keep working) |
| per-user prefs, quiet hours, digests | — | **build-new** (prefs table + digest cron via existing scheduler patterns) |
| voice/push channels | portal web-push (`portal_push_subscriptions`, staff push) | **bind** as channels; voice = stub |

## §8 documents

| Spec concern | Existing asset | Strategy |
|---|---|---|
| storage backends + encryption | SmartStorage (local/S3/Dropbox/GDrive, AES-GCM) | **use-as-is** |
| attach to any entity | `Media`/`DocumentAndNote` polymorphic + module-specific docs | **wrap** with a `documents` service + doc-type taxonomy table |
| system+custom categories | — | **build-new** doc-type table (seeded with spec list) |
| versioning | — | **build-new** (version chain table over stored files) |
| watermarking | — | **build-new** (PDF/image watermark on render/download) |
| view/download/print audit | `ss_access_logs` (when SmartStorage handles file) | **extend** to log at document layer for all access paths |
| e-signature | `clc_consents` + signatures | **reuse pattern** (extend to generic docs if needed) |

## §9 medical_core

| Spec entity | Existing asset | Strategy |
|---|---|---|
| patient (identity/contact) | `contacts` + `clc_patients` + `clc_patient_contact_details` | **extend**: add missing identity fields (national_id, marital, nationality, language…) on `clc_patients`; structured allergies/current-meds/insurance → new satellite tables |
| patient merge/dedup | — | **build-new** (merge service + confidence-scored duplicate detection) |
| patient export (FHIR/HL7/PDF) | — | **build-new** (PDF first; FHIR later phase) |
| encounter | `clc_appointments` (status lifecycle, logs, time tracking, erp_sell_id) | **extend**: encounter type enum (outpatient/telemedicine/home_visit/day_care…), priority, check-in/discharge times, structured diagnosis[] (ICD-10) table, parent_encounter link. Keep appointment=encounter model (proven in prod) rather than splitting entities |
| clinical notes (SOAP) | inline SOAP fields + `clc_soap_options` + confidential notes | **extend**: amendments/addenda + sign/lock + note types; templates via existing exam-template engine; voice hook via AiCore `AiTranscriber` |
| vitals | appointment vitals + `clc_vital_ranges` (+ specialty vitals migration) | **extend**: full standard set (BP, SpO₂, pain, glucose, GCS) as a proper `vitals` table with trend support; keep ranges engine |
| prescriptions | `clc_prescriptions/_items` + medicines + batches + controlled register | **extend**: refills, PRN, substitution flags; interaction-check hook point (Phase 4 engine) |
| orders (unified lab/imaging/procedure) | `clc_imaging_requests` (imaging), `lab_worklist` (lab) | **build-new thin unified `orders` layer** that fronts and routes to the existing flows via events; procedure/consultation order types new |
| scheduling / provider_schedules | `clc_doctor_schedules` + appointments + types/reasons + `ClcBookingDriver` + edit/change requests | **extend**: schedule exceptions, breaks, max-per-slot/overbooking, effective ranges; waitlist + queue mgmt build-new; booking sources partly exist (portal/public/API) |
| referrals | `referred_by` text only | **build-new** |
| problem list | `clc_medical_conditions` + `clc_patient_conditions` | **use-as-is**, minor extension (certainty, SNOMED optional) |
| medical alerts | allergies text + `is_critical` exam/vital flags + blocking-policy tables | **build-new** alert registry + banner surfacing across clinical screens (consume existing critical flags) |

## §10–12, §19 specialties (dental, derma, ophthalmology, radiology)

| Spec module | Existing asset | Strategy |
|---|---|---|
| dental | DentalClinic (tooth chart 1-32, surfaces, findings) + exam templates | **extend**: notation systems, periodontal/endo/implant fields, CDT treatment plans → grow `dental_*` tables; treatment-plan builder binds to `clc_treatment_packages` + billing |
| derma | DermatologyClinic + `clc_clinical_photos` | **extend**: lesion entity + body map (exam engine has `body_map` response type), photo compare; scoring (PASI…) as exam templates |
| ophthalmology | OphthalmologyClinic (`opth_patient_profiles`: VA/refraction/IOP) | **extend**: full eye exam entity, glasses Rx print, glaucoma/DR tracking; optical shop = ERP POS **bind** |
| radiology | `clc_imaging_requests/_modalities/_studies` + RadiologyClinic driver | **extend**: report entity (draft/preliminary/final/amended + critical-findings comms), modality worklist screen, dose fields; DICOM viewer/teleradiology later |
| diagnostic extras (ecg_echo, endoscopy, …) | modality rows + medical reports | **wrap** as order-type plugins (config) — mostly data, minimal code |

## §13–18, §21 inpatient/hospital

| Spec module | Existing asset | Strategy |
|---|---|---|
| bed_management | — (Emergency profile has ward/bed text fields) | **build-new** (wards/rooms/beds/reservations + board) |
| inpatient | — | **build-new** (admissions, MAR, care plans, fluid balance); reuse Rx/notes/vitals from medical_core |
| emergency | EmergencyClinic profile (triage, GCS, SpO₂, admission_status) | **extend** into er_visits entity + board; keep profile for history |
| surgery | appointment type `surgery` only | **build-new** (cases, OR rooms via org rooms, checklists) |
| icu | — | **build-new** (flowsheets); depends on inpatient |
| blood_bank | — | **build-new**; stock **binds** to ERP inventory (bags as batch-tracked items), screening **binds** to laboratory |
| ambulance/nicu/dialysis/physio/mortuary | PhysiotherapyClinic driver (ROM/strength) | physio **extend**; others **build-new mini-modules or registered stubs** (per plan P6-T7) |

## §17 laboratory

| Spec concern | Existing asset | Strategy |
|---|---|---|
| analyzer integration | LabCore (devices, sessions, results, analyte map, worklist) | **use-as-is** |
| clinic linkage | ClinicLab bridge columns | **use-as-is** |
| test catalog (pricing, panels, specimen reqs) | ERP `products` (type: lab tests exist in demo) + `lab_analyte_map` | **extend**: catalog table linking product_id (pricing/billing) ↔ analytes/panels/specimen requirements |
| specimen tracking (barcode, rejection, chain) | `lab_worklist` (sample_no) | **build-new** specimen entity around worklist |
| result validation workflow (tech→verify) | results land directly | **extend**: verified_by/status on results + worklist states |
| outreach management | — | **build-new** (external providers as `contacts` type supplier/customer — **bind**) |
| QC (Levey-Jennings/Westgard) | — | **build-new later** (flag as Phase 4 optional; not blocking release) |

## §20 pharmacy

| Spec concern | Existing asset | Strategy |
|---|---|---|
| dispensing against Rx | `clc_prescription_items` dispense fields + POS | **extend**: dispense workflow screen; stock deduction **bind** medicines.product_id → POS sell / stock adjust |
| medication stock (batch/expiry/FEFO) | ERP lot/expiry tracking (`purchase_lines.exp_date` etc.) | **use-as-is** + FEFO pick helper |
| controlled substances | `clc_controlled_stock_movements` register (witness, reconciliation) | **use-as-is** / extend reports |
| transfers between facilities | AdvancedTransfer module (3-stage) | **use-as-is** |
| retail POS | ERP POS | **use-as-is** |
| drug interaction engine | — | **build-new** hook + rule tables (optional module per preset) |
| external Rx intake/OCR | — | **build-new** (OCR optional via AiCore) |

## §22 billing

| Spec concern | Existing asset | Strategy |
|---|---|---|
| invoices/payments/receipts | `transactions` + `transaction_payments` + schemes/layouts | **use-as-is** (bind clinical charges to sell lines; `erp_sell_id` pattern proven) |
| charge capture from encounters/orders | appointment→sell link | **extend**: auto charge-capture service (orders/Rx/appointments → draft sell lines) |
| price lists (default vs insurance) | `selling_price_groups` + `variation_group_prices` | **extend**: price group per payer |
| insurance (payers, policies, claims, pre-auth, co-pay) | — | **build-new** (payer = `contacts`? No — dedicated payer table; claims reference transactions) |
| payment plans/collections | partial payments + pay terms + reminders | **wrap** |
| revenue analytics | ReportsModule + core reports | **extend** |

## §23 inventory

| Spec concern | Existing asset | Strategy |
|---|---|---|
| items/stock/movements/PO/suppliers | full ERP inventory + purchasing + PR/LandedCost | **use-as-is** |
| facility-scoped stores | `business_locations` + `variation_location_details` | **use-as-is** |
| batch/expiry/FEFO alerts | lot tracking + expiry flags | **use-as-is**; expiry-ladder report **extend** |
| consumption from clinical events | — | **build-new thin bridge** (clinical event → stock deduction via existing adjust/sell APIs) |
| auto-reorder → PO | reorder_level exists | **extend** small cron |

## §24 hr_payroll / §25 accounting

| Spec concern | Existing asset | Strategy |
|---|---|---|
| employees/attendance/leave/shifts/payroll | Essentials (+payroll groups) | **use-as-is** |
| duty rosters | `essentials_shifts` + user shifts | **extend** (visual roster, swap approval) |
| license/credential tracking + expiry alerts | — | **build-new** (shared with organization module credentialing) |
| chart of accounts / journals / reports | `accounts` + `account_transactions` (payment-level double entry) | **extend**: COA + journal layer posting from existing events (auto journal entries); full GL reports build on it |
| AR aging / AP | contact ledgers + purchase dues | **wrap** into accounting reports |

## §26 patient_portal

| Spec concern | Existing asset | Strategy |
|---|---|---|
| registration/OTP auth/devices/push | PortalApi (owners, OTP, magic links, tokens, push) | **use-as-is** |
| booking/reschedule/waitlist | BookingDriver + ClcBookingDriver | **extend** (reschedule/cancel/waitlist endpoints) |
| records access (results, Rx, vitals) | ClinicLab results + clc data (portal wiring partial) | **extend** API resources + "release to portal" flags |
| billing view/online payment | invoices exist; no gateway | **extend** (gateway = separate decision) |
| secure messaging / telemedicine / health tools | — (WhatsApp exists as channel) | **build-new** (Phase 8) |
| dependents (family) | — | **build-new** (owner ↔ multiple patients link) |

---

**Bottom line:** ~60% of the spec maps to *use-as-is / extend / wrap / bind*. The genuinely new builds are: organization satellite (facility profile/hierarchy, rooms, credentialing), module registry + presets + wizard, ABAC/data-scope layer, notification center + prefs, document taxonomy/versioning/watermark, unified orders + referrals + alerts + merge in medical_core, insurance/claims, specimen/validation/outreach in lab, drug-interaction engine, and the whole inpatient family (beds, admissions, ER board, surgery, ICU, blood bank) — plus patient-portal extensions and telemedicine.
