agdar/multidisciplinary_django_prompt_1.md
2025-11-02 14:35:35 +03:00

344 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Tenhal Multidisciplinary Healthcare Platform — Django Build Prompt (StepbyStep)
**Goal:** Build a productionready Django project that implements the PRD for a multidisciplinary clinic (Medical, Nursing, ABA, OT, SLP) with the full patient journey (registration, files/subfiles 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, pertenant 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 & followup【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/Checkin, 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 MDF1, Followup MDF2, 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 OTF1, Session Note OTF3, TargetSkills with 010 scoring graph) ←【26†files_in_root_directory】【27†files_in_root_directory】
- `slp` (Consult variants SLPF1, Assessment/Reassessment SLPF2, Intervention SLPF3, Progress SLPF4) ←【29†files_in_root_directory】【28†files_in_root_directory】【30†files_in_root_directory】【31†files_in_root_directory】
- `referrals` (Interdiscipline 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 humanreadable 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, servicespecific), 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** (optin).
### 1.5 `nursing` — MDNF1
- **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` — MDF1 & MDF2
- **MedicalConsultation** (MDF1) 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** (MDF2): links to MDF1; 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` — ABAF1
- **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` — OTF1, OTF3
- **OTConsult**: reasons (multiselect), 3 top difficulty areas (text), developmental motor milestones, selfhelp skills matrix, feeding participation, infant/now behavior descriptors, recommendation (continue/discharge/referral with rules)【26†files_in_root_directory】.
- **OTSession** (OTF3): date, type (Consult/Individual/Group/ParentTraining), cooperative_level (14), distraction_tolerance (14), checklist of “Today we work on …”, target skills with 010 scoring, observations, activities, recommendations【27†files_in_root_directory】.
- **OTTargetSkill** (session child).
### 1.9 `slp` — SLPF1/F2/F3/F4
- **SLPConsult** (base) + subtype flags (ASD/LanguageDelay/Fluency): primary_concern, suspected_areas, type_of_service (Consult/Eval/Intervention/ParentTraining), communication modes, screen time, and pervariant questionnaires and skillstoobserve matrices with oralmotor screening【29†files_in_root_directory】.
- **SLPAssessment** (F2): diagnosis statement, case history; prenatal/perinatal/postnatal; developmental; medical status; speech/language detail incl. GFTA3/JAT, SSI scores, oral mechanism, language skills via Rossetti scale domain/age levels; jointattention skills (present/absent) summaries; clinical summary; recommendations (frequency 12x/wk, 4560 mins), plan & referral rules【28†files_in_root_directory】.
- **SLPIntervention** (F3): session number/time; `Target#1/2` entries with SOAP (Subjective/Objective/Assessment/Plan) + prompt strategies; add “preview previous SLPF3” relation【30†files_in_root_directory】.
- **SLPProgressReport** (F4): 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 crispyforms 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/yesno fields.
- Inline formsets for medication rows (Medical) and target skills (OT/SLP).
- Nursing form autocomputes BMI; Growth chart linkage is readonly plot placeholder.
- Add custom clean methods: e.g., **consent required** before certain consults; **family satisfaction** 0/50/100 choices on followup.
---
## Phase 3 — `views.py` (ClassBased 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.
- SLPF3 “preview previous session” drawer.
- Permissions: `UserPassesTestMixin` by role; objectlevel by tenant.
- History: expose version timeline via simplehistory.
**Appointment state machine handlers:** Confirm → Reschedule → Cancel/NoShow → Arrive → Start → Complete; autoemit 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 integrationneeded 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 010 (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 eclaims, ZATCA einvoicing, and Consent esignature verification endpoints.
> Create serializers/viewsets/routers **only** for these apps:
1. **appointments.api**
- Endpoints: list/create/confirm/reschedule/cancel/arrive/start/complete; patientsafe subset; provider calendar feed (readonly).
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 webonly (Django templates).
- Use `drf-spectacular` to autogenerate 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 T24h, T12h; daily reconciliation; lab/rad polling (if needed).
---
## Phase 8 — Admin, RBAC, Auditing
- Django Admin for all models with search filters.
- Perrole 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 autocreated; 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 MDF1 saves all sections; MDF2 pulls previous MDF1 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 010 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 previoussession 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 & ratelimits.
- All forms & pages available in Arabic & English; RTL layout verified.
---
## Implementation Notes
- Prefer `ArrayField`/join tables for multiselect checklists depending on reporting needs.
- Store percent scales as `PositiveSmallIntegerField`.
- For “graph history” (OT/SLP targets), persist timeseries 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**
---
## Integrations Addendum — Insurance e-Claims (NPHIES), ESignature, and ZATCA EInvoicing
> This addendum augments Phases 1, 5, 6, 7, and Acceptance Criteria with concrete integration targets.
### A) Insurance eClaims (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 external `Encounter`, `Claim` ids.
- `PayerContract`: payer code, credentials, endpoints, flags (eligibility, pa, claims).
**Phase 5 — Templates:**
- Add payer selection and eclaims buttons on Appointment/Finance pages: *Check Eligibility*, *Submit PreAuth*, *Submit Claim*, *Post Payment*.
- FHIR JSON viewer modal for last request/response.
**Phase 6 — DRF Endpoints (`integrations.api.nphies`)** *(expose only whats 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_client` service: 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) ESignature for Consent Forms
**Phase 1 — Models (augment `core`):**
- `Consent`: add `signature_method` (Drawn/Typed/Uploaded/External), `signature_image` (file), `signature_hash`, `signed_ip`, `signed_user_agent`, `signed_by_name`, `signed_at`.
- Optional `ConsentVersion` to 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.api` minimal 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 EInvoicing (FATOORA — Phase 2)
**Scope:** Compliant einvoices/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 EInvoice*, *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.
---