# 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](https://docs.ohc.network/concepts/platform/report-template.md) for the plain-language view.

**Source:**

* Models: [`care/emr/models/report/report_upload.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/report/report_upload.py) · [`care/emr/models/report/template.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/report/template.py)
* Specs: [`care/emr/resources/report/template/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/report/template/spec.py) · [`care/emr/resources/report/report_upload/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/report/report_upload/spec.py)
* Viewsets: [`care/emr/api/viewsets/report/template.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/report/template.py) · [`care/emr/api/viewsets/report/report_upload.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/report/report_upload.py)
* Report types and data contexts: [`care/emr/reports/report_types.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/reports/report_types.py) · [`care/emr/reports/context_builder/data_points/`](https://github.com/ohcnetwork/care/tree/develop/care/emr/reports/context_builder/data_points)
* Rendering: [`template_engine.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/reports/renderer/template_engine.py) · [`html_sanitizer.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/reports/renderer/html_sanitizer.py) · [`resource_policy.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/reports/renderer/resource_policy.py) · [`weasyprint_generator.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/reports/renderer/generators/weasyprint_generator.py)
* Generation: [`care/emr/reports/report_utils.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/reports/report_utils.py) · [`care/emr/tasks/report_generation.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/tasks/report_generation.py)
* Authorization: [`care/security/permissions/template.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/template.py) · [`care/security/authorization/template.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/template.py) · [`care/emr/reports/authorizers/`](https://github.com/ohcnetwork/care/tree/develop/care/emr/reports/authorizers)

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

## Models

| Model | Purpose |
| - | - |
| `ReportUpload` | One generated report file. It links to its template and to one encounter, patient or account. The file is stored in the report storage bucket. |
| `Template` | A 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

| Field | Type | Notes |
| - | - | - |
| `template` | FK → `Template` (`PROTECT`) | The template used. A template that has reports cannot be deleted. |
| `name` | `CharField(2000)` | `<template name>-<associating_id>-<timestamp in ms>`, set at generation. |
| `report_type` | `CharField(50)` | The report type key. The access checks use it. |
| `associating_id` | `CharField(100)` | UUID of the encounter, patient or account. |
| `upload_completed` | `BooleanField` | Default `False`. Set to true after the file upload to the report storage bucket. |
| `is_archived` | `BooleanField` | Default `False`. |
| `archive_reason` | `TextField` | Blank allowed. |
| `archived_datetime` | `DateTimeField`, nullable | The time of archiving. |
| `archived_by` | FK → `User` (`PROTECT`), nullable | The 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)

| Field | Type | Required | Default | Notes |
| - | - | - | - | - |
| `name` | `str` | Yes | — | — |
| `status` | `TemplateStatusOptions` | Yes | — | See [`TemplateStatusOptions` values](#templatestatusoptions-values). |
| `default_format` | `TemplateFormatOptions` | Yes | — | Selects the generator whose options model validates `options`. Generate uses it when the request has no `output_format`. |
| `description` | `str` | No | `""` | — |
| `options` | `dict` | No | Empty | Validated against the options model of `default_format`. Unknown keys are rejected. See [Template output options](#template-output-options). |
| `facility` | `UUID4 \| None` | No | `None` | Facility 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_value` | `SlugType` | Yes | — | See [Slug rules](#slug-rules). |
| `template_data` | `str` | Yes | — | The Jinja2 template body. Returned only when you retrieve one template. |
| `template_type` | `str` | Yes | — | A registered report type. See [Report types](#report-types). |
| `context` | `str` | Yes | — | A registered data context, built on the same kind of record as `template_type`. See [Data contexts](#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

| Value | Effect |
| - | - |
| `draft` | Cannot generate a report. |
| `active` | The only status that can generate a report. |
| `retired` | Cannot generate a report. |

### `TemplateFormatOptions` values

| Value | Output |
| - | - |
| `pdf` | WeasyPrint converts the rendered HTML to PDF. The HTML sanitizer does not run on it. |
| `html` | The 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.

| Key | Display name | Generated for | Context |
| - | - | - | - |
| `discharge_summary` | Discharge Summary | Encounter | `encounter_base` |
| `encounter_report` | Encounter Report | Encounter | `encounter_base` |
| `patient_summary` | Patient Summary | Patient | `patient_base` |
| `account_report` | Account Report | Account (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](#template-actions).

### Validation messages

| Condition | Message |
| - | - |
| `template_type` is empty | `Report Type is required` |
| `template_type` is not registered | `Invalid report type` |
| `context` is empty | `Report Type is required` (the same text as for `template_type`) |
| `context` is not registered | `Invalid 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 records | `Report Type and Context are not compatible` |
| `slug_value` does not match the pattern | `Slug must contain only URL-safe characters (letters, numbers, hyphens, and underscores). It must start and end with alphanumeric characters.` |
| The slug is already in use | `Slug already exists.` |
| `options` has an unknown key | Rejected by the options model (`extra="forbid"`). |

## Template output options

The keys that `options` accepts depend on `default_format`.

### HTML options

| Option | Type | Default |
| - | - | - |
| `wrap_document` | `bool` | `False` |
| `title` | `str` | `"Report"` |
| `charset` | `str` | `"utf-8"` |

### PDF options

| Option | Type | Default |
| - | - | - |
| `page_size` | `"A4"`, `"A3"`, `"A5"`, `"Letter"` or `"Legal"` | `"A4"` |
| `margin` | `str` | `"1cm"` |
| `orientation` | `"portrait"` or `"landscape"` | `"portrait"` |
| `stylesheets` | List of CSS strings | Empty 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.

| Context | Display name | Record | Template variable |
| - | - | - | - |
| `encounter_base` | Encounter Report | Encounter | `encounter` |
| `patient_base` | Patient Report | Patient | `patient` |
| `account_base` | Account Report | Account | `account` |

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

| Field | Data |
| - | - |
| `status` | The 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_tags` | Other top-level fields of the context. |
| `patient` | The patient of the encounter. |
| `facility` | `name`, `description`, `address`, `pincode`, `phone_number`. |
| `diagnoses` | Conditions 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). |
| `symptoms` | Conditions 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_reports` | Diagnostic 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_intolerances` | Allergy intolerances recorded in this encounter. Each has `clinical_status`, `category`, `verification_status`, `criticality`, `name`, `note`, `last_occurrence` and `allergy_intolerance_type`. |
| `medication_prescriptions` | Prescriptions of this encounter: `name`, `medications`, `status`, `prescribed_by`, `tags`, `note`. Each medication has `name`, `status`, `intent`, `priority`, `authored_on`, `dosage_instructions` and `note`. |
| `questionnaire_responses` | Completed 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_requests` | Service requests of this encounter: `title`, `status`, `intent`, `category`, `priority`, `requester`, `occurance`, `patient_instruction`, `tags`, `note`. |
| `created_by`, `updated_by`, `created_date`, `modified_date` | Audit 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)

| Spec | Role |
| - | - |
| `TemplateCreateSpec` | write · create. Fields in [Write fields](#write-fields-create-and-update). |
| `TemplateUpdateSpec` | write · update. A subclass of `TemplateCreateSpec` with no changes. |
| `TemplateReadSpec` | read · list. Includes `slug_config`. Leaves out `facility` and `template_data`. |
| `TemplateRetrieveSpec` | read · detail. Extends `TemplateReadSpec` with `facility` (`dict \| None`) and `template_data`. |
| `ArchiveRequestSpec` | Body of the archive action: `archive_reason: str`, required. An empty string is accepted. |
| `GenerateReportRequest` | Body of the generate action: `template_id: UUID4`, `associating_id: UUID4`, `output_format: str \| None`, `force: bool` (default `False`) and `status_check: bool` (default `False`). |
| `PreviewTemplateRequest` | Body 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.

| Method | Path | Action |
| - | - | - |
| `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](#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](#pdf-options).

## Authorization

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

### Template permissions

| Permission | Slug | Default facility roles | Held in |
| - | - | - | - |
| Can Create Template on Facility | `can_write_template` | Facility Admin, Doctor, Nurse | The root organization of the facility ("Administration") |
| Can Read Template | `can_read_template` | Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist | Any organization of the facility |
| Can Preview Template | `can_preview_template` | Facility Admin | Any facility organization of any facility |
| Can View Template Schema | `can_view_template_schema` | Facility Admin | Any facility organization of any facility |
| Can generate report from template | `can_generate_report_from_template` | Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist | Any organization of the template's facility |
| Can generate report for completed encounter | `can_generate_report_for_completed_encounter` | Facility Admin | The encounter's organizations |

### Template actions

| Action | Requirement |
| - | - |
| List templates without `facility` | A 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 template | A 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 template | Superuser 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

| Action | Requirement |
| - | - |
| List reports | Read access to the record, for the `report_type` in the request. |
| Retrieve a report | Read access to the report's record. |
| Generate | Write 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`. |
| Archive | Write 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 type | Read (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 organizations | Encounter 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

| Permission | Slug | Default facility roles |
| - | - | - |
| Can Read encounter | `can_read_encounter` | Facility Admin, Doctor, Nurse |
| Update Encounter non clinical | `can_write_encounter` | Facility Admin, Doctor, Nurse |
| Can view clinical data about patients | `can_view_clinical_data` | Facility Admin, Staff, Doctor, Nurse |
| Can Update a Patient's data | `can_write_patient` | Facility Admin, Administrator, Staff, Doctor, Nurse |
| Can Read Account | `can_read_account` | Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist |
| Can Update Account | `can_update_account` | Facility 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.

## Related

* Concept: [Report Template](https://docs.ohc.network/concepts/platform/report-template.md)
* Flow: [View report templates](https://docs.ohc.network/flows/platform/report-template/view-report-templates.md)
* Flow: [Create a report template](https://docs.ohc.network/flows/platform/report-template/create-a-report-template.md)
* Flow: [Preview a template](https://docs.ohc.network/flows/platform/report-template/preview-a-template.md)
* Flow: [Edit a report template](https://docs.ohc.network/flows/platform/report-template/edit-a-report-template.md)
* Flow: [Generate and view a report](https://docs.ohc.network/flows/platform/report-template/generate-and-view-a-report.md)
* Flow: [Print a report](https://docs.ohc.network/flows/platform/report-template/print-a-report.md)
* Flow: [Archive a report](https://docs.ohc.network/flows/platform/report-template/archive-a-report.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [Patient](https://docs.ohc.network/references/clinical/patient.md)
* Reference: [Account](https://docs.ohc.network/references/billing/account.md)
* Reference: [Condition](https://docs.ohc.network/references/clinical/condition.md)
* Reference: [Diagnostic Report](https://docs.ohc.network/references/clinical/diagnostic-report.md)
* Reference: [Facility](https://docs.ohc.network/references/facility.md)
* Reference: [User](https://docs.ohc.network/references/access-governance/user.md)
* Reference: [Role](https://docs.ohc.network/references/access-governance/role.md)
* Reference: [Permission](https://docs.ohc.network/references/access-governance/permission.md)
* Reference: [File Upload](https://docs.ohc.network/references/platform/file-upload.md)
* Reference: [Base model](https://docs.ohc.network/references/foundation/base-model.md)
* Source: [report\_upload.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/report/report_upload.py), [template.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/report/template.py)
* Source: [report\_upload/spec.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/report/report_upload/spec.py), [template/spec.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/report/template/spec.py)
