Skip to main content
Version: 3.1

Report & Templates

Technical reference for the Template and ReportUpload models in Care EMR. A Template holds the Jinja2 body and the render options for one report type. A ReportUpload is one generated report file, made from a template for one encounter, patient or account. See the report template concept for the plain-language view.

Source:

The Template field tables follow the Pydantic resource specs and the request bodies of the API.

Models​

ModelPurpose
ReportUploadOne generated report file. It links to its template and to one encounter, patient or account. The file is stored in the report storage bucket.
TemplateA report definition: Jinja2 body, report type, data context, default format and render options. It belongs to one facility, or it is instance-wide when facility is empty.

ReportUpload fields​

FieldTypeNotes
templateFK → Template (PROTECT)The template used. A template that has reports cannot be deleted.
nameCharField(2000)<template name>-<associating_id>-<timestamp in ms>, set at generation.
report_typeCharField(50)The report type key. The access checks use it.
associating_idCharField(100)UUID of the encounter, patient or account.
upload_completedBooleanFieldDefault False. Set to true after the file upload to the report storage bucket.
is_archivedBooleanFieldDefault False.
archive_reasonTextFieldBlank allowed.
archived_datetimeDateTimeField, nullableThe time of archiving.
archived_byFK → User (PROTECT), nullableThe user who archived the report.

The record also stores who generated the report, the file format and the time of generation.

The model declares files_manager = S3FilesManager(BucketType.REPORT), so the file goes to the report storage bucket.

Retrieving one report returns read_signed_url, a signed download link that is valid for one hour. A PDF file opens in the browser (inline). An HTML file downloads (attachment).

Template fields​

Write fields (create and update)​

FieldTypeRequiredDefaultNotes
namestrYes——
statusTemplateStatusOptionsYes—See TemplateStatusOptions values.
default_formatTemplateFormatOptionsYes—Selects the generator whose options model validates options. Generate uses it when the request has no output_format.
descriptionstrNo""—
optionsdictNoEmptyValidated against the options model of default_format. Unknown keys are rejected. See Template output options.
facilityUUID4 | NoneNoNoneFacility external ID. On create, an empty value makes the template instance-wide. On update, a value replaces the template's facility, and an empty value keeps it. Retrieve returns the facility as an object; the list leaves it out.
slug_valueSlugTypeYes—See Slug rules.
template_datastrYes—The Jinja2 template body. Returned only when you retrieve one template.
template_typestrYes—A registered report type. See Report types.
contextstrYes—A registered data context, built on the same kind of record as template_type. See Data contexts.

An update (PUT) uses the same fields and rules as a create. Send every required field again, including slug_value, template_type and context.

Read responses also include slug_config, the parts of the stored slug.

TemplateStatusOptions values​

ValueEffect
draftCannot generate a report.
activeThe only status that can generate a report.
retiredCannot generate a report.

TemplateFormatOptions values​

ValueOutput
pdfWeasyPrint converts the rendered HTML to PDF. The HTML sanitizer does not run on it.
htmlThe rendered HTML goes through the report HTML sanitizer.

Report types​

template_type takes one of these keys. They are the only report types registered in Care core.

KeyDisplay nameGenerated forContext
discharge_summaryDischarge SummaryEncounterencounter_base
encounter_reportEncounter ReportEncounterencounter_base
patient_summaryPatient SummaryPatientpatient_base
account_reportAccount ReportAccount (billing account)account_base

The report type and the context must have the same associating model (template_type.associating_model equals context.__associating_model__). The schema endpoint lists the supported contexts for each report type.

Slug rules​

  • slug_value has 5 to 50 characters.
  • It contains only letters, numbers, hyphens and underscores, and it starts and ends with a letter or a number (pattern ^[a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9]$).
  • The slug is unique within its facility, or among the instance-wide templates. The check ignores case.
  • Care stores the slug with a prefix: f-<facility external id>-<slug> for a facility template, i-<slug> for an instance-wide template.
  • The API addresses a template by its stored slug, with the prefix, not by its id (lookup_field = "slug").

Facility and instance-wide templates​

  • A template with a facility belongs to that facility. A template with no facility is instance-wide.
  • A list request with facility returns only that facility's own templates: the facility filter is an exact match and runs after the queryset, so instance-wide templates are dropped. The frontend always sends facility, so no screen lists instance-wide templates.
  • For who can write each kind, see Template actions.

Validation messages​

ConditionMessage
template_type is emptyReport Type is required
template_type is not registeredInvalid report type
context is emptyReport Type is required (the same text as for template_type)
context is not registeredInvalid report type or context. The context registry returns None for an unknown context, so the Invalid Context type branch does not run.
Report type and context are built on different recordsReport Type and Context are not compatible
slug_value does not match the patternSlug must contain only URL-safe characters (letters, numbers, hyphens, and underscores). It must start and end with alphanumeric characters.
The slug is already in useSlug already exists.
options has an unknown keyRejected by the options model (extra="forbid").

Template output options​

The keys that options accepts depend on default_format.

HTML options​

OptionTypeDefault
wrap_documentboolFalse
titlestr"Report"
charsetstr"utf-8"

PDF options​

OptionTypeDefault
page_size"A4", "A3", "A5", "Letter" or "Legal""A4"
marginstr"1cm"
orientation"portrait" or "landscape""portrait"
stylesheetsList of CSS stringsEmpty list

A PDF without its own stylesheets gets default CSS: the page_size, orientation and margin from the options, DejaVu Sans at 12pt, and tables with borders. Stylesheets that you supply replace this default CSS.

Data contexts​

A template reads data through one context. The template variable is the name that the template uses for the record.

ContextDisplay nameRecordTemplate variable
encounter_baseEncounter ReportEncounterencounter
patient_basePatient ReportPatientpatient
account_baseAccount ReportAccountaccount

Every generated report also gets current_user, the user who asked for the report. A preview gets a sample user. A user value has full_name and id.

encounter_base top-level fields​

FieldData
statusThe encounter status. Planned, in progress, completed, cancelled and entered in error have their own labels. Other statuses show the raw value in title case (on_hold shows as On_Hold).
encounter_class, priority, start_time, end_time, hospitalization, discharge_summary_advice, external_identifier, extensions, encounter_tags, care_team, current_location, organizations, facility_identifiers, patient_facility_tagsOther top-level fields of the context.
patientThe patient of the encounter.
facilityname, description, address, pincode, phone_number.
diagnosesConditions of category encounter_diagnosis recorded in this encounter. Each has clinical_status, severity, verification_status, name, onset and note. The list can be filtered by clinical status and verification status (include or exclude).
symptomsConditions of category problem_list_item recorded in this encounter. The symptom API stores symptoms in this category. Each has clinical_status, severity, verification_status, name, onset, note, created_by and updated_by.
diagnostic_reportsDiagnostic reports linked to this encounter, filterable by status. Each has title (the display of its code), status, category, observations, conclusion, note, service_request (with title) and file_uploads (name and url of the files that are not archived).
allergy_intolerancesAllergy intolerances recorded in this encounter. Each has clinical_status, category, verification_status, criticality, name, note, last_occurrence and allergy_intolerance_type.
medication_prescriptionsPrescriptions of this encounter: name, medications, status, prescribed_by, tags, note. Each medication has name, status, intent, priority, authored_on, dosage_instructions and note.
questionnaire_responsesCompleted responses to a questionnaire in this encounter. Each has title, description, responses (question and answer) and updated_by. A filter needs a questionnaire slug (otherwise slug is required), and the filtered list is newest first.
service_requestsService requests of this encounter: title, status, intent, category, priority, requester, occurance, patient_instruction, tags, note.
created_by, updated_by, created_date, modified_dateAudit fields.
  • Observations are available only inside a diagnostic report, as the observations attached to that report. Each has title, value, component, status, effective_datetime, interpretation and reference_range. The context has no encounter-level list of observations.
  • Procedures and immunizations are not available. Care has Procedure and Immunization records, but no report data point reads them.
  • Chronic conditions (category chronic_condition) are not available. No report data point reads that category.

patient_base fields​

The patient context has demographic fields only: name, gender, age, blood_group, address, phone_number, date_of_birth, deceased_datetime, instance_identifiers, instance_tags, extensions. It has no clinical data: no conditions, medications, allergies, reports or encounters.

account_base fields​

Top-level fields: external_id, name, status, billing_status, description, total_gross, total_paid, total_balance, total_billable_charge_items, total_price_components, invoices, charge_items, category_charge_items_summary, payment_reconciliations, created_date, calculated_at, primary_encounter, patient, facility.

  • invoices, charge_items and payment_reconciliations are those of the account.
  • primary_encounter gives the full encounter_base context of the account's primary encounter, with its diagnoses, symptoms and the other encounter fields.

Resource specs (API schema)​

SpecRole
TemplateCreateSpecwrite · create. Fields in Write fields.
TemplateUpdateSpecwrite · update. A subclass of TemplateCreateSpec with no changes.
TemplateReadSpecread · list. Includes slug_config. Leaves out facility and template_data.
TemplateRetrieveSpecread · detail. Extends TemplateReadSpec with facility (dict | None) and template_data.
ArchiveRequestSpecBody of the archive action: archive_reason: str, required. An empty string is accepted.
GenerateReportRequestBody of the generate action: template_id: UUID4, associating_id: UUID4, output_format: str | None, force: bool (default False) and status_check: bool (default False).
PreviewTemplateRequestBody of the preview action: template_data: str, output_format: str (default "html"), context: str, options: dict (default empty). It names no template, patient, encounter or account.

Endpoints​

Every call needs a signed-in user.

MethodPathAction
GET/api/v1/template/List templates.
POST/api/v1/template/Create a template.
GET/api/v1/template/{slug}/Retrieve one template.
PUT/api/v1/template/{slug}/Update a template (full update).
GET/api/v1/template/schema/The data contexts with their fields, the output formats, the custom field types and the report types.
POST/api/v1/template/preview/Render template text with sample data.
GET/api/v1/template_reports/List reports. Needs report_type and associating_id.
GET/api/v1/template_reports/{id}/Retrieve one report, with read_signed_url.
POST/api/v1/template_reports/generate/Start a report generation.
POST/api/v1/template_reports/{id}/archive/Archive a report.

The template API has no delete endpoint. The report API has no create, update, delete or unarchive endpoint.

Template list filters​

  • name (contains), template_type (exact), status, and facility (facility external ID, exact).
  • facility_only is accepted, but it changes nothing when facility is sent, because the facility filter already limits the list to the facility's own templates.
  • Ordering: created_date, name, template_type.

Report list filters​

  • report_type and associating_id are required. Without them the API returns report_type and associating_id are required.
  • Other filters: name, template (template slug), is_archived and upload_completed.
  • Ordering: created date or name.
  • The list includes archived reports unless you filter them out.

Report generation​

POST /api/v1/template_reports/generate/ runs these steps in this order:

  1. Validate output_format. An unknown format gives Invalid output format. Without a value, the template's default_format applies.
  2. Check write access to the record for the template's report type. See Record access per report type.
  3. For a facility template, check "Can generate report from template" in the template's facility. The refusal is You are not authorized to generate reports. Instance-wide templates skip this check.
  4. Check that the template status is active. Otherwise the API returns Template is not active.
  5. Look up the lock for the report type and the record (<template_type>_<associating_id>). One generation runs at a time for each report type and record, whatever the template. force clears the lock.
  6. With status_check, return progress (a percentage) when a generation runs, or an empty response when none runs. Nothing starts.
  7. When a generation already runs, return 409 with Report generation is already in progress for this report, current progress N%.
  8. Queue a Celery task, and return 201 at once with no report in the body.
  • A status_check request also goes through steps 2 to 4.
  • The task sets the progress to 10, then to 30. It clears the lock when it ends, after a success or a failure.
  • The lock expires after two minutes.
  • The task retries up to three times on storage errors (ClientError). It expires if it does not start within ten minutes. Care's global Celery limits are 1800 s (soft) and 9000 s (hard).
  • The report uses the record's data at the time of generation.
  • Each generation creates a new ReportUpload. Earlier reports stay.
  • Care uploads the file to the report storage bucket and sets upload_completed. If the upload fails, Care deletes the report record.
  • Nothing checks that a facility template belongs to the facility of the encounter, patient or account.

Rendering​

Template engine​

  • Templates use Jinja2 in an immutable sandboxed environment, with autoescaping on.
  • By default, a name that does not exist fails the render (StrictUndefined).
  • A template can read only the declared report fields, plus filter on lists. Internal attributes are hidden.
  • Extra filters: date, datetime, time, currency, phone. Extra functions: current_date, current_datetime, current_time.
  • Default formats: date uses %d/%m/%Y, datetime uses %d/%m/%Y %I:%M %p, and time uses %I:%M %p, in the server's local time zone.
  • currency uses the rupee symbol (₹) and Indian digit grouping by default.
  • Care does not check the template syntax when you save a template. Syntax errors show at preview or at generation.
  • Errors: Failed to render template for a render failure, and Failed to generate <format> for an output failure.

Preview​

  • The preview builds the context in preview mode, not from a real record.
  • In preview mode, each field shows its built-in sample value, or nothing. A list shows one to four sample rows, chosen at random.
  • Errors: Invalid output format, Invalid context, and Preview generation failed for any render failure.

HTML sanitizer​

  • HTML output goes through the report HTML sanitizer (sanitize_report_html).
  • Allowed elements: html, head, body, title, style, link, div, center, span, font, p, label, h1 to h6, ul, ol, li, table, caption, colgroup, col, thead, tbody, tfoot, tr, th, td, strong, em, b, i, u, s, mark, del, ins, small, sub, sup, br, hr, a, img, pre, code, kbd, blockquote, q, cite, dl, dt, dd, section, nav, aside, header, footer, main, article, figure, figcaption, address, abbr, time.
  • The sanitizer removes other elements, such as script, iframe, form, input, button, svg and video. Text after a removed element stays.
  • Allowed attributes: class, id, title, lang, dir and style on any element, plus href on a; src, alt, width and height on img; href, rel, media, type and crossorigin on link; and layout attributes on table, col, colgroup, td, th, ol, li and time. The sanitizer removes other attributes, such as event handlers.
  • A link element stays only if it is a stylesheet from an allowed origin.
  • An img source must be an embedded data: image or come from an allowed origin. Otherwise the sanitizer removes it.
  • An href must use https, http, mailto or tel, or be a # fragment.
  • CSS: only listed CSS functions stay. A url() must point to an allowed origin or be an embedded image or font. An @import must come from an allowed origin. Allowed at-rules include @media, @supports, @page (with page-margin boxes), @font-face and @keyframes.
  • The sanitized HTML carries a Content-Security-Policy meta tag. The HTML preview response also sends the policy as a header.
  • The default policy is default-src 'none': no scripts, images and fonts only from data: and the allowed origins, and styles inline or from the allowed origins.

Allowed remote resources​

  • The allowed origins come from REPORT_ALLOWED_RESOURCE_ORIGINS. If it is not set, Care uses REPORT_ALLOWED_IMAGE_ORIGINS, then FACILITY_CDN. Otherwise no origin is allowed.
  • A remote resource must use https, must have no user name or password in the URL, and must match the host and port of an allowed origin exactly. The allowed origin must be listed without a path.
  • Allowed remote image types: PNG, JPEG, GIF, WebP, AVIF, BMP.

PDF output (WeasyPrint)​

  • WeasyPrint makes the PDF from the rendered HTML. The HTML sanitizer does not run on PDF output. The URL fetcher limits what a PDF can load.
  • The fetcher loads only data: and https URLs, and it does not follow redirects.
  • Remote images, CSS and fonts must come from an allowed origin (Report resource origin is not allowed). Remote resources must be images, CSS or fonts (Remote report resources must be images, CSS, or fonts), and remote SVG or XML is refused. Raster images are verified.
  • Each remote resource is limited to REPORT_MAX_RESOURCE_SIZE_BYTES, 10 MB by default.
  • For the default CSS, see PDF options.

Authorization​

The role lists below are the defaults in the code. Roles and their permissions can be changed.

Template permissions​

PermissionSlugDefault facility rolesHeld in
Can Create Template on Facilitycan_write_templateFacility Admin, Doctor, NurseThe root organization of the facility ("Administration")
Can Read Templatecan_read_templateFacility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, PharmacistAny organization of the facility
Can Preview Templatecan_preview_templateFacility AdminAny facility organization of any facility
Can View Template Schemacan_view_template_schemaFacility AdminAny facility organization of any facility
Can generate report from templatecan_generate_report_from_templateFacility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, PharmacistAny organization of the template's facility
Can generate report for completed encountercan_generate_report_for_completed_encounterFacility AdminThe encounter's organizations

Template actions​

ActionRequirement
List templates without facilityA signed-in user. The API returns only the instance-wide templates.
List templates with facility"Can Read Template" in any organization of that facility. The refusal is You do not have permission to read templates.
Retrieve a templateA facility template needs "Can Read Template" in any organization of the template's facility. Any signed-in user can retrieve an instance-wide template.
Create a facility template"Can Create Template on Facility" in the root organization of the facility.
Update a facility template"Can Create Template on Facility" in the root organization of the template's current facility.
Create or update an instance-wide templateSuperuser only. The refusal is You do not have permission to write templates.
Get the schema"Can View Template Schema" in any facility organization of any facility. The refusal is You do not have permission to access template schema.
Preview"Can Preview Template" in any facility organization of any facility. The check is not tied to the facility of a template. The refusal is You do not have permission to preview templates.

Report actions​

ActionRequirement
List reportsRead access to the record, for the report_type in the request.
Retrieve a reportRead access to the report's record.
GenerateWrite access to the record, for the template's report type. A facility template also needs "Can generate report from template" in any organization of the template's facility. The template must be active.
ArchiveWrite access to the report's record, the same record check as for generate. The template permission and the template status are not checked.

An unknown report type gives Invalid report type: <type>. A refused check gives Cannot read report of type <type> or Cannot write report of type <type>.

Record access per report type​

Report typeRead (list, retrieve)Write (generate, archive)
discharge_summary, encounter_report"Can view clinical data about patients" (can_view_clinical_data) through a role on the patient, or "Can Read encounter" (can_read_encounter) in the encounter's organizationsEncounter not in a completed status: "Update Encounter non clinical" (can_write_encounter). Encounter in a completed status: "Can generate report for completed encounter" (can_generate_report_for_completed_encounter). Both in the encounter's organizations.
patient_summary"Can view clinical data about patients" through a role on the patient"Can Update a Patient's data" (can_write_patient) through a role on the patient. When PATIENT_GLOBAL_EDIT_ACCESS_ENABLED is on (it is off by default), the permission held anywhere is enough.
account_report"Can Read Account" (can_read_account) in any organization of the account's facility"Can Update Account" (can_update_account) in any organization of the account's facility
  • The encounter's organizations are its facility organizations plus those of its current location. They always include the facility's root organization, and each linked organization with its parents.
  • A user's roles on a patient come from the organizations of the patient's encounters that are not in a completed status (and of their current locations), from the patient's own organizations, and from direct association with the patient.
  • The completed statuses are completed, cancelled, entered_in_error and discontinued. planned, in_progress, on_hold, discharged and unknown are not completed statuses, so a discharged encounter still uses "Update Encounter non clinical".
  • Completed-encounter rule: when an encounter is in a completed status, generating or archiving its Discharge Summary or Encounter Report needs "Can generate report for completed encounter". By default, Facility Admin holds it, and Doctor and Nurse do not.

Record permissions​

PermissionSlugDefault facility roles
Can Read encountercan_read_encounterFacility Admin, Doctor, Nurse
Update Encounter non clinicalcan_write_encounterFacility Admin, Doctor, Nurse
Can view clinical data about patientscan_view_clinical_dataFacility Admin, Staff, Doctor, Nurse
Can Update a Patient's datacan_write_patientFacility Admin, Administrator, Staff, Doctor, Nurse
Can Read Accountcan_read_accountFacility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist
Can Update Accountcan_update_accountFacility Admin

Methods & save behaviour​

  • On save, Care does not write the fields whose value equals the field default (exclude_defaults=True). So description: "" in an update keeps the old description.
  • On update, a facility in the request replaces the template's facility. An empty facility keeps the current facility.
  • The archive action sets is_archived, archive_reason, archived_datetime and archived_by. It does not check whether the report is already archived.

API integration notes​

  • Generation is asynchronous. The generate call returns 201 with no report, and a client polls with status_check. The Care report viewer polls this way, and it lists reports with upload_completed=true and is_archived=false.
  • read_signed_url is valid for one hour.
  • The Care report viewer shows and prints only PDF reports. It offers an HTML report as a download only. Use pdf for a template that people print.