# Shifa One — Existing Features Inventory (P0-T1)

> Phase 0 deliverable of [SIFA-MEDICAL-PLAN.md](../Shifa-one/SIFA-MEDICAL-PLAN.md).
> Purpose: know exactly what the platform already provides so Phases 1–8 build **only what is missing**.
> Companion docs: [REUSE-MAP.md](REUSE-MAP.md) (P0-T2), [GAP-LIST.md](GAP-LIST.md) (P0-T3), [TENANCY-PERMISSIONS-AUDIT.md](TENANCY-PERMISSIONS-AUDIT.md) (P0-T4).

The platform is a multi-tenant Laravel SaaS ERP (UltimatePOS-derived core, "Static ERP") + ~80
nwidart modules. Shifa One is the human-medical edition running the ERP core + the **ClinicCore**
clinical platform (45 specialty plugins) + LabCore/ClinicLab + WhatsApp/AiCore/Essentials, etc.

---

## 1. Core ERP (app/)

### 1.1 Tenancy

| Concern | Existing asset |
|---|---|
| Tenant | `App\Business` (`business`) — currency, tax, fiscal year, accounting method (FIFO/LIFO/AVCO); JSON: `enabled_modules`, `email_settings`, `sms_settings`, `common_settings` |
| Branch / facility | `App\BusinessLocation` (`business_locations`) — address, per-location invoice scheme/layout, payment accounts, price group. **Leaf level — no nesting** |
| Department | **Not in core** (ClinicCore has `clc_departments` — see §2) |
| Scoping | Manual `where('business_id', …)` in controllers + `SetSessionData` middleware; **no global scopes** |
| Location ACL | `permission.location.{id}` + `access_all_locations`; `User::permitted_locations()` |
| Provisioning | `/business/register` → `BusinessController::postRegister` → `BusinessUtil::newBusinessDefaultResources()` (admin/cashier roles, walk-in customer, invoice scheme/layout, default unit, notification templates) |

### 1.2 Auth & permissions

- Guards: `web` (session, `App\User`), `api` (Passport OAuth2), `customer` (session guard for `App\Contact` portals).
- **Spatie laravel-permission**; roles carry `business_id` and are name-scoped per tenant (`Admin#1`).
- Granularity today: module-level + action-level (`customer.view / view_own / create / update / delete`), location-level (`permission.location.{id}`), "own records" pattern (`*.view_own` via `created_by` / `user_contact_access`).
- **No field-level or record-attribute (ABAC) engine in core.**

### 1.3 Contacts (customers & suppliers)

- `App\Contact` (`contacts`): `type` customer/supplier/both, tax number, address, mobile/landline/alternate, pay terms, `contact_status`, soft-deletes, polymorphic `DocumentAndNote`.
- **No person-level clinical fields** (DOB/gender/blood group) in core — ClinicCore extends via 1:1 `clc_patients`.
- `App\CustomerGroup` for pricing/discount grouping.

### 1.4 Products & inventory

- `App\Product` → `ProductVariation` → `Variation` (single/variable/combo), brand/category/sub-category/unit, tax inc/exc, `enable_stock`, `alert_quantity`.
- Per-location stock: `variation_location_details` (qty on hand, reorder level).
- **Batch/lot + expiry**: `purchase_lines.mfg_date/exp_date`, lot allocation on sell/adjust (`lot_no_line_id`), business flags `enable_product_expiry`, `expiry_type`; POS expiry alerts.
- Stock ops: transfers (`sell_transfer`/`purchase_transfer`), adjustments (+lot-aware lines), opening stock; sub-units (`base_unit_id` chains).
- Price lists: `selling_price_groups` + `variation_group_prices` (fixed/percent), permission-gated per group.
- Purchasing: purchase / purchase_order / purchase_return transaction types; Modules add PR workflow (PurchaseRequisition + LandedCost) and 3-stage transfer (AdvancedTransfer).

### 1.5 Sales / invoicing / payments (billing backbone)

- Unified `App\Transaction` (`transactions`) — types: sell, purchase, expense, stock_adjustment, transfers, opening_*, sell_return, purchase_return, payroll, sales_order, purchase_order; statuses: draft/final/pending/ordered/…
- Sell lines `transaction_sell_lines` (line discounts, line tax, lot allocation, modifier children); quotations, drafts, suspended sells, **recurring invoices/subscriptions** (`is_recurring`, `recur_*`).
- Invoice numbering `invoice_schemes` + printable `invoice_layouts` per location.
- Payments: `transaction_payments` — multiple/partial, methods per location (`default_payment_accounts`), payment proof `document`, refunds via `parent_id`; events (`TransactionPaymentAdded`…).
- Accounts: `accounts` + `account_transactions` (debit/credit double-entry sync via `AccountTransactionUtil`).
- Taxes: `tax_rates` incl. tax groups; time-bound `discounts`; reward points fields on transactions.
- **No insurance concept anywhere in core** (payer, claims, co-pay, pre-approval → gap).

### 1.6 HR in core

Minimal: `users` (business_id, user_type, is_active, language) + commission agent & service-staff pointers on transactions. Real HR lives in **Essentials** module (see §3).

### 1.7 Notifications (core)

- `notification_templates` per business & event (`new_sale`, `payment_received`, `payment_reminder`, `new_booking`, …) with `email_body` / `sms_body` / `whatsapp_text`, subject, cc/bcc, auto-send flags per channel.
- Dispatch: `NotificationUtil::autoSendNotification()` with tag replacement (`{contact_name}`, `{invoice_number}`, …); event-triggered; scheduled commands (`AutoSendPaymentReminder`, `RecurringInvoice`, …).
- Channels: Email (SMTP per business), SMS (pluggable provider config), WhatsApp (link-based in core; **real delivery via WhatsApp module**, see §3).
- **No in-app notification center, no digest options, no per-module template registry** (templates are a fixed `template_for` list).

### 1.8 Documents & media (core)

- `App\Media` — polymorphic file attachments (file/base64 upload, delete), `uploaded_by`.
- `App\DocumentAndNote` — polymorphic documents+notes with media, activity-logged.
- **No versioning, no watermarking, no view/download/print audit trail, no per-tenant storage driver config in core** (SmartStorage module covers driver pluggability + encryption — see §3).

### 1.9 Settings

- Business-level JSON settings on `business`; per-location settings on `business_locations`; global key-value `App\System` (`system` table — also used for module version gates `{module}_version`).
- **No JSON-schema-driven per-module settings UI** — each module hand-rolls its settings screens.

### 1.10 Key utility classes

| Class | Purpose |
|---|---|
| `app/Utils/ModuleUtil.php` | module availability checks, cross-module data aggregation (`getModuleData`) |
| `app/Utils/TransactionUtil.php` | transaction creation, invoice numbers, payment tracking |
| `app/Utils/BusinessUtil.php` | tenant provisioning, fiscal year |
| `app/Utils/ProductUtil.php` | product/variation/pricing helpers |
| `app/Utils/NotificationUtil.php` | template dispatch (email/SMS/WA) |
| `app/Utils/ContactUtil.php` | contact CRUD, credit limit |
| `app/Utils/AccountTransactionUtil.php` | double-entry sync |

---

## 2. Clinical platform (Modules/)

### 2.1 ClinicCore (`clc_*`, ~60 models, 100+ migrations)

The shared human-medical engine. Patient identity = **`App\Contact` ↔ 1:1 `clc_patients`**.

| Spec concern | Existing asset |
|---|---|
| Patient master | `clc_patients` (contact_id 1:1, gender, dob, blood group, allergies, chronic_conditions, family_history, weight/height, photo, status) + `clc_patient_contact_details` (emergency contact, occupation, referred_by, email confirm) |
| Providers | `clc_doctors` (user_id nullable, department, specialization, consultation_fee) |
| Departments | `clc_departments` (business-scoped, icon, status) + `clc_clinic_locations` (→ `business_locations`) |
| Encounters | `clc_appointments` = appointment+encounter combined: ref_no, date/time/duration, type (checkup/vaccination/surgery/emergency/other), status lifecycle (pending→confirmed→in_progress→completed / cancelled / no_show) with `clc_appointment_status_logs` audit, time tracking, `erp_sell_id` billing link |
| SOAP notes | Inline on appointment: soap_subjective/objective/assessment/plan/investigations/lab_exam/plan_meds(JSON) + `clc_soap_options` vocabularies + `clc_confidential_notes` |
| Vitals | temp/HR/RR/weight on appointment + `clc_vital_ranges` (life-stage-aware critical alerting) + specialty vital columns |
| Structured exams | `clc_exam_templates` / `_items` (select/multi/grade/measurement/text/yes_no/body_map, normal+critical bounds, lateralisation) / `clc_appointment_exam_findings` (severity 0-3, is_critical, snapshots) + AI-suggest/voice-fill toggles in `clc_exam_settings` |
| Prescriptions | `clc_prescriptions` + `_items` (dosage/frequency/duration/route, dispense tracking) + `clc_medicines` (controlled_schedule, product_id link) + `clc_medicine_batches` |
| Controlled drugs | `clc_controlled_stock_movements` — insert-only register, running balance, witness, serials |
| Vaccinations | `clc_vaccine_types`, `clc_vaccinations` (next-due, waived, reminders) |
| Orders: imaging | `clc_imaging_requests` (modality, priority routine/urgent/stat, status requested→in_progress→reported) + `clc_imaging_modalities` (XR/US/CT/MR/ENDO) + `clc_imaging_studies` (files, DICOM linked) |
| Orders: lab | via ClinicLab → `lab_worklist` (see 2.2) |
| Problem list | `clc_medical_conditions` (ICD code, is_chronic) + `clc_patient_conditions` (onset, active/resolved/inactive) |
| Reports | `clc_medical_reports` (lab/xray/ultrasound/ecg/other, attachments JSON) |
| Consents | `clc_consent_templates` / `clc_consents` / `clc_consent_signatures` (multi-party digital signature, verify token) |
| Treatment plans | `clc_treatment_packages` / `clc_patient_treatment_plans` / `clc_treatment_plan_sessions` (multi-session courses, billing via product) |
| Wellness/membership | `clc_wellness_plans` / `_benefits` / `_subscriptions` (→ ERP recurring transactions) / `_benefit_usage` |
| Scheduling | `clc_doctor_schedules` (weekly working hours + slot_duration) + appointment types/reasons + edit-request & doctor-change-request workflows + blocking policy tables |
| Reminders | `clc_reminder_settings` / `_templates` / `_logs` (appointment/vaccination/wellness via sms/email/whatsapp) |
| Quality | `clc_evaluations` + questions/responses (patient satisfaction, flag & review) |
| Photos/docs | `clc_clinical_photos`, `clc_appointment_documents` |
| Access grants | `clc_authorized_vets` (explicit per-patient access), `clc_role_landing_pages`, `clc_role_settings` |
| Module settings | `clc_module_settings` (business-scoped key/value toggles) |
| Specialty registry | `clc_specialties` — **45 seeded specialties**; data-driven; structural ones carry `driver_key` + capabilities JSON |

Key services: `SpecialtyDriverRegistry`, `AppointmentService`, `PrescriptionService`, `VaccinationService`, `ClinicCapabilities`, `ControlledStockSyncService`, `Services/Booking/ClcBookingDriver`.

### 2.2 LabCore + ClinicLab (`lab_*`)

- `lab_agents` / `lab_devices` (NX600/Abaxis/IDEXX, TCP/serial) / `lab_test_sessions` / `lab_test_results` (analyte, ref ranges, abnormal flags) / `lab_worklist` / `lab_analyte_map` (vendor→canonical + default ranges) / comm & error logs / `lab_settings`.
- ClinicLab bridge adds `clc_patient_id` + `clc_appointment_id` to worklist/sessions; order→result→notify loop (`clinicwa:notify-lab-results`).
- **Absent vs spec:** no billable test catalog with panels/pricing, no specimen collection/rejection tracking, no formal result validation (tech→pathologist) workflow, no outreach (external provider) management.

### 2.3 Specialty driver pattern (45 modules)

`ClinicSpecialtyDriver` contract → registered in `SpecialtyDriverRegistry`: `patientProfileModel()`, form/show/appointment Blade fragments, `persistPatientProfile()`, `examTemplateSeeds()`, `terminology()`, optional `capabilities()`/`aiGuidance()`.

Structural drivers with own tables: **Dental** (`dental_patient_profiles`, `dental_tooth_findings` — 32-tooth chart, surfaces M/O/D/B/L), **Ophthalmology** (`opth_patient_profiles` — VA, sphere/cyl/axis, IOP), **Radiology** (`radiology_patient_profiles` + imaging workflow), **Emergency** (`emergency_patient_profiles` — triage green/yellow/orange/red, GCS, SpO₂, er/admitted/icu/discharged), **Physiotherapy** (ROM, MRC strength, goals), **Dermatology** (fitzpatrick/skin type). Remainder are config-only rows in `clc_specialties`.

### 2.4 Portals & public booking

- **PortalApi** (`portal_*`): patient accounts (`portal_owners`, password optional), OTP challenges (bcrypt hash, attempts, expiry), magic tokens, hashed bearer tokens, devices, web-push subscriptions, per-business `portal_brands` (public_booking + booking_otp toggles), feature toggles. **BookingDriver registry** (vertical-agnostic; `ClcBookingDriver` for `medical_clinic` — computes slots from `clc_doctor_schedules`).
- **ClinicStaffPortal**: staff PWA tokens keyed to ERP `users` (no parallel accounts) + push.
- **ClinicSite** (`cs_*`): public clinic website (sites/pages/media/messages) with booking widget.
- **ClinicWhatsApp**: `clinicwa:send-recalls` (appointments + vaccine boosters), `clinicwa:notify-lab-results`.

### 2.5 Clinical gaps confirmed (feed GAP-LIST)

Patient merge/dedup · drug-interaction rule engine · separate medical-alert registry (allergies are a text field) · referral management · telemedicine/virtual visits · **insurance/coverage anywhere** · DICOM viewer · Rx e-signature · automated order routing rules · medication reconciliation · financial-clearance enforcement · unified orders entity (lab and imaging are separate flows; no generic "procedure order").

---

## 3. Module infrastructure & support modules

### 3.1 Module system (nwidart/laravel-modules v9)

| Concern | Existing mechanism |
|---|---|
| Discovery / on-off | `modules_statuses.json` (host-wide, `FileActivator`) + `bootstrap/cache/{slug}_module.php` provider caches |
| Manifest | `module.json`: name, alias, description, active, order, `providers`, `files`, **`requires`** (dependencies) |
| Per-tenant enablement | **Superadmin subscriptions**: `subscriptions.package_details` JSON keyed by module flags; gate = `ModuleUtil::hasThePermissionInSubscription($business_id, '{key}_module', 'superadmin_package')` (app/Utils/ModuleUtil.php:152-189); falls back to *allow* when Superadmin absent (single-tenant mode) |
| Module flag declaration | each module's `DataController::superadmin_package()` returns its package keys — aggregated by Superadmin package builder UI |
| Install/version gate | `system` table `{module}_version` row via module `InstallController` (`/install`, `/install/update`, `/install/uninstall`); `ModuleUtil::isModuleInstalled()` = `Module::has()` **and** version row |
| Permissions | created in module migrations via Spatie `Permission::create()`; exposed to role UI via `DataController::user_permissions()` |
| Menus | `AdminSidebarMenu` middleware calls every module's `DataController::modifyAdminMenu()` (nwidart/laravel-menus `Menu::modify('admin-sidebar-menu', …)`), each gated by its subscription check |
| Global asset injection | `DataController::get_additional_script()` → collected by `AppServiceProvider` view composer into all layouts (NeoSkin pattern; no core edits) |
| Events/cron | ServiceProvider `boot()` — `Event::listen()`, `$schedule->command(...)` |
| Quotas | `ModuleUtil::isQuotaAvailable()` — package limits (location_count, user_count, product_count, invoice_count) |
| Per-module settings | ad-hoc: JSON columns on `business` (e.g. `essentials_settings`) or `system`/`clc_module_settings` key-value. **No JSON-schema auto-generated settings UI** |

### 3.2 Support modules

- **Essentials (HR)**: `essentials_leaves/_leave_types/_holidays/_attendance` (shift-aware clock in/out, auto-clock-out cron), `essentials_shifts` + `essentials_user_shifts` (duty roster), `essentials_payrolls` + allowances/deductions (+ payroll groups), reminders/todos/messages/knowledge base, employee documents + shares. **Absent:** multi-level leave approval, license/credential tracking, appraisals.
- **WhatsApp**: `wa_channels` (per-location; **Meta Cloud API** + WhatsApp-Web/QR drivers), `wa_templates` (variable placeholders), `wa_messages` (status log), conversations, auto-replies, AI responder (AiCore). Service API for other modules: `WaSender` / `WaNotifier`.
- **SmartStorage**: `ss_files` (logical→backend path; local/S3/Dropbox/GDrive/default drivers; **AES-GCM at-rest encryption**), OTP-gated access, `ss_access_logs` (read/write/delete/denied + IP/geo/device). **Absent:** versioning, watermarking.
- **AiCore**: `ai_providers` (per-business provider/model/budget, business_vertical), `ai_usage_logs`, prompts, feedback; `AiClient` failover; tool registry.
- **ActivityLog**: `enhanced_activity_logs` — before/after JSON snapshots per create/update/delete, sensitive-field masking, request-scoped grouping (`ActivityLoggerService`).
- **Connector/TPConnector**: Passport `auth:api` REST (products, contacts, sells…; OAuth login → Bearer).
- **PortalApi/VrcPortalApi pattern**: stateless per-request tenant/DB resolution middleware; hashed bearer tokens keyed to ERP users (staff) or portal owners (customers) + entitlement & Spatie permission checks in middleware.
- **SaasSwitcher**: multi-project host — per-project DB connections, session-selected, middleware switches default connection. **DemoLogin**: env-gated role-card quick login.
- **NeoSkin**: reference implementation of the asset-injection seam + per-tenant theme in `system` key-value.

### 3.3 Infra gaps confirmed (feed GAP-LIST)

Central module registry **table/catalog with per-facility/department instances** (today: host JSON + per-business subscription flags only) · schema-driven per-module settings UI · in-app notification center with per-user channel/event preferences, quiet hours, digests · unified `notify()` facade across channels (email/SMS exist in core, WA in module, but no single event→channel router) · document versioning/watermarking/doc-type taxonomy · setup wizard with business-type presets · facility hierarchy & departments as first-class core-adjacent entities · rooms/resources · ABAC + data-scope permission layer.

