22 KiB
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
- 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)
- Project:
- Settings
- Installed apps,
AUTH_USER_MODEL=core.User(extendAbstractUser),LANGUAGES= ar/en,USE_I18N,USE_TZ. REST_FRAMEWORKbasic config (only for APIs we expose).- Static/media,
django-storagesready hook (optional).
- Installed apps,
- 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).
- Conventions
- Use
TextChoicesfor enumerations. - Use UUIDs for all primary keys; add human‑readable IDs where the forms expect e.g. File #.
- Use
simple_historyto track edits on clinical documents; includecreated_by,updated_by,signed_at(for consents).
- Use
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_historyacross 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】.
- patient, clinic, provider, service, status (
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/2entries 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,DeleteViewper 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:
UserPassesTestMixinby 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)
Now includes NPHIES e‑claims, ZATCA e‑invoicing, and Consent e‑signature verification endpoints.
Create serializers/viewsets/routers only for these apps:
-
appointments.api
- Endpoints: list/create/confirm/reschedule/cancel/arrive/start/complete; patient‑safe subset; provider calendar feed (read‑only).
-
notifications.api
- Outbound message create (system only), delivery webhook receiver; message status update.
-
referrals.api
- Create referral (internal/external); query referral status.
-
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-spectacularto auto‑generate OpenAPI; secure with token/KeyAuth. - Filtering & pagination via
django-filterand 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_historyviews 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)
- Models for all apps (with enums, indexes, FKs, on_delete rules,
__str__); migrations. - Forms (ModelForms + inline formsets; crispy; i18n labels).
- Views (CBVs + HTMX partials; permission mixins; state transitions).
- URLs (namespaced; DRF routers only for selected apps).
- Templates (ColorAdmin/Bootstrap; RTL/LTR; dashboards and detail tabs).
- DRF (appointments/notifications/referrals/integrations only).
- Signals/Services/Tasks (notifications, scheduler, reminders).
- Admin/RBAC/Audit.
- Tests.
- 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
ExternalOrderwith 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
Integrations Addendum — Insurance e-Claims (NPHIES), E‑Signature, and ZATCA E‑Invoicing
This addendum augments Phases 1, 5, 6, 7, and Acceptance Criteria with concrete integration targets.
A) Insurance e‑Claims (NPHIES — HL7 FHIR R4)
Scope: Eligibility, Prior Authorization, Claims, Payment Notice/Reconciliation via nphies central hub (FHIR R4.0.1).
Artifacts: Use FHIR resources (CoverageEligibilityRequest/Response, PriorAuthorization via Claim/ClaimResponse, Claim, PaymentNotice, PaymentReconciliation).
Environment: External base URL and security handled via OAuth2/mTLS per payer guidance (store credentials in env).
Phase 1 — Models (augment integrations app):
NphiesMessage:direction(OUTBOUND/INBOUND),resource_type,fhir_json(JSONField),status(QUEUED/SENT/ACK/ERROR),correlation_id,response_http_status,error_code,error_message.NphiesEncounterLink: FK to Patient/Appointment, stores pointers to externalEncounter,Claimids.PayerContract: payer code, credentials, endpoints, flags (eligibility, pa, claims).
Phase 5 — Templates:
- Add payer selection and e‑claims buttons on Appointment/Finance pages: Check Eligibility, Submit Pre‑Auth, Submit Claim, Post Payment.
- FHIR JSON viewer modal for last request/response.
Phase 6 — DRF Endpoints (integrations.api.nphies) (expose only what’s needed):
POST /api/integrations/nphies/eligibility→ takes patient, coverage, service, returns CoverageEligibilityResponse snapshot.POST /api/integrations/nphies/prior-auth→ creates Claim (PA) and polls for ClaimResponse.POST /api/integrations/nphies/claims→ submit Claim for episode (Appointment/Consult), store ClaimResponse.POST /api/integrations/nphies/payment-reconcile→ fetch PaymentReconciliation (optional if payer supports pull).- Webhook receiver for asynchronous responses (optional if supported).
Phase 7 — Services/Tasks:
nphies_clientservice: build FHIR bundles from internal models; sign & transmit; retry with exponential backoff.- Celery tasks for long-running PA/Claim polling and reconcile jobs.
Acceptance Criteria (add):
- Can perform eligibility check from Appointment and see structured FHIR response stored in
NphiesMessage. - Can submit PA/Claim; status reflected on Finance/Appointment with last response snapshot.
- Errors and payer warnings visible in UI and audit trail.
B) E‑Signature for Consent Forms
Phase 1 — Models (augment core):
Consent: addsignature_method(Drawn/Typed/Uploaded/External),signature_image(file),signature_hash,signed_ip,signed_user_agent,signed_by_name,signed_at.- Optional
ConsentVersionto freeze HTML/PDF at time of signing.
Phase 5 — Templates:
- Consent modal with canvas signature (JS) + typed fallback; capture name, IP, timestamp; render bilingual text.
- “View Signed PDF” action (HTML-to-PDF export with embedded signature image, hash, and audit footer).
Phase 6 — DRF (if external signing provider later):
consents.apiminimal endpoints to verify signature hash and fetch signed PDF (internal only by default).
Phase 7 — Services:
signature_service: compute hash of consent terms + signer metadata; persist; generate PDF artifact; optional webhooks to DMS.
Acceptance Criteria (add):
- User can sign consent on first visit; signed artifact is immutable, downloadable, and auditable.
- Consent requirement enforced before certain consults.
C) ZATCA E‑Invoicing (FATOORA — Phase 2)
Scope: Compliant e‑invoices/notes (XML/UBL with required fields), QR (TLV), Clearance (B2B) and Reporting (B2C), CSR/CSID lifecycle, simulation & production gateways.
Phase 1 — Models (augment finance & integrations):
EInvoice: FK Invoice,uuid,xml_payload,qr_base64,clearance_status(PENDING/CLEARED/REJECTED/REPORTED),zatca_document_type,submission_mode(CLEARANCE/REPORTING),response_payload,error_code,error_message.ZatcaCredential: compliance/production CSIDs, certs/keys storage refs, environment flag (SIMULATION/PRODUCTION).
Phase 5 — Templates:
- Invoice detail: Generate E‑Invoice, Submit to ZATCA, View QR, Download XML, status badge.
- Printing: render QR and mandatory fields on invoice PDF.
Phase 6 — DRF (integrations.api.zatca):
POST /api/integrations/zatca/prepare→ build signed XML + QR (TLV).POST /api/integrations/zatca/submit→ send to FATOORA (reporting or clearance), store response.POST /api/integrations/zatca/onboard→ CSR → CSID (simulation/compliance/production flows).- Webhooks for async notifications (if applicable).
Phase 7 — Services/Tasks:
zatca_signer: XML signing, canonicalization, hash; QR TLV encoder.zatca_client: submit to correct gateway (simulation/compliance/production); retry & error mapping.- Nightly reconciliation job for reporting compliance.
Acceptance Criteria (add):
- Able to onboard in simulation: generate CSR, obtain CSID, submit sample invoices and receive acceptance/warnings.
- Live submission updates
EInvoice.clearance_status; QR appears on PDF; errors visible and traceable. - Invoices reported within required SLA windows.