# Condition

Technical reference for the `Condition` module in Care EMR. For what a condition is, see the [Condition](https://docs.ohc.network/concepts/clinical/condition.md) concept.

A `Condition` row records one symptom or one diagnosis for a patient. Care serves the same table through two APIs under the patient: the symptom API and the diagnosis API.

**Source:**

* Model: [`care/emr/models/condition.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/condition.py)
* Resource specs: [`spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/condition/spec.py) · [`valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/condition/valueset.py) · shared type [`common/coding.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/common/coding.py)
* Viewsets: [`care/emr/api/viewsets/condition.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/condition.py) · authorization base [`encounter_authz_base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/encounter_authz_base.py) · viewset base [`base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/base.py)
* Value set check: [`care_valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/registries/care_valueset/care_valueset.py)
* Authorization: [`security/authorization/encounter.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/encounter.py) · [`security/authorization/patient.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/patient.py)

The Django model stores the data. Its `code`, `body_site`, `onset` and `abatement` fields are JSON fields.

The Pydantic resource specs define the shape of `code`, `onset` and `abatement`. The specs also define the enums, the value set bindings, the validation and the read and write schemas.

## Models

| Model | Purpose |
| - | - |
| `Condition` | One symptom or one diagnosis recorded for a patient |

`Condition` extends [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md). That reference page describes the inherited fields. The "Inherited fields" table below lists the ones that the condition APIs use.

## `Condition` fields

Each table gives the storage type from the Django model and the API shape from the specs.

### Status and classification

| Field | Storage type | API shape | Notes |
| - | - | - | - |
| `clinical_status` | `CharField(100)`, nullable | `ClinicalStatusChoices` on write, `str` on read | Optional on create and update |
| `verification_status` | `CharField(100)`, nullable | `VerificationStatusChoices` on write, `str` on read | Required on create and update |
| `category` | `CharField(100)`, nullable | `CategoryChoices` on create, `str` on read | Required on create by both APIs. The symptom API then saves `problem_list_item`, whatever the request sends. The update specs do not take it |
| `severity` | `CharField(100)`, nullable | `SeverityChoices` on write, `str` on read | Optional on create and update |

### Coded concepts

| Field | Storage type | API shape | Notes |
| - | - | - | - |
| `code` | `JSONField` (`default=dict`), not null | Write: `ValueSetBoundCoding`, bound to `system-condition-code` (diagnosis API) or `system-symptom-code` (symptom API). Read: `Coding` | Required on create and update. The `name` list filter searches its `display` |
| `body_site` | `JSONField` (`default=dict`), not null | Not in `ConditionReadSpec` or the update specs | The read and update schemas do not return or change it |

### Timing

| Field | Storage type | API shape | Notes |
| - | - | - | - |
| `onset` | `JSONField` (`default=dict`) | `ConditionOnSetSpec` | Accepted on create and update, returned on read. Shape below |
| `abatement` | `JSONField` (`default=dict`) | `ConditionAbatementSpec` | Accepted on create and update, returned on read. Shape below |
| `recorded_date` | `DateTimeField`, nullable | Not in `ConditionReadSpec` or the update specs | The read and update schemas do not return or change it |

### Context and note

| Field | Storage type | API shape | Notes |
| - | - | - | - |
| `patient` | `FK → emr.Patient` (`CASCADE`), required | Not in `ConditionReadSpec` | Set on create from the encounter's patient. The client does not choose it |
| `encounter` | `FK → emr.Encounter` (`CASCADE`), nullable | `UUID4`: required on create, returned on read, not in the update specs | Must exist, else "Encounter not found". Must belong to the patient in the URL, else "Patient external ID mismatch with encounter's patient" |
| `note` | `TextField`, nullable | `str \| None` | Optional |

### Inherited fields

| Field | API shape | Notes |
| - | - | - |
| `external_id` | Returned as `id` (`UUID4`) in the read schema | An upsert datapoint with this `id` updates the record |
| `created_date` | `datetime`, in the read schema | A list ordering field |
| `modified_date` | `datetime`, in the read schema | A list ordering field |
| `created_by` | `dict \| None`, in the read schema | Returned on read |
| `updated_by` | `dict \| None`, in the read schema | Returned on read |
| `deleted` | Not in the read schema | `DELETE` sets it to `True` (soft delete) |

## Enum values

Every enum is a `str, Enum` in `care/emr/resources/condition/spec.py`. The model stores the string value, and the read schema returns it as a `str`.

### `ClinicalStatusChoices` values

| Value |
| - |
| `active` |
| `recurrence` |
| `relapse` |
| `inactive` |
| `remission` |
| `resolved` |
| `unknown` |

Care's frontend form offers six of these values. It does not offer `unknown`.

### `VerificationStatusChoices` values

| Value |
| - |
| `unconfirmed` |
| `provisional` |
| `differential` |
| `confirmed` |
| `refuted` |
| `entered_in_error` |

Care's frontend form offers `entered_in_error` only on a record that is already saved. To retract a record, the frontend sets `verification_status` to `entered_in_error`. It never sends `DELETE`.

### `CategoryChoices` values

| Value | Set by |
| - | - |
| `problem_list_item` | The symptom API, on every create |
| `encounter_diagnosis` | Care's Diagnosis form, on every new diagnosis |
| `chronic_condition` | No screen in Care's frontend. The frontend only reads this category |

Both create specs require `category`. The symptom API then overwrites it with `problem_list_item`, whatever the request sends.

### `SeverityChoices` values

| Value |
| - |
| `mild` |
| `moderate` |
| `severe` |

## Nested JSON shapes

### `onset` (`ConditionOnSetSpec`)

| Key | Type | Default | Meaning and validation |
| - | - | - | - |
| `onset_datetime` | `datetime \| None` | `None` | Date and time of onset. Cannot be in the future: "Onset date cannot be in the future" |
| `onset_age` | `int \| None` | `None` | Age at onset |
| `onset_string` | `str \| None` | `None` | Free-text description of the onset |
| `note` | `str \| None` | `None` | Note about the onset |

### `abatement` (`ConditionAbatementSpec`)

`ConditionAbatementSpec` extends `EMRResource`.

| Key | Type | Default | Meaning and validation |
| - | - | - | - |
| `abatement_datetime` | `datetime \| None` | `None` | Date and time of abatement. No future-date check |
| `abatement_age` | `int \| None` | `None` | Age at abatement |
| `abatement_string` | `str \| None` | `None` | Free-text description of the abatement |
| `note` | `str \| None` | `None` | Note about the abatement |

### `code`

On write, `code` is a `ValueSetBoundCoding`. Care checks the coding against the bound value set (see "Bound value sets").

On read, `ConditionReadSpec` types `code` as a plain `Coding`, not as a bound coding. For the `Coding` keys, see [`common/coding.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/common/coding.py).

## Related models

`Condition` has two foreign keys to clinical records.

```
patient   → FK emr.Patient   (CASCADE, required)

encounter → FK emr.Encounter (CASCADE, nullable; both create specs require it)
```

Each create and update through either API also writes a [questionnaire response](https://docs.ohc.network/references/clinical/questionnaire-response.md) for the condition's patient and encounter. See "Methods & save behaviour".

## Resource specs (API schema)

The diagnosis API writes with the `Condition*` specs, which bind `code` to the Condition value set. The symptom API writes with the `Symptom*` specs, which bind `code` to the Symptom value set.

Both APIs read with `ConditionReadSpec`.

| Spec class | Role | Fields and behaviour |
| - | - | - |
| `ConditionSpec` | Diagnosis API: create, and upsert datapoints without `id` | Required: `verification_status`, `code` (Condition value set), `encounter` (UUID4), `category`. Optional fields include `clinical_status`, `severity`, `onset`, `abatement` and `note`. Checks that the encounter exists. On create, sets `encounter` and takes `patient` from it |
| `SymptomSpec` | Symptom API: create, and upsert datapoints without `id` | Extends `ConditionSpec` and binds `code` to the Symptom value set. The API then saves `category` as `problem_list_item` |
| `ConditionUpdateSpec` | Diagnosis API: update, and upsert datapoints with `id` | Extends `BaseConditionSpec`. Required: `verification_status`, `code` (Condition value set). Optional: `clinical_status`, `severity`, `onset`, `abatement`, `note`. Does not take `encounter` or `category` |
| `SymptomUpdateSpec` | Symptom API: update, and upsert datapoints with `id` | Extends `ConditionUpdateSpec` and binds `code` to the Symptom value set |
| `ChronicConditionUpdateSpec` | Not used | Extends `ConditionUpdateSpec` and adds `encounter` (UUID4). No viewset uses it |
| `ConditionReadSpec` | Both APIs: read | `id` (the record's `external_id`), `clinical_status`, `verification_status`, `category`, `severity` (each `str`), `code` (`Coding`), `encounter` (UUID4), `onset`, `abatement`, `created_by`, `updated_by`, `note`, `created_date`, `modified_date`. It has no `criticality` field |
| `ConditionOnSetSpec` | Nested: shape of `onset` | `onset_datetime`, `onset_age`, `onset_string`, `note` |
| `ConditionAbatementSpec` | Nested: shape of `abatement` | `abatement_datetime`, `abatement_age`, `abatement_string`, `note` |

### Bound value sets

| Specs | Value set | Constant | Slug | Default composition |
| - | - | - | - | - |
| `ConditionSpec`, `ConditionUpdateSpec`, `ChronicConditionUpdateSpec` | Condition | `CARE_CODITION_CODE_VALUESET` | `system-condition-code` | SNOMED CT concepts `is-a` `64572001` |
| `SymptomSpec`, `SymptomUpdateSpec` | Symptom | `CARE_SYMPTOM_CODE_VALUESET` | `system-symptom-code` | SNOMED CT concepts that match the constraint `< 404684003 MINUS << 64572001` |

The Symptom constraint takes the descendants of `404684003` that are not `64572001` or a descendant of `64572001`. So, by default, no code is in both value sets.

Both value sets have the status `active` and register as system value sets.

The Symptom value set, and the `is-a` `64572001` rule of the Condition value set, are new in Care 3.1.

Validation reads the stored value set by slug and takes the first match. If no value set has the slug, the request fails with "Valueset does not exist in care, Resync valuesets".

A code outside the value set fails with "Code does not exist in the valueset". A Condition value set code sent to the symptom API fails this way.

Care's frontend searches the same value sets. The symptom search uses `system-symptom-code`, and the diagnosis search uses `system-condition-code`.

### Validation

* `verification_status`, `code`, `encounter` and `category` are required on create, by both APIs.
* `verification_status` and `code` are required on update.
* `code` must hold a code from the bound value set, on create and on update.
* The encounter in the request must exist. Otherwise the request fails with "Encounter not found".
* The condition's encounter must belong to the patient in the URL. Otherwise the request fails with "Patient external ID mismatch with encounter's patient".
* `onset.onset_datetime` cannot be in the future: "Onset date cannot be in the future". `abatement.abatement_datetime` has no such check.
* The update specs do not take `encounter` or `category`.

### Server-side behaviour

* Create: Care sets `encounter` from the request and takes `patient` from that encounter.
* Symptom create: Care saves `category` as `problem_list_item`, whatever the request sends.
* Read, symptom API: Care returns only the patient's records of category `problem_list_item`.
* Read, diagnosis API: Care returns the patient's records of every category, symptoms included.

## Methods & save behaviour

* `SymptomViewSet.perform_create` sets `category` to `problem_list_item` before the save.
* Delete is a soft delete. Care sets `deleted = True` and keeps the row.
* Each create and update through either API also writes a `QuestionnaireResponse` for the condition's patient and encounter.
* The questionnaire response has `structured_response_type` set to `symptom` (symptom API) or `diagnosis` (diagnosis API). Its submit type is `CREATE` on create and `UPDATE` on update.
* Care's frontend shows these questionnaire responses in the encounter's responses, titled "Symptom" or "Diagnosis".
* `patient` and `encounter` use `on_delete=CASCADE`.

## API integration notes

### Endpoints

Both APIs sit on the patient router. The base paths are `/api/v1/patient/{patient_id}/symptom/` and `/api/v1/patient/{patient_id}/diagnosis/`, where `{patient_id}` is the patient's `external_id`.

| Action | Symptom API | Diagnosis API |
| - | - | - |
| list and retrieve | Only the patient's `problem_list_item` records, as `ConditionReadSpec` | The patient's records of every category, as `ConditionReadSpec` |
| create | `SymptomSpec`. Requires `category`, then saves `problem_list_item` | `ConditionSpec`. Requires `category` |
| update | `SymptomUpdateSpec` | `ConditionUpdateSpec` |
| delete (`DELETE`) | Soft delete | Soft delete |
| upsert (`POST upsert/`) | A `datapoints` list, through the specs above | The same |

Neither list leaves out records entered in error by default.

The diagnosis list also returns symptoms. To list diagnoses only, send `category=encounter_diagnosis,chronic_condition`, as Care's frontend does.

### Upsert

* The body has a `datapoints` list.
* An empty list fails with "No datapoints provided". More than `MAX_DATAPOINTS_PER_UPSERT` datapoints (default 100) fail with "Too many datapoints provided".
* A datapoint with `id` (the `id` that the read schema returns) updates that record through the API's update spec. A datapoint without `id` creates a record through the API's create spec.
* Each datapoint goes through the create or update authorization check (see "Authorization").
* Each created or updated datapoint writes its own questionnaire response.
* The upsert is all-or-nothing. If one datapoint fails, Care saves none of them.
* Care's Diagnosis form sends only new or changed rows, with the form's encounter on each row, as one upsert.
* Care's Symptom form sends every row it holds, changed or not, as one upsert.

### Filters and ordering

| Parameter | Behaviour |
| - | - |
| `encounter` | An encounter `external_id`. Returns only that encounter's records. With it, the read check can also pass through the encounter (see "Authorization") |
| `clinical_status`, `exclude_clinical_status` | One or more clinical statuses, comma-separated, to include or to leave out |
| `verification_status`, `exclude_verification_status` | One or more verification statuses, comma-separated, to include or to leave out |
| `severity` | One severity |
| `name` | Records whose `code.display` contains the text |
| `category` | One or more categories, comma-separated |
| `ordering` | `created_date` or `modified_date`. A leading `-` sorts in descending order |

### Authorization

The viewsets check clinical-data permissions for each action, as the table shows.

| Action | Care checks | Permission (slug) | Refusal |
| - | - | - | - |
| list and retrieve, both APIs | Patient clinical-data read on the patient in the URL. If that fails and the request has `?encounter=`, encounter clinical-data read on that encounter | "Can view clinical data about patients" (`can_view_clinical_data`), through a role on the patient. Or "Can Read encounter related clinical data" (`can_read_encounter_clinical_data`), in the encounter | "Permission denied to user" |
| create, both APIs | `can_update_encounter_clinical_data` on the encounter in the request | "Update Encounter related clinical data" (`can_write_encounter_clinical_data`), in the encounter. The encounter must not be closed | "You do not have permission to update encounter" |
| update, symptom API | The same check, on the record's encounter | As for create | As for create |
| update, diagnosis API, category `chronic_condition` | Patient clinical-data read on the record's patient only | "Can view clinical data about patients" (`can_view_clinical_data`), through a role on the patient | "You do not have permission to update chronic condition" |
| update, diagnosis API, other categories | The create check, on the record's encounter | As for create | As for create |
| delete, both APIs | The create check, on the record's encounter | As for create | As for create |
| upsert, both APIs | The create or update check, for each datapoint | As for create and update | As for create and update |

* "In the encounter" means a role in one of the encounter's facility organizations or in a facility organization of its current location.
* The encounter's facility organizations are its departments, the parents of each department, and the facility's root department, "Administration".
* A user's roles on the patient come from three places. These are the facility organizations of the patient's open encounters and their current locations, the patient's organizations, and a direct patient link.
* An encounter is closed when its status is `completed`, `cancelled`, `entered_in_error` or `discontinued`. On a closed encounter, create, update and delete fail with "You do not have permission to update encounter".
* The exception is a diagnosis of category `chronic_condition`: its update checks only the patient permission, with no encounter status check.
* A read with `?encounter=` passes when the user holds "Can Read encounter related clinical data" in that encounter. No role on the patient is needed.
* After an encounter closes, roles held only through that encounter stop counting as roles on the patient.
* The encounter clinical-data read check has no status condition. So such a user can still read that encounter's conditions with `?encounter=`, through "Can Read encounter related clinical data" in the encounter.
* By default, Doctor, Nurse and Facility Admin hold "Update Encounter related clinical data" and "Can Read encounter related clinical data".
* By default, Staff, Doctor, Nurse and Facility Admin hold "Can view clinical data about patients".
* So, by default, Staff can read conditions but cannot create, update or delete them. The exception is the update of a `chronic_condition` diagnosis, which needs only "Can view clinical data about patients".
* `role.py` defines an Admin role with the facility context, but no Admin role can be given in a facility department. Roles sync by name, and the role-organization Admin syncs after the facility Admin and replaces its contexts.
* So only one Admin role exists, for role organizations only. In a facility, the default roles that can write conditions are Doctor, Nurse and Facility Admin.
* These role lists are defaults. Roles are editable.
* The value set search that picks a `code` needs no other permission. Every signed-in user can read instance-level value sets.
* Care's frontend does not check "Update Encounter related clinical data" before it shows the Symptom and Diagnosis forms. The backend checks it when the form saves, except for the update of a `chronic_condition` diagnosis.

### Errors

| Message | Cause |
| - | - |
| "Encounter not found" | The `encounter` in a create request does not exist |
| "Patient external ID mismatch with encounter's patient" | The condition's encounter belongs to another patient than the one in the URL |
| "Onset date cannot be in the future" | `onset.onset_datetime` is in the future |
| "Valueset does not exist in care, Resync valuesets" | No stored value set has the bound slug |
| "Code does not exist in the valueset" | `code` is not in the bound value set |
| "No datapoints provided" | An upsert with no datapoints |
| "Too many datapoints provided" | An upsert with more than `MAX_DATAPOINTS_PER_UPSERT` datapoints |
| "Permission denied to user" | The read check fails |
| "You do not have permission to update encounter" | The write check fails, or the encounter is closed |
| "You do not have permission to update chronic condition" | An update of a `chronic_condition` diagnosis without "Can view clinical data about patients" |

### Other notes

* The symptom API registers as an internal questionnaire of type `symptom`, titled "Symptom", with subject type `patient`.
* The diagnosis API registers as an internal questionnaire of type `diagnosis`, titled "Diagnosis", with subject type `patient`.
* In the form builder, the structured question types Symptom and Diagnosis are offered for encounter questionnaires. So a facility's own encounter forms can record conditions.
* Care's frontend creates every new diagnosis as `encounter_diagnosis`. No screen creates a `chronic_condition` record.
* Print templates: the report data for an encounter includes its `encounter_diagnosis` records as diagnoses and its `problem_list_item` records as symptoms.
* These print data points do not filter on verification status, so they include records entered in error.
* Send `code` as a coding from the bound value set, not as free text. Do not send `patient`: Care takes it from the encounter.

## Related

* Concept: [Condition](https://docs.ohc.network/concepts/clinical/condition.md)
* Flow: [Record a symptom](https://docs.ohc.network/flows/clinical/condition/record-symptom.md)
* Flow: [Record a diagnosis](https://docs.ohc.network/flows/clinical/condition/record-diagnosis.md)
* Flow: [Add a symptom or diagnosis from past records](https://docs.ohc.network/flows/clinical/condition/add-condition-from-past-records.md)
* Flow: [Update a symptom or diagnosis](https://docs.ohc.network/flows/clinical/condition/update-condition.md)
* Flow: [Mark a symptom or diagnosis as entered in error](https://docs.ohc.network/flows/clinical/condition/condition-entered-in-error.md)
* Flow: [View a patient's symptoms and diagnoses](https://docs.ohc.network/flows/clinical/condition/view-clinical-history.md)
* Reference: [Patient](https://docs.ohc.network/references/clinical/patient.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [Questionnaire Response](https://docs.ohc.network/references/clinical/questionnaire-response.md)
* Reference: [Value Set](https://docs.ohc.network/references/definitions/valueset.md)
* Reference: [Permission](https://docs.ohc.network/references/access-governance/permission.md) · [Role](https://docs.ohc.network/references/access-governance/role.md)
* Base: [EMRBaseModel](https://docs.ohc.network/references/foundation/base-model.md)
* FHIR: [Condition](https://build.fhir.org/condition.html)
* Source: [condition.py (model)](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/condition.py) · [spec.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/condition/spec.py) · [valueset.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/condition/valueset.py) · [condition.py (viewsets)](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/condition.py)
