# SIFA Medical Specs — Compact Index (working reference)

> Machine-extracted condensation of [SIFA-MEDICAL-SPECS.md](../Shifa-one/SIFA-MEDICAL-SPECS.md) (3,255 lines) for Phase 0 gap analysis.
> The full spec remains the source of truth for field lists — always read the relevant spec section before implementing a task.

---

## 1. Business types & module presets

| Business type | Default modules | Optional modules |
|---|---|---|
| **hospital** | medical_core, scheduling, inpatient, outpatient, emergency, surgery, pharmacy, laboratory, radiology, bed_management, billing, inventory, hr_payroll, accounting, ambulance, icu, blood_bank, nicu, dialysis, physiotherapy, mortuary, all_specialty_modules | — |
| **polyclinic** | medical_core, scheduling, outpatient, pharmacy, laboratory, billing, inventory | radiology, all_specialty_modules |
| **single_clinic** | medical_core, scheduling, outpatient, billing | pharmacy, one_specialty_module_of_choice |
| **bioclinic** (multi-clinic brand; each facility enables its own specialties) | medical_core, scheduling, outpatient, billing, inventory | pharmacy, laboratory, all_specialty_modules |
| **laboratory** | medical_core, laboratory, billing, inventory | specimen_tracking, outreach_management |
| **imaging_center** | medical_core, radiology, scheduling, billing | teleradiology |
| **pharmacy** | medical_core, pharmacy, billing, inventory | drug_interaction_engine, insurance_claims |
| **dialysis_center** | medical_core, scheduling, dialysis, billing, inventory | — |
| **physiotherapy_center** | medical_core, scheduling, physiotherapy, billing | — |
| **diagnostic_center** | medical_core, laboratory, radiology, scheduling, billing, inventory | ecg_echo, endoscopy, pulmonary_function, audiometry, vision_testing |

**Setup wizard:** (1) pick facility type (the 10 above + Custom→manual selection) → (2) confirm pre-selected default + optional modules → (3) Confirm & Install triggers module installation.

## 2. Permissions model

- **Roles:** super_admin, facility_admin, department_head, doctor, nurse, pharmacist, lab_technician, radiologist, receptionist, billing_clerk, accountant, hr_manager, inventory_manager, patient.
- **ABAC examples:** doctor sees only assigned patients; nurse edits vitals not diagnosis; billing clerk cannot view clinical notes; pharmacist views Rx but not diagnoses.
- **Data scopes:** tenant / facility / department / own / custom.
- **Granularity:** module → feature → action → field → record.

## 3. Module: organization (deps: none)

- **tenant**: name/legal_name/registration_number/tax_id, logo+colors, timezone/locale/currency/date-time formats, address/contact/subscription JSON, status(active,suspended,trial,expired).
- **facility**: tenant_id, code unique/tenant, type(hospital,clinic,lab,imaging,pharmacy,dialysis,physio,diagnostic,other), parent_facility_id (nesting max depth 5), geo point, working_hours per day/dept, modules_enabled[], capacity(beds,daily_outpatient,daily_lab_samples,daily_imaging), status(active,inactive,under_construction).
- **department**: facility_id, parent_department_id, code, type(clinical,diagnostic,administrative,support), head_user_id, working_hours, modules_enabled[], settings, sort_order.
- **room**: department_id, type(consultation,operating,emergency,lab,imaging,pharmacy,waiting,admin,storage,other), floor, capacity, equipment[], status(available,occupied,maintenance,reserved), scheduling_enabled.
- **user_management**: CRUD, bulk CSV/Excel import, m2m assignment to facility/department/role, license tracking (number/expiry/certs/CE credits), credentialing (doc upload, verification workflow, expiry alerts), status(active,inactive,suspended,terminated,on_leave).

## 4. Module: module_registry (deps: none)

- **registry metadata**: id, semver, display_name, description, icon, category(core,medical,specialty,facility,support,integration), dependencies/optional_dependencies/conflicts_with, installable_per(tenant,facility,department), schema_version, author/license/changelog/docs.
- **Lifecycle**: install (validate deps → lock → pre-hooks → migrations → seed → register permissions/routes/events/menus → post-hooks → active; rollbackable) · uninstall (verify no dependents; archive/soft/hard data options) · update (compat check, incremental migrations, rollbackable) · pause/resume (hide UI, disable API, keep data) · soft-lock (reject new operations).
- **module_instance**: per tenant/facility settings as schema-validated JSONB with auto-generated settings UI.

## 5. Module: notifications (deps: none, per tenant)

- Channels: in_app (websocket, 90-day retention, read tracking, action buttons), email (smtp/sendgrid/ses/mailgun), sms (twilio/vonage/sns/smpp), push (fcm/apns/web_push), whatsapp (twilio/meta_cloud_api), voice_call (twilio).
- Event→notification mapping configurable per tenant (e.g. appointment.created → in_app+sms to patient; lab.result.ready → to ordering doctor & patient; invoice.overdue; bed.available).
- Per-user per-channel per-event preferences, quiet hours, digest (immediate/hourly/daily).
- Per-module editable templates with variables.

## 6. Module: documents (deps: none, per tenant)

- Storage backends: local/s3/azure/gcs/minio, AES-256 at rest, configurable per tenant.
- System doc types: patient_id_proof, insurance_card, consent_form, medical_report, lab_report, imaging_report, prescription, referral_letter, discharge_summary, invoice, receipt, contract, cv, license, certificate (+custom).
- Features: multi-upload, **versioning**, preview, OCR, auto-categorization, tagging, secure share links w/ expiry, e-signature (docusign/adobe/hellosign/internal), print formatting, bulk ops.
- Access: per document_type + patient_assignment + role; **dynamic watermarking with viewer info**; **audit trail of every view/download/print**.

## 7. Module: medical_core (deps: organization; per tenant)

- **patient**: patient_id auto-format, identity (names, DOB, sex enum, gender_identity, national_id/passport, blood_type, marital, nationality, language, photo), contact (+emergency_contacts[]), clinical baseline (allergies[] typed/severity/source/verified, chronic_conditions[] ICD-10, current_medications[], surgical/family history, social history enums, obstetric history), administrative (insurance[] provider/policy/copay/pre-auth/docs, referring_source, status active/deceased/transferred/inactive).
  Features: fuzzy+phonetic search, **merge with full logging**, **auto dedup detection (confidence score)**, export HL7/FHIR/C-CDA/CSV/PDF, portal link, QR/barcode wristbands.
- **encounter**: number, type(outpatient,inpatient,emergency,telemedicine,home_visit,day_care), status(scheduled,in_progress,on_hold,completed,cancelled,no_show), priority, check-in/start/end/discharge times, diagnosis[] (ICD-10, primary/secondary/differential, confidence), chief_complaint, parent_encounter_id. Features: timeline, auto summary, print, transfer, linking.
- **clinical_notes**: types(soap,progress,consultation,procedure,discharge,referral,follow_up,nursing,anesthesia,operative), SOAP jsonb structure, attachments, signed_by/at, amendments[], lock_after_sign, co-sign, auto-save 30s, versioning, **voice dictation**, AI assist (suggest ICD-10, draft assessment — never auto-submit).
- **vitals**: standard set (temp, HR+rhythm, BP+position/arm, RR, SpO2+supplemental O2, weight/height/BMI, pain 0-10, glucose+timing, GCS auto-total) + extended (waist, head circumference, peak flow, pediatric percentiles). Features: WHO/CDC growth charts, trends, configurable abnormal alerts, device import, batch ward entry.
- **prescriptions**: type(outpatient,inpatient,discharge), status(draft,active,completed,discontinued,expired,cancelled), items[] (form/route/frequency enums, refills, PRN, substitutions, dawa/ndc/atc codes), dispense_at_pharmacy_id. Features: drug DB + formulary, **interaction checker** (drug-drug/allergy/condition/food; contraindicated→block), dosage calculator (mg/kg, BSA, renal/hepatic, pediatric), templates, e-prescribing, controlled tracking, refill mgmt.
- **orders** (unified lab/imaging/procedure/consultation): items[] (LOINC/CPT, urgency routine/stat/asap/timed, laterality), status(ordered,collected,in_progress,resulted,verified,cancelled), results[] (ref range, abnormal_flag incl. critical, preliminary/final/corrected, verified_by). Features: order sets, favorites, duplicate detection, **critical value alert**, result acknowledgment, auto-verify normals.
- **scheduling**: appointment (type enum, status incl. checked_in/rescheduled, source walk_in/online/phone/referral/internal, room_id, service_id), **provider_schedule** (effective range, patterns[] day/start/end/slot/max_per_slot/overbooking/breaks/service_types/room, exceptions[]). Features: availability calendar, booking rules (min/max advance, new-vs-follow-up), waitlist, recurring, multi-provider, resource conflict detection, **queue management** (virtual queue, display boards, SMS updates, wait estimates), telemedicine link auto-gen, no-show tracking, analytics.
- **referrals**: internal/external in/out, urgency, clinical summary, requested services, status(sent…completed/rejected), response docs. Features: directory, tracking, incoming workflow, letter generation, HL7 REF, analytics.
- **problem_list**: ICD-10/SNOMED, type(diagnosis,symptom,finding,condition,risk_factor), status(active,resolved,chronic,recurrent), certainty, linked encounters/orders. Features: chronological view, auto-suggest from encounter diagnoses, SNOMED mapping.
- **medical_alerts**: allergy (red banner, acknowledge/override logged), drug interaction (severity escalation, senior ack), duplicate therapy, critical value (notify + escalate), fall risk, isolation, consent missing (blocks procedure), VTE risk. Config per tenant/facility/department: severity override, routing, escalation timing.

## 8. Specialty modules (deps: medical_core + scheduling; per facility)

- **dental**: dental_chart (fdi/universal/palmer, per-tooth status enum, restorations by surface/material, caries severity, periodontal probing/recession/BOP/mobility/furcation, endo status, implants, occlusion enum), dental_note (radiographs periapical/bitewing/panoramic/ceph/cbct/occlusal; CDT treatment plan w/ urgency+cost), dental_procedure_log (anesthesia, materials+lots, complications). Features: interactive tooth chart, panoramic/DICOM viewer, treatment-plan builder (cost + insurance preview + approval), recall system, dental inventory.
- **derma**: skin_examination (fitzpatrick, body_map jsonb w/ x-y lesions), skin_lesion (morphology/color/size/shape/border/surface/consistency enums, evolution, dermoscopy, biopsy), derma_note (topical/systemic/procedural/phototherapy plans). Features: body-map editor, photo comparison timeline, dermoscopy import, skin-cancer checklists (ABCDE), chronic scoring (PASI/EASI/DLQI/IGA), cosmetic log w/ batch tracking.
- **ophthalmology**: eye_examination (VA uncorrected/corrected/pinhole per eye, refraction sph/cyl/axis/add, IOP + method enum, pupils, slit lamp, fundus incl. cup/disc, EOM, visual field/OCT/topography JSON, Schirmer, TBUT). Features: glasses Rx + lab order, contact-lens fitting, glaucoma tracking (IOP trend, target IOP), diabetic-retinopathy grading (R0-R3/M0-M1), cataract workflow (biometry, IOL calc SRK-T etc.), optical shop POS.
- Summary specialties: cardiology (ECG viewer, EF trend, anticoagulation), orthopedics (joint diagram, implant registry), pediatrics (growth charts, immunization scheduler, mg/kg dosing), ob/gyn (EDD, ANC schedule, partogram), ENT (audiogram), neurology (seizure tracker), urology (IPSS, PSA velocity).

## 9. Inpatient / hospital modules (per facility)

- **bed_management** (deps: organization): ward (type enum incl. icu/nicu/picu/isolation, in_charge_nurse), bed (type incl. incubator/negative-pressure, equipment, current_status available/occupied/reserved/maintenance/blocked, cleaning_status), bed_reservation (for admission/transfer/surgery/step-down, expiry). Features: real-time visual bed board (drag-drop transfer), forecasting, turnover tracking, infection control (isolation, cohorting, proximity contact tracing).
- **inpatient** (deps: medical_core, bed_management): admission (type elective/emergency/transfer/maternity/observation, source, discharge type enum incl. absconded/expired, insurance_approval_number, room history), bed_assignment, nursing_care_plan (assessments w/ Braden/Morse scores, diagnoses/interventions/outcomes), **MAR** (scheduled vs administered, status given/held/refused/missed/delayed, witness), fluid_balance (intake/output/balance per shift auto-calc). Features: admission workflow, discharge workflow (med reconciliation, summary, follow-up, billing, bed release), ward dashboard, ISBAR shift handover, ward rounds.
- **emergency** (deps: medical_core): er_visit (arrival mode, triage level resuscitation…non_urgent w/ ESI/Manchester/CTAS, disposition incl. LWBS/AMA, key timing metrics), er_board (triage→to_be_seen→in_progress→pending_results→pending_disposition→admitted_awaiting_bed). Features: triage workflow + auto level suggestion, fast track, trauma activation, ER order sets per complaint, boarding management, ER metrics.
- **surgery** (deps: medical_core): surgical_case (team roles, procedures w/ CPT/laterality/ASA class/priority/est blood loss, consent gate, anesthesia type, scheduled vs actual OR/times, findings, complications, specimens→pathology, implants w/ serial/lot, blood products, status enum), or_room, pre_op_checklist (categories incl. NPO/site marking/antibiotic & DVT prophylaxis; nurse+anesthesiologist+surgeon sign-off), post_op_orders (diet/activity/IV/pain/DVT/drain/wound). Features: OR scheduling board (conflict detection, turnaround), WHO surgical safety checklist (mandatory Time-Out), sponge count w/ closure block, OR utilization analytics, implant registry w/ recall.
- **icu** (deps: medical_core, inpatient, bed_management): icu_admission (APACHE-II/SOFA scores, intensivist, ventilator mode enum, dialysis/isolation flags), **icu_flow_sheet** (hourly: neuro GCS/pupils/RASS, cardio HR/BP/MAP/CVP/CO/vasoactives, resp RR/SpO2/FiO2/PEEP/volumes/pressures/EtCO2, fluids, latest labs, drains, interventions), icu_daily_note (systems review, goals of care, sedation/weaning/antimicrobial plans). Features: ICU dashboard (patient strips, sparklines), ventilator weaning protocol + SBT, auto score calculation, rounds template, family communication log.
- **blood_bank** (deps: laboratory, inventory): blood_donation (donor, type, product, bag number, group/rh, screening HIV/HBV/HCV/syphilis, status incl. quarantined), crossmatch (antibody screen, method gel/tube/electronic, result), blood_issue (transfusion timing, **reaction workflow** w/ type/severity/management), blood_inventory (by group+product, reserved_for). Features: stock dashboard + min alerts, FIFO issuance + expiry warnings, demand forecasting, donor management (deferrals, recall), component preparation.
- **Mini-modules**: ambulance (vehicles, calls, run sheets, GPS dispatch), mortuary (body records, slots, release, death certificate workflow), dialysis (Rx, sessions, machine assignment, vascular access, Kt/V), physiotherapy (assessment, plans, sessions, exercise library, outcome measures), nicu (neonatal admission/flowsheet/nutrition, Fenton charts, Apgar), specimen_tracking (courier app, temperature excursion alerts).

## 10. Diagnostics & revenue modules

- **laboratory** (deps: medical_core; per facility): **test_catalog** (LOINC, category enum, specimen requirements w/ container/volume/temp/stability/fasting, result parameters w/ age/sex ref ranges + critical bounds, TAT, price, method), **specimen** (barcode, collection/receipt, **rejection reasons enum**, status chain, storage), **lab_result** (param results w/ abnormal flags, performed/verified split, preliminary/final/corrected), **culture** (media, growth, organisms, **antibiotic sensitivity S/I/R + MIC**). Features: barcode specimen tracking + chain of custody, analyzer integration (HL7/ASTM, auto-verification rules, Levey-Jennings/Westgard QC), worklists, QC module, **outreach management** (external providers, pickup scheduling, result delivery), analytics (TAT, rejection rate, revenue).
- **radiology** (deps: medical_core; per facility): imaging_order (modality enum incl. mammo/PET-CT/DEXA, views, contrast w/ creatinine + allergy checks, pregnancy status), imaging_study (DICOM study UID, accession, series[], radiation dose DAP/DLP/CTDIvol), imaging_report (structured findings, impression, **critical findings w/ communicated_to**, draft/preliminary/final/amended). Features: DICOM worklist/store/viewer (MPR, 3D), radiologist worklist (STAT first, priors comparison, voice dictation, BI-RADS/Lung-RADS templates), critical-value read-back + 30-min escalation, radiation safety (cumulative dose), modality-specific slots + prep instructions, teleradiology.
- **pharmacy** (deps: medical_core, inventory; per facility): pharmacy_prescription (dispense workflow fields, substitutions, batch, counseling), medication_stock (batch/expiry, temperature zone, controlled schedule I-V, status incl. recalled), stock_movement, pharmacy_transfer (request→approve→transit→receive). Features: 9-step dispensing workflow (FEFO batch), **retail POS interface**, inventory dashboards + expiry alerts, controlled-substance management (perpetual inventory, double verification, daily reconciliation, witnessed wastage), clinical pharmacy (TDM, med reconciliation, ADR reporting, antimicrobial stewardship), external Rx intake w/ OCR.
- **billing** (deps: medical_core; per tenant): **charge_capture** (encounter-linked items w/ CPT/HCPCS, performing provider, approval), invoice (charges, **insurance_coverage vs patient_responsibility**, balance due), payment (methods incl. mobile/insurance/waiver, refunds), **insurance_claim** (types, item-level allowed/approved/denied, copay/deductible, status draft→submitted→…→appealed, EDI 837P/837I, ERA/835 auto-posting, denial management, pre-auth tracking), price_list (default vs insurance price, effective dates). Features: manual+automatic charge entry from orders/Rx, claim scrubbing, patient statements, online payment, payment plans, collections, revenue analytics (days-in-AR, denial rate), multi-currency, tax rules.
- **inventory** (deps: organization; per facility): item (category enum drug/supply/reagent/…, min/max/reorder/lead time, expiry/batch/serial/temperature flags), stock (per facility+location, reserved vs available), stock_movement (type enum incl. consumed/patient_return), purchase_order (partial receiving), supplier (rating, terms). Features: dashboards, **auto-reorder → PO**, stock take w/ barcode + variance, FEFO + expiry ladder (90/60/30/15/7), demand forecasting, multi-location transfers, module integrations (pharmacy deduct, lab reagents, radiology contrast, surgery implants, ward supplies).

## 11. Back office & portal

- **hr_payroll** (deps: organization; per tenant): employee (employment type incl. locum/volunteer, grade, pay frequency, bank/tax JSON, probation), attendance (biometric/rfid/manual/gps, scheduled vs actual, overtime), leave (types, multi-level approval), payroll (allowances[]/deductions[], auto gross/net, payslips), shift + staff_scheduling (swap w/ approval, no-show). Features: leave balances/encashment, visual roster + auto-schedule (skill match, min rest), batch payroll runs + register, performance (KPI, appraisals, 360), compliance (license expiry alerts, mandatory training, credentialing status).
- **accounting** (deps: organization; per tenant): chart_of_accounts (hierarchical codes, types), journal_entry (lines w/ cost centers, draft/posted/reversed), AR (aging 30/60/90/120), AP (bills, approval), financial reports (BS, P&L, cash flow, trial balance, GL, departmental P&L). Features: **auto journal entries** (patient/insurance payment, payroll, purchase, expense), bank reconciliation, cost centers, budgets w/ variance, period open/close, audit trail.
- **patient_portal** (deps: medical_core; per tenant): self-registration w/ OTP/national-ID, login (password/OTP/biometric), **dependents (family)**; appointments (view/book/reschedule/cancel/waitlist/history); records (notes after release, lab w/ ranges, imaging reports, Rx, vitals trends, allergies/problems, download PDF/structured, **temporary share with another provider**); secure messaging, notifications, education; billing (invoices, online payment, history, insurance info, cost estimates); documents (upload ID/insurance/consents); telemedicine (video join, chat, virtual waiting room); health tools (symptom checker triage, medication reminders, wellness tracking weight/BP/glucose, PHQ-9/GAD-7 questionnaires).
