05-documentswave: W2filled3 citations

Treatment Plan Templates — Structured Care Plans

Audiences: doctor, clinical-buyer, developer

Treatment Plan Templates — Structured Care Plans

Doctors define structured treatment plan templates — sections, expected outputs, and locale — that the AI summarization engine uses to generate consistent, clinic-specific care plans from clinical encounter data.

Business Purpose

Without structured templates, AI-generated treatment plans are freeform and clinic-specific expectations are lost. The treatment-plan-template module lets clinic admins define a library of reusable templates: which sections a plan must contain (e.g. "Diagnosis Summary", "Medication Plan", "Follow-up Schedule"), what output format to expect (PDF, MARKDOWN, JSON), and the plan's locale. When TUCAN or the document generation engine produces a treatment plan, it resolves the appropriate template for the org/locale pair and uses it to structure the output.

The system mirrors the summarization template pattern in the doxing module — same Prisma model shape, same status lifecycle, same ensureDefault() seeding mechanism. This design lets the AI pipeline apply consistent clinical logic regardless of which org runs it.

Commercial value: standardized treatment plans improve documentation quality, satisfy health insurer requirements for structured care records, and reduce the cognitive load on doctors who currently write plans from scratch.

Audiences

  • Investor: Structured treatment plans are a gateway to automated reimbursement documentation — a key unlock for GKV (statutory health insurance) billing automation. Template library differentiates Dudoxx HMS from generic AI scribing tools.
  • Clinical buyer (doctor/nurse/receptionist): Doctors see the clinic's standard sections pre-filled when creating a treatment plan. Templates can be set as clinic defaults or published for specific specialties. Admins publish/archive templates without developer involvement.
  • Developer/partner: TreatmentPlanTemplateController + TreatmentPlanTemplateService — standard NestJS CRUD with lifecycle endpoints (publish, archive, ensureDefault). organizationId is always derived from the Trusted Gateway tenant context (X-Clinic-IDreq.clinicId); never from the client payload. Write endpoints require @RequireAdminRole().
  • Internal (ops/support): ensureDefault() is an idempotent seeding endpoint — it creates a default template for an org/locale if none exists, deduplicates multiple defaults, and can be called safely during tenant provisioning. Status lifecycle: DRAFT → PUBLISHED → ARCHIVED.

Architecture

diagram
documents/treatment-plan-template/
├── treatment-plan-template.controller.ts  — REST CRUD + lifecycle endpoints
├── treatment-plan-template.module.ts      — Module wiring
├── services/
│   └── treatment-plan-template.service.ts — Business logic, org ID resolution, dedup
└── dto/
    └── treatment-plan-template.dto.ts     — CreateDto, UpdateDto, ResponseDto,
                                             ExpectedSectionDto, OutputFormatValue, TemplateStatusValue

Prisma model: DocumentTreatmentPlanTemplate in prisma-main (ddx_api_main). Key fields:

FieldTypePurpose
organizationIdStringTenant scoping
localeString"de" / "en" — resolved on template lookup
nameStringTemplate display name
descriptionString?Optional admin notes
sectionsJsonArray of ExpectedSectionDto (section name + instructions)
outputFormatSummarizationOutputFormatPDF, MARKDOWN, JSON
statusSummarizationTemplateStatusDRAFT, PUBLISHED, ARCHIVED
isDefaultBooleanOne active default per org/locale
isActiveBooleanSoft-delete flag

Status lifecycle:

FromTransitionTo
DRAFTadmin publishesPUBLISHED
PUBLISHEDARCHIVED

ensureDefault() creates in DRAFT; the caller must publish.

Only PUBLISHED + isActive=true templates are selected for document generation. ARCHIVED templates are preserved for audit but not used in new plan generation.

Tech Stack & Choices

ConcernChoiceRationale
StorageDocumentTreatmentPlanTemplate in prisma-mainCo-located with other document models; org-scoped via organizationId
Auth@RequireAdminRole() on write endpointsOnly SUPER_ADMIN / CLINIC_ADMIN manage templates; doctors use them read-only
Org resolutiongetOrganizationIdOrThrow(req) — derives from req.clinicIdNever trusts organizationId from request body; Trusted Gateway pattern
Default seedingensureDefault(orgIdOrSlug, locale) — idempotentCalled during tenant provisioning; safe to call repeatedly
Output formatsSummarizationOutputFormat enum (PDF, MARKDOWN, JSON)Reuses the same enum as summarization templates for pipeline consistency
SectionsExpectedSectionDto[] JSON columnFlexible section schema without schema migrations; each section has name + instructions for the AI
DeduplicationensureDefault() degrades multiple defaults to onePrevents multiple defaults from conflicting in template resolution

Data Flow

Template resolution for AI document generation

  1. TUCAN document generation tool calls TreatmentPlanTemplateService.ensureDefault(orgId, locale) → gets or creates the default template.
  2. If a PUBLISHED + isDefault=true template exists for { organizationId, locale }, it is returned immediately.
  3. AI engine reads the sections JSON → uses each section's name + instructions as a structured prompt to the LLM.
  4. Output is formatted per outputFormat and returned as the generated treatment plan.

Admin creates a template

  1. Admin calls POST /treatment-plan-templates with CreateTreatmentPlanTemplateDto (name, sections, locale, outputFormat).
  2. getOrganizationIdOrThrow(req) extracts organizationId from req.clinicId (Trusted Gateway).
  3. TreatmentPlanTemplateService.create() writes row with status: DRAFT, isActive: true, isDefault: false.
  4. Admin calls PATCH /treatment-plan-templates/:id/publish → status changes to PUBLISHED.
  5. Admin calls PATCH /treatment-plan-templates/:id/set-defaultisDefault = true; any previous default for same { organizationId, locale } is unset.

EnsureDefault (tenant provisioning)

  1. Tenant provisioner calls POST /treatment-plan-templates/ensure-default with { locale: "de" }.
  2. TreatmentPlanTemplateService.ensureDefault(orgId, "de"):
    • Queries for existing PUBLISHED + isDefault + isActive templates for the org/locale.
    • If found and count > 1: degrades extras to isDefault = false, returns preferred.
    • If none found: creates a platform default template in DRAFT status with Dudoxx's standard German clinical sections.
  3. Returns the active default template.

Implicated Code

  • ddx-api/src/documents/treatment-plan-template/treatment-plan-template.controller.ts:1TreatmentPlanTemplateController; @RequireAdminRole() on write endpoints; getOrganizationIdOrThrow(req) helper at :60; @ApiTags('Treatment Plan Templates')
  • ddx-api/src/documents/treatment-plan-template/services/treatment-plan-template.service.ts:29TreatmentPlanTemplateService; ensureDefault() at :57 — idempotent default creation with dedup logic at :76–82
  • ddx-api/src/documents/treatment-plan-template/services/treatment-plan-template.service.ts:34resolveOrganizationIdOrThrow() — resolves both UUID and slug to org UUID via Prisma OR query
  • ddx-api/src/documents/treatment-plan-template/dto/treatment-plan-template.dto.tsCreateTreatmentPlanTemplateDto, UpdateTreatmentPlanTemplateDto, ExpectedSectionDto (section name + instructions), OutputFormatValue, TemplateStatusValue
  • ddx-api/src/documents/treatment-plan-template/treatment-plan-template.module.tsTreatmentPlanTemplateModule; TreatmentPlanTemplateService provider; PrismaModule import

Operational Notes

  • Idempotent provisioning: POST /treatment-plan-templates/ensure-default can be called multiple times during tenant setup. It only creates a template if no PUBLISHED + isDefault + isActive template exists. Safe to include in the seeder pipeline.
  • Multiple defaults deduplication: If the database somehow accumulates multiple default templates for the same org/locale (schema migration edge case), ensureDefault() automatically degrades extras. The most-recently-updated template wins.
  • Org slug resolution: resolveOrganizationIdOrThrow() accepts both UUID and clinic slug (e.g. "ddx-hamburg-clinic"). This matches the org service convention used throughout the platform.
  • Sections schema: sections is a Json Prisma field — the ExpectedSectionDto[] shape is validated in the DTO layer but not enforced at the DB level. Future schema changes (adding a required: boolean field to sections) are non-breaking.
  • AI integration: Treatment plan template sections are consumed by TUCAN document generation tools and the document-generation module. The outputFormat field controls which renderer is invoked (PDF → ddx-pdf-engine, MARKDOWN → raw text, JSON → structured data).
  • Validation commands: pnpm tsc:check (ddx-api); pnpm prisma:generate:all if DocumentTreatmentPlanTemplate model changes.
  • Document Management — uses treatment plan templates to structure AI-generated care plan documents; generated treatment plans are stored as PatientDocument records in ddx_api_main
  • Doxing — OCR and Summarization — sibling template system (SummarizationTemplate) follows the same pattern; shares SummarizationOutputFormat and SummarizationTemplateStatus enums
  • FHIR ResourceFacade — FHIR CarePlan resources map to treatment plan instances (not templates); templates are Prisma-only