# Tenhal Multidisciplinary Healthcare Platform — Django Build Prompt (Step‑by‑Step) **Goal:** Build a production‑ready Django project that implements the PRD for a multidisciplinary clinic (Medical, Nursing, ABA, OT, SLP) with the full patient journey (registration, files/sub‑files per clinic, appointments, consents, finance, notifications), plus structured clinical documentation and progress tracking. **Approach:** Implement in **clear phases**: (1) `models.py`, (2) `forms.py`, (3) `views.py`, (4) `urls.py`, (5) templates. Add **DRF** only for the apps that must expose/consume external integrations (Appointments, Notifications, Referrals, Smart Lab & Radiology stubs). **Constraints:** Django 5.x, Python 3.12, Postgres, HTMX + Bootstrap/ColorAdmin templates, Arabic/English i18n, per‑tenant support (extendable), RBAC, audit trails, strong typing. > Reference forms & flows used to derive entities and fields: ABA consult【22†files_in_root_directory】; Medical consult & follow‑up【23†files_in_root_directory】【24†files_in_root_directory】; Nursing vitals【25†files_in_root_directory】; OT consult & session notes【26†files_in_root_directory】【27†files_in_root_directory】; SLP consult, assessment, intervention, progress report【29†files_in_root_directory】【28†files_in_root_directory】【30†files_in_root_directory】【31†files_in_root_directory】; Patient/appointment flow【7†files_in_root_directory】. --- ## Phase 0 — Project & App Scaffold 1. **Create project & core apps** - Project: `clinic_platform` - Apps: - `core` (User, Tenant, Patient, Consent, Files/SubFiles, Attachments, AuditLog) - `appointments` (Clinics, Schedules, Booking, Reminders, Arrival/Check‑in, Status machine) - `finance` (Invoices, Payments, Packages, Payer; light for now) - `notifications` (SMS/WhatsApp/email gateway abstraction + outbox/receipt) - `nursing` (Vitals, Anthropometrics, Allergies) ← map to Nursing Form【25†files_in_root_directory】 - `medical` (Consultation MD‑F‑1, Follow‑up MD‑F‑2, Medications, Complaints) ←【23†files_in_root_directory】【24†files_in_root_directory】 - `aba` (Consult, Functional Interview, Behaviors, Antecedents/Consequences, Recommendations) ←【22†files_in_root_directory】 - `ot` (Consult OT‑F‑1, Session Note OT‑F‑3, TargetSkills with 0‑10 scoring graph) ←【26†files_in_root_directory】【27†files_in_root_directory】 - `slp` (Consult variants SLP‑F‑1, Assessment/Reassessment SLP‑F‑2, Intervention SLP‑F‑3, Progress SLP‑F‑4) ←【29†files_in_root_directory】【28†files_in_root_directory】【30†files_in_root_directory】【31†files_in_root_directory】 - `referrals` (Inter‑discipline referrals; external provider placeholder) - `integrations` (Smart Lab, Radiology stubs; webhooks; DRF client helpers) 2. **Settings** - Installed apps, `AUTH_USER_MODEL=core.User` (extend `AbstractUser`), `LANGUAGES` = ar/en, `USE_I18N`, `USE_TZ`. - `REST_FRAMEWORK` basic config (only for APIs we expose). - Static/media, `django-storages` ready hook (optional). 3. **Libraries** - `django-filter`, `django-htmx`, `django-crispy-forms`, `django-simple-history` (audit), `django-phonenumber-field`, `django-money`, `drf-spectacular`, `django-environ`, `whitenoise` (if not behind nginx), `django-anymail` (optional). 4. **Conventions** - Use `TextChoices` for enumerations. - Use UUIDs for all primary keys; add human‑readable IDs where the forms expect e.g. File #. - Use `simple_history` to track edits on clinical documents; include `created_by`, `updated_by`, `signed_at` (for consents). --- ## Phase 1 — `models.py` (All Apps) > Create models **first** for all apps. Keep them cohesive and minimal, closely mirroring the uploaded forms. ### 1.1 `core` - **Tenant** (optional now, add `name`, `code`). - **User** (extends `AbstractUser`; fields: `tenant`, `role` = Admin/Doctor/Nurse/OT/SLP/ABA/FrontDesk/Finance). - **Patient**: MRN (generated), national_id, first/last (ar/en), DOB, sex, contacts, caregiver, address, `tenant`. - **Clinic** (if not in `appointments`): name, specialty (Medical/OT/SLP/ABA/Nursing). - **File** (main) & **SubFile** (per clinic) reflecting flow【7†files_in_root_directory】. - **Consent**: type (general treatment, service‑specific), signed_by, signed_at, files. - **Attachment**: generic FK to any document (PDFs, images). - **AuditLog**: generic model or use `simple_history` across models. ### 1.2 `appointments` - **Provider** (FK User), **Room**, **Timeslot** (RRULE or simple weekly template), **Appointment**: - patient, clinic, provider, service, status (`BOOKED`, `CONFIRMED`, `RESCHEDULED`, `CANCELLED`, `NO_SHOW`, `ARRIVED`, `IN_PROGRESS`, `COMPLETED`). - confirmation_at, arrival_at, start_at, end_at; reschedule reason; cancel reason. - Links to notifications, finance clearance, and consents per PRD/flow【7†files_in_root_directory】. ### 1.3 `finance` (lightweight) - **Invoice**, **LineItem** (service/package), **Payment** (method, amount, txn_id), **Clearance** flag on Appointment. - **Package** (e.g., SLP/OT bundle sessions per PRD future enhancement). ### 1.4 `notifications` - **Message**: channel (SMS/WhatsApp/Email), template_code, payload, status, sent_at, provider_response_id. - **Subscription/Preference** (opt‑in). ### 1.5 `nursing` — MD‑N‑F‑1 - **NursingEncounter**: patient, appointment?, filled_by, height_cm, weight_kg, head_circ_cm, bmi (calc), vitals (hr_bpm, bp_sys, bp_dia, rr, spo2, crt enum `<2s`/`>2s`), pain_score_0_10, allergy flags + text, observation【25†files_in_root_directory】. ### 1.6 `medical` — MD‑F‑1 & MD‑F‑2 - **MedicalConsultation** (MD‑F‑1) with sections: chief_complaint, present_history, past_history, vaccination, family_history, social_history, pregnancy/neonatal history, developmental history (motor/language/social/cognitive milestones), medications (inline through related model), behavioral_symptoms checklist, physical_exam (structured), summary, recommendations; link Smart Lab/Radiology placeholders【23†files_in_root_directory】. - **MedicationPlan**: drug_name, dose, frequency enum (Daily/BID/TID/Other), compliance (Good/Partial/Bad), gains, side_effects, target_behavior, improved flag. - **MedicalFollowUp** (MD‑F‑2): links to MD‑F‑1; previous complaints (status enum Resolved/Static/Worse), new_complaints, vital_link (to Nursing), assessment, recommendations, family_satisfaction (0/50/100), medication table snapshot【24†files_in_root_directory】. ### 1.7 `aba` — ABA‑F‑1 - **ABAConsult**: reason_of_referral (with radio options), parental_concern, school_concern; respondents, interviewer, diagnosed, interaction_hours; physiological/medical factors (booleans + text); behaviors (1..n) with frequency enum Hourly/Daily/Weekly/Less, duration, intensity enum (Mild/Moderate/Severe), antecedents (likely/least likely contexts), recommendations【22†files_in_root_directory】. - **ABABehavior** (child of ABAConsult). ### 1.8 `ot` — OT‑F‑1, OT‑F‑3 - **OTConsult**: reasons (multi‑select), 3 top difficulty areas (text), developmental motor milestones, self‑help skills matrix, feeding participation, infant/now behavior descriptors, recommendation (continue/discharge/referral with rules)【26†files_in_root_directory】. - **OTSession** (OT‑F‑3): date, type (Consult/Individual/Group/ParentTraining), cooperative_level (1‑4), distraction_tolerance (1‑4), checklist of “Today we work on …”, target skills with 0‑10 scoring, observations, activities, recommendations【27†files_in_root_directory】. - **OTTargetSkill** (session child). ### 1.9 `slp` — SLP‑F‑1/F‑2/F‑3/F‑4 - **SLPConsult** (base) + subtype flags (ASD/LanguageDelay/Fluency): primary_concern, suspected_areas, type_of_service (Consult/Eval/Intervention/ParentTraining), communication modes, screen time, and per‑variant questionnaires and skills‑to‑observe matrices with oral‑motor screening【29†files_in_root_directory】. - **SLPAssessment** (F‑2): diagnosis statement, case history; prenatal/perinatal/postnatal; developmental; medical status; speech/language detail incl. GFTA‑3/JAT, SSI scores, oral mechanism, language skills via Rossetti scale domain/age levels; joint‑attention skills (present/absent) summaries; clinical summary; recommendations (frequency 1‑2x/wk, 45‑60 mins), plan & referral rules【28†files_in_root_directory】. - **SLPIntervention** (F‑3): session number/time; `Target#1/2` entries with SOAP (Subjective/Objective/Assessment/Plan) + prompt strategies; add “preview previous SLP‑F‑3” relation【30†files_in_root_directory】. - **SLPProgressReport** (F‑4): demographic snapshot; sessions scheduled/attended; final diagnosis; objectives & progress (% accuracy), plan (continue/add/fade prompts/generalization), overall progress, participation, attendance, carryover, prognosis, recommendations with package & sessions count; reassessment tick【31†files_in_root_directory】. - **SLPTarget** (for Intervention/Progress objective linkage). ### 1.10 `referrals` & `integrations` - **Referral**: from_app, to_app, reason, urgency, status; auto rules (e.g., ASD→Pediatrician)【26†files_in_root_directory】【28†files_in_root_directory】【29†files_in_root_directory】. - **ExternalOrder** (lab/radiology placeholder): order_type, payload, status, result_url. > Add common mixins: `TimeStampedModel`, `OwnedByTenant`, `ClinicallySignable` (who/when), `SoftDelete` (optional). Add `__str__` and unique constraints. Add sensible DB indexes (patient/date/status). --- ## Phase 2 — `forms.py` - Build **ModelForms** per clinical document, grouping fields exactly per sections in the uploaded forms. - Use crispy‑forms helpers, Arabic labels/help_text from the forms. - Widgets & validations: - MultiSelect for checklists (e.g., SLP communication modes; OT reasons). - Enum radios for intensity/frequency/yes‑no fields. - Inline formsets for medication rows (Medical) and target skills (OT/SLP). - Nursing form auto‑computes BMI; Growth chart linkage is read‑only plot placeholder. - Add custom clean methods: e.g., **consent required** before certain consults; **family satisfaction** 0/50/100 choices on follow‑up. --- ## Phase 3 — `views.py` (Class‑Based Views + HTMX) - Use CBVs: `ListView`, `DetailView`, `CreateView`, `UpdateView`, `DeleteView` per entity. - HTMX partials for: - Appointment confirm/reschedule/cancel/arrive transitions. - Session target rows add/remove. - Medication rows add/remove. - SLP‑F‑3 “preview previous session” drawer. - Permissions: `UserPassesTestMixin` by role; object‑level by tenant. - History: expose version timeline via simple‑history. **Appointment state machine handlers:** Confirm → Reschedule → Cancel/No‑Show → Arrive → Start → Complete; auto‑emit notifications per transition (using `notifications` app). --- ## Phase 4 — `urls.py` - Namespaced per app: `core:`, `appointments:`, `medical:`, `nursing:`, `aba:`, `ot:`, `slp:`, `finance:`, `notifications:`, `referrals:`. - HTMX endpoints postfix `-partial`. - DRF routers (only for integration‑needed apps; see Phase 6). --- ## Phase 5 — Templates (Bootstrap/ColorAdmin, Arabic/English) - Base layout with RTL/LTR switch; nav by role. - **Patient detail hub** with tabs: Overview, Appointments, Nursing, Medical, ABA, OT, SLP, Attachments, Audit. - **Form pages** mirror paper forms (group boxes/headings same as originals). - **Charts**: OT/SLP target progress 0–10 (ApexCharts or Chart.js). - **Appointment calendar** (weekly grid, filters by clinic/provider). - **Notifications outbox** list with status badges. - **Audit timeline** component. --- ## Phase 6 — DRF (Only Where External Interaction Is Required) > Create serializers/viewsets/routers **only** for these apps: 1. **appointments.api** - Endpoints: list/create/confirm/reschedule/cancel/arrive/start/complete; patient‑safe subset; provider calendar feed (read‑only). 2. **notifications.api** - Outbound message create (system only), delivery webhook receiver; message status update. 3. **referrals.api** - Create referral (internal/external); query referral status. 4. **integrations.api** - **Smart Lab** order create & result callback stubs; **Radiology** order create & result callback stubs (from MD forms)【23†files_in_root_directory】【24†files_in_root_directory】. > No DRF for internal clinical documents unless required. Keep those web‑only (Django templates). - Use `drf-spectacular` to auto‑generate OpenAPI; secure with token/KeyAuth. - Filtering & pagination via `django-filter` and LimitOffsetPagination. - Throttling on public endpoints. --- ## Phase 7 — Signals, Services, Tasks - Signals: on Appointment status → enqueue Notification; on Patient create → create main File; on SubFile create → link clinic. - Services: `notifications.send(template_code, to, ctx)` provider adapters; `appointments.scheduler`. - Tasks (Celery ready): reminder T‑24h, T‑12h; daily reconciliation; lab/rad polling (if needed). --- ## Phase 8 — Admin, RBAC, Auditing - Django Admin for all models with search filters. - Per‑role permissions matrix (read/create/update/delete per app). - `simple_history` views to diff old/new values. - Export to CSV/PDF (basic). --- ## Phase 9 — Tests & QA - Model tests for constraints and choices. - Form validation tests (critical paths). - View & permissions tests (role coverage). - DRF API tests for appointments/notifications/referrals/integrations. - i18n toggle & RTL smoke tests. - E2E: book → confirm → arrive → consult → intervention → progress → invoice. --- ## Deliverables & Order of Work (Do **not** skip order) 1) **Models** for all apps (with enums, indexes, FKs, on_delete rules, `__str__`); migrations. 2) **Forms** (ModelForms + inline formsets; crispy; i18n labels). 3) **Views** (CBVs + HTMX partials; permission mixins; state transitions). 4) **URLs** (namespaced; DRF routers only for selected apps). 5) **Templates** (ColorAdmin/Bootstrap; RTL/LTR; dashboards and detail tabs). 6) **DRF** (appointments/notifications/referrals/integrations only). 7) **Signals/Services/Tasks** (notifications, scheduler, reminders). 8) **Admin/RBAC/Audit**. 9) **Tests**. 10) **Docs** (README with .env, run scripts, role matrix). --- ## Acceptance Criteria (Samples) - New patient create → main File auto‑created; clinic SubFile created upon first appointment. - Appointment lifecycle reflects all states with timestamps & emits notifications. - Nursing form captures vitals & computes BMI; growth chart displays. - Medical MD‑F‑1 saves all sections; MD‑F‑2 pulls previous MD‑F‑1 summary/plan and medication snapshot; family satisfaction captured【24†files_in_root_directory】. - ABA consult holds behaviors with frequency/intensity and antecedents; recommendations saved【22†files_in_root_directory】. - OT consult and session notes support 0‑10 target scoring and “Today we work on …” checklist【26†files_in_root_directory】【27†files_in_root_directory】. - SLP consult variants render correct questionnaires; SLP assessment stores Rossetti domains and SSI; intervention supports SOAP & prompt strategies with previous‑session preview; progress report aggregates sessions and produces goals with % accuracy【29†files_in_root_directory】【28†files_in_root_directory】【30†files_in_root_directory】【31†files_in_root_directory】. - DRF exposes only appointments/notifications/referrals/integrations with auth & rate‑limits. - All forms & pages available in Arabic & English; RTL layout verified. --- ## Implementation Notes - Prefer `ArrayField`/join tables for multi‑select checklists depending on reporting needs. - Store percent scales as `PositiveSmallIntegerField`. - For “graph history” (OT/SLP targets), persist time‑series per session; templates render charts. - Keep lab/radiology as integration stubs now—model `ExternalOrder` with state; wire later to real providers. - Wrap enums and label text in `gettext_lazy`. - Add demo fixtures for dev (do not include PHI). --- **End of Prompt**