diff --git a/versioned_docs/version-3.0/references/clinical/condition.mdx b/versioned_docs/version-3.0/references/clinical/condition.mdx index ea3c2e50..ba3de98c 100644 --- a/versioned_docs/version-3.0/references/clinical/condition.mdx +++ b/versioned_docs/version-3.0/references/clinical/condition.mdx @@ -41,7 +41,7 @@ A `Condition` lives across two layers, and the split matters when you read the c | Field | Type | Notes | | --- | --- | --- | | `code` | `JSONField` (`default=dict`, not null/blank) | The condition itself. On write, a single [`Coding`](#coding-shape) bound to the [`CARE_CODITION_CODE_VALUESET`](#code-value-set-binding) value set (SNOMED CT clinical findings). On read, serialized as a plain `Coding`. | -| `body_site` | `JSONField` (`default=dict`, not null/blank) | Anatomical location(s). Exists on the model but no current spec exposes it — never written or read through the standard `Condition` API. | +| `body_site` | `JSONField` (`default=dict`, not null/blank) | Anatomical location. Optional on write: a single [`Coding`](#coding-shape) bound to `CARE_BODY_SITE_VALUESET` (slug `system-body-site-observation`, SNOMED CT). On read, serialized as a plain `Coding` or `null`. | ### Timing @@ -139,6 +139,10 @@ These spec classes (all extend `EMRResource`) are the real structure behind the On write, `code` is typed `ValueSetBoundCoding[CARE_CODITION_CODE_VALUESET.slug]` — a `Coding` checked against the Condition code value set (`care/emr/resources/condition/valueset.py`, slug `system-condition-code`), which covers SNOMED CT concepts that are `is-a` `404684003` (*Clinical finding*). Codes outside it are rejected on `ConditionSpec`, `ConditionUpdateSpec`, and `ChronicConditionUpdateSpec`. The read spec falls back to a plain `Coding` and skips value-set validation, so reads stay cheap. +### `body_site` value-set binding + +On write, `body_site` is typed `ValueSetBoundCoding[CARE_BODY_SITE_VALUESET.slug]` and is optional (`None` by default). The value set (`care/emr/resources/observation/valueset.py`, slug `system-body-site-observation`) is the same one [Observation](../clinical/observation.mdx) uses: a curated list of SNOMED CT body-structure concepts plus every descendant of `442083009` (*Body structure, altered from its original anatomical structure*). `ConditionSpec` and `ConditionUpdateSpec` both accept it; `ConditionReadSpec` returns a plain `Coding` or `null`. + ## Resource specs (API schema) Every spec extends `BaseConditionSpec` → `EMRResource` and round-trips through `serialize` (DB → Pydantic) and `de_serialize` (Pydantic → DB). `BaseConditionSpec` sets `__model__ = Condition`, sets `__exclude__ = ["patient", "encounter"]` (both server-maintained, never trusted from the client), and exposes `id: UUID4`. @@ -146,20 +150,20 @@ Every spec extends `BaseConditionSpec` → `EMRResource` and round-trips through | Spec class | Role | Exposes / behaviour | | --- | --- | --- | | `BaseConditionSpec` | shared base | `id`; excludes `patient` and `encounter` from direct mapping. | -| `ConditionSpec` | write · create | `clinical_status?`, `verification_status` (**required**), `severity?`, `code` (value-set bound, **required**), `encounter` (UUID4, **required**), `onset` (`={}`), `abatement` (`={}`), `note?`, `category` (**required**). Validates that the encounter exists; on create sets `obj.encounter` and `obj.patient = encounter.patient`. | -| `ConditionUpdateSpec` | write · update | `clinical_status?`, `verification_status` (**required**), `severity?`, `code` (value-set bound, **required**), `onset` (`={}`), `abatement` (`={}`), `note?`. Does **not** accept `encounter`, `category`, or `patient`. | +| `ConditionSpec` | write · create | `clinical_status?`, `verification_status` (**required**), `severity?`, `code` (value-set bound, **required**), `body_site?` (value-set bound), `encounter` (UUID4, **required**), `onset` (`={}`), `abatement` (`={}`), `note?`, `category` (**required**). Validates that the encounter exists; on create sets `obj.encounter` and `obj.patient = encounter.patient`. | +| `ConditionUpdateSpec` | write · update | `clinical_status?`, `verification_status` (**required**), `severity?`, `code` (value-set bound, **required**), `body_site?` (value-set bound), `onset` (`={}`), `abatement` (`={}`), `note?`. Does **not** accept `encounter`, `category`, or `patient`. | | `ChronicConditionUpdateSpec` | write · update (chronic) | Extends `ConditionUpdateSpec` and adds `encounter` (UUID4). On deserialize, if `encounter` is set, resolves it (`get_object_or_404`) and assigns `obj.encounter`. | -| `ConditionReadSpec` | read · detail/list | `clinical_status`, `verification_status`, `category`, `criticality`, `severity` (all plain `str`), `code` (plain `Coding`), `encounter` (UUID4), `onset`, `abatement`, `created_by?`, `updated_by?`, `note?`, `created_date`, `modified_date`. | +| `ConditionReadSpec` | read · detail/list | `clinical_status`, `verification_status`, `category`, `criticality`, `severity` (all plain `str`), `code` (plain `Coding`), `body_site` (plain `Coding \| None`), `encounter` (UUID4), `onset`, `abatement`, `created_by?`, `updated_by?`, `note?`, `created_date`, `modified_date`. | ### Validation & server-side behaviour - Encounter is required and verified on create. `ConditionSpec.validate_encounter_exists` rejects unknown encounter UUIDs; `perform_extra_deserialization` (create only) loads the encounter and derives `patient` from it. Clients never set `patient` or `encounter` directly. - `verification_status` is mandatory on both `ConditionSpec` and `ConditionUpdateSpec`; `category` is mandatory only on create (`ConditionSpec`). -- `code` must belong to the bound value set (SNOMED CT clinical findings) on every write spec. +- `code` must belong to the bound value set (SNOMED CT clinical findings) on every write spec; `body_site`, when sent, must belong to the body-site value set. - `onset_datetime` cannot be in the future and is forced timezone-aware; `abatement_datetime` carries no such constraint. - `ConditionReadSpec` exposes `criticality`, a string in the read schema with no backing column on the `Condition` model. The standard serializer never populates it, so it comes back unset. - Read serialization (`perform_extra_serialization`) maps `id = external_id`, replaces `encounter` with its `external_id`, and expands `created_by`/`updated_by` via `serialize_audit_users` (cached `UserSpec`). -- `body_site` and `recorded_date` exist on the model but no current spec reads or writes them — storage-only, outside the standard `Condition` API surface. +- `body_site` and `recorded_date` exist on the model. `body_site` is read and written by the specs as a bound `Coding`; `recorded_date` is storage-only and outside the standard `Condition` API surface. ## Related models @@ -182,7 +186,7 @@ Deleting a `Patient` or `Encounter` cascades to its `Condition` rows. The column ## API integration notes -- Send `code` as a structured `Coding` (`{system, code, display}`) drawn from the SNOMED CT clinical-finding value set, not as free text. Always include `verification_status`; add `category` and `encounter` when creating. +- Send `code` as a structured `Coding` (`{system, code, display}`) drawn from the SNOMED CT clinical-finding value set, not as free text. Always include `verification_status`; add `category` and `encounter` when creating. Send `body_site` as a `Coding` from the body-site value set when the anatomical location matters. - `onset` and `abatement` are structured choice-of-type objects (`*_datetime`, `*_age`, `*_string`, `note`), not arbitrary JSON. `onset_datetime` must be timezone-aware and not in the future. - Don't send `patient`, `external_id`, audit fields, or `deleted` from the client — the server owns them. diff --git a/versioned_docs/version-3.0/references/clinical/detected-issue.mdx b/versioned_docs/version-3.0/references/clinical/detected-issue.mdx new file mode 100644 index 00000000..97ce975a --- /dev/null +++ b/versioned_docs/version-3.0/references/clinical/detected-issue.mdx @@ -0,0 +1,193 @@ +--- +sidebar_position: 6 +description: "Technical reference for the Detected Issue module in Care EMR: models, specs, enums, permissions and validation." +--- + +# Detected Issue + +A `DetectedIssue` records a clinical risk found during an encounter — a drug interaction, a dose problem, a duplicate therapy, or a care gap. It maps to the FHIR `DetectedIssue` resource. Each issue points at the clinical records that caused it, and carries the notes that describe how staff mitigated it. + +**Source:** +- Model: [`care/emr/models/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/detected_issue.py) +- Resource spec: [`care/emr/resources/detected_issue/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/spec.py) +- Constants: [`care/emr/resources/detected_issue/constants.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/constants.py) +- Viewsets: [`care/emr/api/viewsets/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/detected_issue.py) +- Permissions: [`care/security/permissions/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/detected_issue.py) + +A detected issue lives across two layers. The Django models are storage: `code` and `metadata` are opaque `JSONField`s, and `status`, `category`, and `severity` are plain `CharField`s. The Pydantic resource specs are the API layer. They supply the enums, the read and write schemas, and the validation. + +## Models + +| Model | Purpose | +| --- | --- | +| `DetectedIssue` | A clinical risk detected for a patient during an encounter | +| `DetectedIssueMitigation` | A note that records the action taken against an issue | +| `DetectedIssueResource` | A link from an issue to the clinical record that caused it | + +All three extend [`EMRBaseModel`](../foundation/base-model.mdx), the shared Care EMR base that gives `external_id`, `created_date`/`modified_date`, `created_by`/`updated_by`, soft-delete through `deleted`, and `history`/`meta` JSON. + +## `DetectedIssue` fields + +| Field | Type | Notes | +| --- | --- | --- | +| `status` | `CharField(25)` | Lifecycle state. Spec binds it to [`DetectedIssueStatusOptions`](#detectedissuestatusoptions-values); required on create | +| `category` | `CharField(25)` | Kind of risk. Spec binds it to [`DetectedIssueCategoryOptions`](#detectedissuecategoryoptions-values); required on create | +| `severity` | `CharField(25)` | How serious the risk is. Spec binds it to [`DetectedIssueSeverityOptions`](#detectedissueseverityoptions-values); required on create | +| `code` | `JSONField`, nullable | Coded detail of the issue. No current spec reads or writes it — storage only | +| `encounter` | `FK → Encounter`, `on_delete=PROTECT` | The encounter the issue belongs to. Required on create as a UUID; the server resolves it | +| `patient` | `FK → Patient`, `on_delete=PROTECT`, not null | Subject of the issue. Taken from the URL, never from the body (`__exclude__`) | + +## Enums + +Every enum is a `str, Enum` in `care/emr/resources/detected_issue/constants.py`. The value stored and serialized is the string in the table. + +### `DetectedIssueStatusOptions` values + +| Value | Meaning | +| --- | --- | +| `draft` | Issue is not yet published | +| `active` | Issue is open | +| `inactive` | Issue no longer applies | +| `not_done` | Issue was not acted on | +| `entered_in_error` | Issue was recorded by mistake | + +### `DetectedIssueSeverityOptions` values + +| Value | +| --- | +| `high` | +| `moderate` | +| `low` | + +### `DetectedIssueMitigationStatusOptions` values + +| Value | Meaning | +| --- | --- | +| `active` | Mitigation applies. Model default | +| `entered_in_error` | Mitigation was recorded by mistake | + +### `DetectedIssueCategoryOptions` values + +The category codes come from the FHIR `DetectedIssue` category value set (`http://hl7.org/fhir/ValueSet/detectedissue-category`), with codes from `http://terminology.hl7.org/CodeSystem/v3-ActCode`. The abstract grouping codes of `v3-ActCode` (the `notSelectable` codes with a `_` prefix) are not included. + +| Group | Values | +| --- | --- | +| Product and interaction alerts | `FOOD`, `TPROD`, `DRG`, `NHP`, `NONRX`, `OBSA` | +| Age alerts | `AGE`, `ADALRT`, `DOSEHINDA`, `DOSELINDA`, `GEALRT`, `PEALRT` | +| Condition alerts | `COND`, `HGHT`, `LACT`, `PREG`, `WGHT` | +| Reaction and allergy alerts | `CREACT`, `GEN`, `GEND`, `LAB`, `REACT`, `ALGY`, `INT`, `RREACT`, `RALG`, `RAR`, `RINT` | +| Compliance alerts | `PREVINEF`, `COMPLY`, `DUPTHPY`, `DUPTHPCLS`, `DUPTHPGEN`, `ABUSE`, `FRAUD`, `PLYDOC`, `PLYPHRM` | +| Dose alerts | `DACT`, `DOSE`, `DOSECOND`, `DOSEDUR`, `DOSEDURH`, `DOSEDURHIND`, `DOSEDURL`, `DOSEDURLIND`, `DOSEH`, `DOSEHIND`, `DOSEHINDSA`, `DOSEHINDW`, `DOSEIVL`, `DOSEIVLIND`, `DOSEL`, `DOSELIND`, `DOSELINDSA`, `DOSELINDW`, `MDOSE` | +| Timing alerts | `TIME`, `ALRTENDLATE`, `ALRTSTRTLATE`, `ENDLATE`, `STRTLATE`, `TIMING`, `INTERVAL`, `MINFREQ`, `HELD`, `TOOLATE`, `TOOSOON` | +| Fulfilment alerts | `ALLDONE`, `FULFIL`, `NOTACTN`, `NOTEQUIV`, `NOTEQUIVGEN`, `NOTEQUIVTHER` | +| Other | `HISTORIC`, `PATPREF`, `PATPREFALT`, `CAREGAP`, `CODINGGAP` | + +### `DetectedIssueResourceType` values + +The record types an issue can point at. Each value maps to a handler in [`care/emr/utils/resource_reference.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/utils/resource_reference.py), which does the read authorization and the rendering. + +| Value | +| --- | +| `diagnostic_report` | +| `observation` | +| `condition` | +| `allergy_intolerance` | +| `service_request` | +| `specimen` | +| `questionnaire_response` | +| `file_upload` | +| `immunization` | +| `medication_request` | + +## Related models + +### `DetectedIssueMitigation` + +Records what staff did about an issue. A mitigation is append-only: the note cannot change after creation, and the only update allowed sets the status to `entered_in_error`. + +| Field | Type | Notes | +| --- | --- | --- | +| `detected_issue` | `FK → DetectedIssue` (CASCADE) | `related_name="mitigation"`. Set from the URL | +| `note` | `TextField` | Required. Stripped of outer whitespace and must not be empty | +| `status` | `CharField(25)`, default `"active"` | One of [`DetectedIssueMitigationStatusOptions`](#detectedissuemitigationstatusoptions-values) | +| `entered_in_error_by` | `FK → users.User` (PROTECT), nullable | Set by the server when the status changes to `entered_in_error` | +| `entered_in_error_at` | `DateTimeField`, nullable | Set by the server at the same time | + +### `DetectedIssueResource` + +Links an issue to the clinical record that caused it. + +| Field | Type | Notes | +| --- | --- | --- | +| `detected_issue` | `FK → DetectedIssue` (CASCADE) | `related_name="resources"`. Set from the URL | +| `resource_type` | `CharField(100)` | One of [`DetectedIssueResourceType`](#detectedissueresourcetype-values) | +| `resource_id` | `UUIDField` | The `external_id` of the linked record | +| `metadata` | `JSONField`, default `{}` | Free-form client metadata about the link | + +A partial `UniqueConstraint` named `unique_detected_issue_resource` covers `resource_type`, `resource_id`, and `detected_issue` where `deleted=False`. A duplicate link returns a validation error ("Resource is already attached to this detected issue"). The resource columns lead the index, so the same index also serves the reverse lookup that finds issues for a set of records. + +### Relationships + +```text +DetectedIssue.patient → FK Patient (PROTECT, from the URL) +DetectedIssue.encounter → FK Encounter (PROTECT, required on create) +DetectedIssueMitigation.detected_issue → FK DetectedIssue (CASCADE, related_name="mitigation") +DetectedIssueResource.detected_issue → FK DetectedIssue (CASCADE, related_name="resources") +``` + +## Resource specs (API schema) + +Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py)) unless the table says otherwise. `DetectedIssueBaseSpec` sets `__model__ = DetectedIssue` and `__exclude__ = ["patient", "encounter", "resources"]`, so none of the three is read from the generic field loop. + +| Spec class | Role | Exposes / behaviour | +| --- | --- | --- | +| `DetectedIssueBaseSpec` | shared base | `id`, `status`, `category`, `severity` | +| `DetectedIssueCreateSpec` | write · create | Base + `encounter` (UUID4, required) and `resources` (`list[DetectedIssueResourceCreateSpec]`, default `[]`). Resolves the encounter and holds the resource list for the viewset | +| `DetectedIssueUpdateSpec` | write · update | `status`, `category`, `severity`, each `MISSING` by default. A field left out keeps its stored value. `encounter`, `patient`, and `resources` cannot change | +| `DetectedIssueListSpec` | read · list | Base + `patient` (UUID4), `encounter` (UUID4), `created_date`, `modified_date`, `created_by?`, `updated_by?` | +| `DetectedIssueRetrieveSpec` | read · detail | List spec + `resources` (`DetectedIssueResourceReadSpec[]`) and `mitigation` (`DetectedIssueMitigationReadSpec[]`) | +| `DetectedIssueResourceCreateSpec` | write · create | `resource_type`, `resource_id` (UUID4), `metadata` (default `{}`) | +| `DetectedIssueResourceReadSpec` | read | Create spec + `id`, `detected_issue` (UUID4), `created_date`, `modified_date`, `created_by?`, `updated_by?` | +| `DetectedIssueMitigationCreateSpec` | write · create | `note` only (`extra="forbid"`, whitespace stripped, `min_length=1`) | +| `DetectedIssueMitigationUpdateSpec` | write · update | Plain `BaseModel`, `extra="forbid"`. `status` is a `Literal["entered_in_error"]` — the only allowed update | +| `DetectedIssueMitigationReadSpec` | read | `id`, `detected_issue`, `note`, `status`, `entered_in_error_by?`, `entered_in_error_at?`, audit fields | +| `DetectedIssueResolvedResourceSpec` | read (action) | `resource_type` and the rendered `resource` dict, returned by the `resolve` action | +| `DetectedIssueResourceLookupRequest` | write (action body) | `encounter` (UUID4), `resource_type`, `resource_ids` (1–100 UUID4s). `extra="forbid"` | +| `DetectedIssueResourceLookupResponse` | read (action) | `results`: a list of `DetectedIssueRetrieveSpec` | + +### Validation & server-maintained behaviour + +- `patient` comes from the URL. On create the viewset checks that the supplied `encounter` belongs to that patient, else "Patient does not match the encounter patient". +- `resources` sent inside the create body are saved in the same transaction as the issue, through the same validation as the standalone resource endpoint. +- A linked record must belong to the issue's patient, and the caller must be able to read it. For a `file_upload`, the file must be uploaded and not archived, and its owning record (`patient`, `encounter`, `diagnostic_report`, `service_request`, `referral`, or `consent`) must resolve to the same patient. +- Updating a mitigation takes a row lock and only writes when the status really changes. It then stamps `entered_in_error_by`, `entered_in_error_at`, and `updated_by`. +- The list endpoint requires an `encounter` query parameter — detected issues are always listed per encounter. `status`, `category`, and `severity` are the supported filters, and `created_date` / `modified_date` are the ordering fields. + +## Permissions + +Detected issues are authorized at the encounter level. Both checks run through the encounter's facility organizations (and the organizations of its current location). + +| Permission | Allows | Default roles | +| --- | --- | --- | +| `can_read_detected_issue` | Read issues, their resources, and their mitigations | Facility Admin, Administrator, Admin, Staff, Doctor, Nurse, Volunteer, Pharmacist | +| `can_write_detected_issue` | Create and update issues, with their resources and mitigations | Facility Admin, Admin, Doctor, Nurse | + +Write access is also refused when the encounter is already in a completed state. + +## API integration notes + +- Endpoints are nested under the patient: `/patient/{patient_external_id}/detected_issue/`, with `resources/` and `mitigations/` nested under an issue. +- `POST .../detected_issue/by_resources/` returns the issues of one encounter that reference a given set of records. Send `encounter`, `resource_type`, and 1–100 `resource_ids`. +- `GET .../resources/{external_id}/resolve/` returns the linked record itself, rendered with that resource type's read spec, after a fresh read-permission check. +- Create and update return the full `DetectedIssueRetrieveSpec`, so the resources and mitigations come back in the same response. +- Do not send `patient`, `external_id`, audit fields, or `deleted` — the server owns them. + +## Related + +- Reference: [Patient](../clinical/patient) +- Reference: [Encounter](../clinical/encounter.mdx) +- Reference: [Condition](../clinical/condition.mdx) +- Reference: [Allergy intolerance](../clinical/allergy-intolerance.mdx) +- Reference: [Medication request](../medications/medication-request.mdx) +- Reference: [Base model](../foundation/base-model.mdx) +- Source: [detected_issue.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/detected_issue.py) · [spec.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/spec.py) · [constants.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/constants.py) diff --git a/versioned_docs/version-3.0/references/clinical/encounter.mdx b/versioned_docs/version-3.0/references/clinical/encounter.mdx index 388ca271..9c8f664e 100644 --- a/versioned_docs/version-3.0/references/clinical/encounter.mdx +++ b/versioned_docs/version-3.0/references/clinical/encounter.mdx @@ -191,8 +191,8 @@ All specs build on `EMRResource`, which provides `serialize` / `de_serialize` pl | `EncounterSpecBase` | shared | Fields: `id`, `status`, `encounter_class`, `period` (`PeriodSpec`, default `{}`), `hospitalization` (`HospitalizationSpec \| None`, default `{}`), `priority`, `external_identifier`, `discharge_summary_advice`. `__model__ = Encounter` | | `EncounterCreateSpec` | write · create | Extends base + `ExtensionValidator`. Adds `patient: UUID4`, `facility: UUID4`, `organizations: list[UUID4] = []`, `appointment: UUID4 \| None`. Resolves FKs by `external_id`; validates appointment belongs to the patient and facility | | `EncounterUpdateSpec` | write · update | Extends base + `ExtensionValidator`. Does not accept `patient`/`facility`/`organizations`/`appointment` — only mutable fields. Appends to status/class history on change | -| `EncounterListSpec` | read · list | Adds serialized `patient` ([`PatientListSpec`](../clinical/patient)), `facility` (`FacilityBareMinimumSpec`), `status_history`, `encounter_class_history`, `created_date`, `modified_date`, `tags`, `current_location` (`FacilityLocationMinimalListSpec \| None`), `care_team` (`[{ member, role }]`) | -| `EncounterRetrieveSpec` | read · detail | Extends list + `EncounterPermissionsMixin`. Adds `appointment` (`TokenBookingReadSpec`), `created_by`/`updated_by` ([`UserSpec`](../access-governance/user.mdx)), `organizations` (`FacilityOrganizationReadSpec[]`), `location_history` (`FacilityLocationEncounter[]`, newest first), `extensions`; patient via `PatientRetrieveSpec` | +| `EncounterListSpec` | read · list | Extends base + `ExtensionListRenderer`. Adds serialized `patient` ([`PatientListSpec`](../clinical/patient)), `facility` (`FacilityBareMinimumSpec`), `status_history`, `encounter_class_history`, `created_date`, `modified_date`, `tags`, `current_location` (`FacilityLocationMinimalListSpec \| None`), `care_team` (`[{ member, role }]`), `extensions` (rendered through `deserialize_extensions_list`) | +| `EncounterRetrieveSpec` | read · detail | Extends list + `ExtensionRetrieveRenderer` + `EncounterPermissionsMixin`. Adds `appointment` (`TokenBookingReadSpec`), `created_by`/`updated_by` ([`UserSpec`](../access-governance/user.mdx)), `organizations` (`FacilityOrganizationReadSpec[]`), `location_history` (`FacilityLocationEncounter[]`, newest first); patient via `PatientRetrieveSpec`; `extensions` re-rendered through `deserialize_extensions_retrieve` | | `HospitalizationSpec` | nested | Plain `BaseModel`; see shape above | | `EncounterCareTeamMemberSpec` | nested (write) | `{ user_id: UUID4, role: Coding }`, `role` bound to the `system-practitioner-role-code` value set | | `EncounterCareTeamMemberWriteSpec` | write · care team | `{ members: list[EncounterCareTeamMemberSpec] }`. Dedicated payload for replacing the care team | @@ -252,7 +252,7 @@ Expect two write passes per create or update through the ORM, plus identifier-de - Create and update don't touch the care team. Replace it through the dedicated care-team endpoint with `EncounterCareTeamMemberWriteSpec`, where each member's `role` must resolve within the `system-practitioner-role-code` value set. - `period` and `hospitalization` carry structured JSON matching the nested-spec shapes above; `period.start` and `period.end` must be timezone-aware. - `current_location` is a cached convenience field. The authoritative record is `location_history`, from `FacilityLocationEncounter`. -- `extensions` holds custom key-value data without a schema migration, validated by `ExtensionValidator`. +- `extensions` holds custom key-value data without a schema migration, validated by `ExtensionValidator` on write. On read, each registered extension handler renders its own payload — list reads use the short form, detail reads the full form — so a key can hold less data in a list response than in a detail response. ## Related diff --git a/versioned_docs/version-3.0/references/definitions/product-knowledge.mdx b/versioned_docs/version-3.0/references/definitions/product-knowledge.mdx index d2d6146f..9d506c97 100644 --- a/versioned_docs/version-3.0/references/definitions/product-knowledge.mdx +++ b/versioned_docs/version-3.0/references/definitions/product-knowledge.mdx @@ -43,6 +43,15 @@ The Django model is only the storage layer: `code`, `names`, `storage_guidelines | `names` | `JSONField` (list) | Nullable; list of `ProductName { name_type: ProductNameTypes, name: str }`. `name_type` is bound to the `ProductNameTypes` enum, not a FHIR value set | | `names_cache` | `CharField(2048)` | Nullable; denormalized space-joined string of `name` plus every `names` entry, rebuilt on each `save()` to power search. Platform-maintained, absent from every spec — never set it from clients | +### Tags + +| Field | Type | Notes | +| --- | --- | --- | +| `tags` | `ArrayField[int]`, default `[]` | Applied [tag](../platform/tag-config.mdx) ids. Written through the tag actions, rendered on read by `SingleFacilityTagManager` | +| `tags_data` | `JSONField`, default `{}` | Denormalized tag payload maintained by the tagging layer. Not exposed by any spec | + +A product definition is taggable: `TagConfig` accepts `product_knowledge` as a `resource` value, and the viewset carries `EMRTagMixin` plus `SingleFacilityTagFilter`. Pass `?tags=` on the list endpoint to filter definitions by tag. Instance-level definitions take instance-level tags; facility-scoped definitions take that facility's tags. + ### Coding & definition (JSON fields) The model stores these as bare `JSONField`s; the spec enforces the shapes below. @@ -204,7 +213,7 @@ Every spec builds on `EMRResource` (`care/emr/resources/base.py`), which provide | `BaseProductKnowledgeSpec` | shared base | `__exclude__ = ["facility"]`. Fields: `id`, `alternate_identifier`, `status`, `product_type`, `code`, `base_unit` (required, UCUM-bound), `name`, `names`, `storage_guidelines`, `definitional` | | `ProductKnowledgeUpdateSpec` | write · update | Adds `category: str \| None` (resource-category **slug**) and `slug_value: SlugType` (required). On deserialize, resolves `category` via `ResourceCategory.objects.get(slug=...)` and sets `obj.slug = self.slug_value` | | `ProductKnowledgeWriteSpec` | write · create | Extends the update spec; adds `facility: UUID4 \| None`. On deserialize, runs the update-spec logic, then resolves `facility` via `Facility.objects.get(external_id=...)` when supplied | -| `ProductKnowledgeReadSpec` | read · detail/list | Adds `is_instance_level: bool`, `category: dict \| None`, `slug_config: dict`, `slug: str`. On serialize, sets `id = external_id`, `is_instance_level = not facility_id`, serializes `category` via `ResourceCategoryReadSpec`, and sets `slug_config = parse_slug(slug)` | +| `ProductKnowledgeReadSpec` | read · detail/list | Adds `is_instance_level: bool`, `category: dict \| None`, `slug_config: dict`, `slug: str`, `tags: list[dict]`. On serialize, sets `id = external_id`, `is_instance_level = not facility_id`, serializes `category` via `ResourceCategoryReadSpec`, sets `slug_config = parse_slug(slug)`, and renders `tags` with `SingleFacilityTagManager` | ### Validation & bound value sets @@ -218,7 +227,7 @@ Every spec builds on `EMRResource` (`care/emr/resources/base.py`), which provide - `facility` never flows through the generic field loop (it sits in `__exclude__`); only `ProductKnowledgeWriteSpec` (create) sets it, from the `facility` UUID. - `slug` is set server-side from `slug_value`; `names_cache` is rebuilt in the model's `save()` (see below). -- On read, `is_instance_level`, `slug_config`, and the serialized `category` are computed in `perform_extra_serialization` — none are stored columns. +- On read, `is_instance_level`, `slug_config`, the serialized `category`, and `tags` are computed in `perform_extra_serialization` — none are stored columns. ## Methods & save behaviour @@ -242,6 +251,7 @@ Every spec builds on `EMRResource` (`care/emr/resources/base.py`), which provide ## Related - Reference: [Product](../supply/product.mdx) +- Reference: [Tagging](../platform/tag-config.mdx) - Reference: [Inventory Item](../supply/inventory-item.mdx) - Reference: [Resource Category](../platform/resource-category.mdx) - Base: [Base model](../foundation/base-model.mdx) diff --git a/versioned_docs/version-3.0/references/platform/tag-config.mdx b/versioned_docs/version-3.0/references/platform/tag-config.mdx index ebb6a997..f74df901 100644 --- a/versioned_docs/version-3.0/references/platform/tag-config.mdx +++ b/versioned_docs/version-3.0/references/platform/tag-config.mdx @@ -95,6 +95,8 @@ A tag is scoped to at most one owner — an instance-wide organization, a facili | `supply_request_order` | | `supply_delivery_order` | | `account` | +| `location` | +| `product_knowledge` | ### `TagStatus` values diff --git a/versioned_docs/version-3.0/references/scheduling/schedule.mdx b/versioned_docs/version-3.0/references/scheduling/schedule.mdx index c4615bd8..4cadeb86 100644 --- a/versioned_docs/version-3.0/references/scheduling/schedule.mdx +++ b/versioned_docs/version-3.0/references/scheduling/schedule.mdx @@ -34,6 +34,9 @@ All four extend [`EMRBaseModel`](../foundation/base-model.mdx), which supplies ` | `valid_to` | `DateTimeField` | yes | End of the effective window. Must be ≥ now | | `revisit_allowed_days` | `IntegerField` | no | Nullable. Window within which a follow-up uses the revisit charge. Settable only via the `set_charge_item_definition` action | | `is_public` | `BooleanField` | yes | Exposes the schedule for public booking. Model default `False` | +| `encounter_type` | `CharField(100)` | no | Nullable. Class of encounter started from a booking. Bound to `ClassChoices` in the specs | +| `questionnaire_id` | `TextField` | no | Nullable. Identifier (slug or UUID) of the questionnaire to show for a booking against this schedule. Free text — the server does not resolve it | +| `extensions` | `JSONField`, default `{}` | no | Open extension bag for deployment-specific metadata. Validated by `ExtensionValidator` against `ExtensionResource.schedule` | ### Billing links @@ -144,10 +147,12 @@ Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care | Spec | Role | Exposes / behaviour | | --- | --- | --- | -| `ScheduleBaseSpec` | shared | `id`, `is_public`. `__exclude__ = ["resource", "facility"]` | -| `ScheduleCreateSpec` | write · create | `facility`, `name`, `valid_from`, `valid_to`, `availabilities: list[AvailabilityForScheduleSpec]`, `resource_type`, `resource_id`, `is_public`. Validates dates ≥ now, `valid_from ≤ valid_to`, and cross-availability non-overlap. `perform_extra_deserialization` stashes `facility`, `_resource_id`, `_resource_type`, and `availabilities` on the instance for the viewset | -| `ScheduleUpdateSpec` | write · update | `name`, `valid_from`, `valid_to`, `is_public`. `perform_extra_deserialization` blocks narrowing validity that would drop allocated slots — it compares `Sum(TokenSlot.allocated)` across the old vs new range and raises if they differ | -| `ScheduleReadSpec` | read · list + detail | All of the above plus `availabilities` (re-serialized from `Availability` rows), `resource_type`, `charge_item_definition` / `revisit_charge_item_definition` (full `ChargeItemDefinitionReadSpec` or `null`), `revisit_allowed_days`, `created_by`, `updated_by` | +| `ScheduleBaseSpec` | shared | `id`, `is_public`, `encounter_type`, `questionnaire_id`. `__exclude__ = ["resource", "facility"]`; `___extension_resource_type__ = ExtensionResource.schedule` | +| `ScheduleWriteSpec` | shared write | Adds `organizations: list[UUID4]`, `care_team: list[EncounterCareTeamMemberSpec]`, and `extensions` (through `ExtensionValidator`). `encounter_type` and `questionnaire_id` default to `MISSING`, so a field left out of the body keeps its stored value. Checks that every organization and care-team member belongs to the schedule facility | +| `ScheduleCreateSpec` | write · create | Extends `ScheduleWriteSpec` with `facility`, `name`, `valid_from`, `valid_to`, `availabilities: list[AvailabilityForScheduleSpec]`, `resource_type`, `resource_id`. Validates dates ≥ now, `valid_from ≤ valid_to`, and cross-availability non-overlap. `perform_extra_deserialization` stashes `facility`, `_resource_id`, `_resource_type`, and `availabilities` on the instance for the viewset | +| `ScheduleUpdateSpec` | write · update | Extends `ScheduleWriteSpec` with `name`, `valid_from`, `valid_to`. `perform_extra_deserialization` blocks narrowing validity that would drop allocated slots — it compares `Sum(TokenSlot.allocated)` across the old vs new range and raises if they differ | +| `ScheduleReadSpec` | read · list | All of the above plus `availabilities` (re-serialized from `Availability` rows), `resource_type`, `charge_item_definition` / `revisit_charge_item_definition` (full `ChargeItemDefinitionReadSpec` or `null`), `revisit_allowed_days`, `created_by`, `updated_by`, and `extensions` rendered through `ExtensionListRenderer` | +| `ScheduleRetrieveSpec` | read · detail | Extends the read spec with `organizations` and `care_team` (both serialized), and renders `extensions` through `ExtensionRetrieveRenderer` | | `AvailabilityBaseSpec` | shared | `id`. `__exclude__ = ["schedule"]` | | `AvailabilityForScheduleSpec` | write/read (nested in schedule) | `name`, `slot_type`, `slot_size_in_minutes`, `tokens_per_slot`, `create_tokens`, `reason`, `availability: list[AvailabilityDateTimeSpec]`. Carries the availability + slot-type validators | | `AvailabilityCreateSpec` | write · create (standalone) | Adds `schedule: UUID4`; on create, re-checks overlap against all existing availabilities of that schedule | @@ -165,12 +170,15 @@ Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care - **Locking + slot guards.** Update and destroy take a `Lock("booking:resource:")`. Deleting a schedule or availability is rejected when future allocated `TokenSlot`s exist; otherwise availabilities and slots are soft-deleted (`deleted=True`). - **Exception slot clearing.** Creating an `AvailabilityException` soft-deletes overlapping `TokenSlot`s, but rejects the request if any are already allocated ("There are bookings during this exception"). - **List requires resource.** The `Schedule` and `AvailabilityException` list endpoints require `resource_type` and `resource_id` query params and scope results to that `SchedulableResource`. +- **Extensions.** `extensions` is validated on write against the handlers registered for `ExtensionResource.schedule`, and rendered on read — the list form through `deserialize_extensions_list`, the detail form through `deserialize_extensions_retrieve`. An unregistered key is dropped. +- **Booking metadata.** `serialize_schedule_metadata` carries `organizations`, `care_team`, `encounter_type`, and `questionnaire_id` onto the schedule block of a [booking](../scheduling/booking.mdx) read, so a client can open the right questionnaire at check-in without a second call. ## Integration notes - Slots are computed from `Availability` at read time, not stored as rows on the schedule. - When reading a `SchedulableResource`, dispatch on `resource_type` to pick the populated relation (`user`, `location`, or `healthcare_service`) — only one is set, and you can't assume which. - A `ChargeItemDefinition` referenced by a schedule can't be deleted while the schedule exists (`PROTECT`). +- `encounter_type` and `questionnaire_id` are `MISSING`-defaulted on write. Omit the key to keep the stored value; send `null` to clear it. ## Related diff --git a/versioned_docs/version-3.1/references/clinical/condition.mdx b/versioned_docs/version-3.1/references/clinical/condition.mdx index 725c081d..ba3de98c 100644 --- a/versioned_docs/version-3.1/references/clinical/condition.mdx +++ b/versioned_docs/version-3.1/references/clinical/condition.mdx @@ -1,84 +1,67 @@ --- sidebar_position: 3 -description: "Technical reference for the Condition module in Care EMR. For what a condition is, see the Condition concept." +description: "A Condition records a clinical problem, diagnosis, or symptom against a patient." --- # Condition -Technical reference for the `Condition` module in Care EMR. For what a condition is, see the [Condition](../../concepts/clinical/condition.mdx) 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. +A `Condition` records a clinical problem, diagnosis, or symptom against a patient. It maps to the FHIR `Condition` resource and shows up in the Care product UI as **Symptoms**. **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) +- Resource spec: [`care/emr/resources/condition/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/condition/spec.py) +- Value set: [`care/emr/resources/condition/valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/condition/valueset.py) -The Django model stores the data. Its `code`, `body_site`, `onset` and `abatement` fields are JSON fields. +A `Condition` lives across two layers, and the split matters when you read the code: -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. +- The Django model (`care/emr/models/condition.py`) is storage. Its coded and timing fields (`code`, `body_site`, `onset`, `abatement`) are opaque `JSONField`s — the model says nothing about their shape. +- The Pydantic resource specs (`care/emr/resources/condition/spec.py`) are the API. They define the enums, the structure inside each JSON field, field validation, the value-set binding for `code`, and the separate read and write schemas. ## Models | Model | Purpose | | --- | --- | -| `Condition` | One symptom or one diagnosis recorded for a patient | +| `Condition` | A clinical condition, problem, diagnosis, or symptom recorded for a patient | -`Condition` extends [`EMRBaseModel`](../foundation/base-model.mdx). That reference page describes the inherited fields. The "Inherited fields" table below lists the ones that the condition APIs use. +`Condition` extends [`EMRBaseModel`](../foundation/base-model.mdx), the shared Care EMR base that provides `external_id`, `created_date`/`modified_date`, soft-delete via `deleted`, `created_by`/`updated_by`, and `history`/`meta` JSON. ## `Condition` fields -Each table gives the storage type from the Django model and the API shape from the specs. +### Status & classification -### 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 | +| Field | Type | Notes | +| --- | --- | --- | +| `clinical_status` | `CharField(100)`, nullable | Clinical state. Spec binds to [`ClinicalStatusChoices`](#clinicalstatuschoices-values); optional on write. | +| `verification_status` | `CharField(100)`, nullable | Level of certainty. Spec binds to [`VerificationStatusChoices`](#verificationstatuschoices-values); **required** on write (`ConditionSpec`/`ConditionUpdateSpec`). | +| `category` | `CharField(100)`, nullable | Classification. Spec binds to [`CategoryChoices`](#categorychoices-values); **required** on create (`ConditionSpec`). | +| `severity` | `CharField(100)`, nullable | Subjective severity. Spec binds to [`SeverityChoices`](#severitychoices-values); optional on write. | ### 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 | +| Field | Type | Notes | +| --- | --- | --- | +| `code` | `JSONField` (`default=dict`, not null/blank) | The condition itself. On write, a single [`Coding`](#coding-shape) bound to the [`CARE_CODITION_CODE_VALUESET`](#code-value-set-binding) value set (SNOMED CT clinical findings). On read, serialized as a plain `Coding`. | +| `body_site` | `JSONField` (`default=dict`, not null/blank) | Anatomical location. Optional on write: a single [`Coding`](#coding-shape) bound to `CARE_BODY_SITE_VALUESET` (slug `system-body-site-observation`, SNOMED CT). On read, serialized as a plain `Coding` or `null`. | ### 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 | +| Field | Type | Notes | +| --- | --- | --- | +| `onset` | `JSONField` (`default=dict`) | Choice-of-type onset, shaped by [`ConditionOnSetSpec`](#conditiononsetspec-onset-shape). Defaults to `{}`. | +| `abatement` | `JSONField` (`default=dict`) | When the condition resolved or went into remission. Shaped by [`ConditionAbatementSpec`](#conditionabatementspec-abatement-shape). Defaults to `{}`. | +| `recorded_date` | `DateTimeField`, nullable | When the condition was first recorded. Not exposed by the current specs. | -### Inherited fields +### Context & notes -| Field | API shape | Notes | +| Field | Type | 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) | +| `patient` | `FK → Patient`, `on_delete=CASCADE` | Subject of the condition. Derived server-side from the encounter on create, never read from the client (`__exclude__`). | +| `encounter` | `FK → Encounter`, nullable, `on_delete=CASCADE` | Encounter the condition was recorded in. Set server-side on create (`__exclude__`); the client supplies a UUID in the spec, which is validated to exist. | +| `note` | `TextField`, nullable | Free-text clinical note. | -## Enum values +## Enums -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`. +Every enum is a `str, Enum` in `care/emr/resources/condition/spec.py`. The value stored and serialized is the string in the table. ### `ClinicalStatusChoices` values @@ -92,8 +75,6 @@ Every enum is a `str, Enum` in `care/emr/resources/condition/spec.py`. The model | `resolved` | | `unknown` | -Care's frontend form offers six of these values. It does not offer `unknown`. - ### `VerificationStatusChoices` values | Value | @@ -105,17 +86,13 @@ Care's frontend form offers six of these values. It does not offer `unknown`. | `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. +| Value | +| --- | +| `problem_list_item` | +| `encounter_diagnosis` | +| `chronic_condition` | ### `SeverityChoices` values @@ -127,216 +104,95 @@ Both create specs require `category`. The symptom API then overwrites it with `p ## Nested JSON shapes -### `onset` (`ConditionOnSetSpec`) +These spec classes (all extend `EMRResource`) are the real structure behind the model's JSON fields. -| 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 | +### `ConditionOnSetSpec` (`onset` shape) -### `abatement` (`ConditionAbatementSpec`) +| Field | Type | Default | Notes | +| --- | --- | --- | --- | +| `onset_datetime` | `datetime \| None` | `None` | Coerced to timezone-aware (`make_aware`) if naive. **Cannot be in the future** — a value `> care_now()` is rejected. | +| `onset_age` | `int \| None` | `None` | Age at onset. | +| `onset_string` | `str \| None` | `None` | Free-text onset description. | +| `note` | `str \| None` | `None` | Note about the onset. | -`ConditionAbatementSpec` extends `EMRResource`. +### `ConditionAbatementSpec` (`abatement` shape) -| Key | Type | Default | Meaning and validation | +| Field | Type | Default | Notes | | --- | --- | --- | --- | -| `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 | +| `abatement_datetime` | `datetime \| None` | `None` | Unlike `onset_datetime`, no future-date check. | +| `abatement_age` | `int \| None` | `None` | Age at abatement. | +| `abatement_string` | `str \| None` | `None` | Free-text abatement description. | +| `note` | `str \| None` | `None` | Note about the abatement. | -### `code` +### `Coding` shape -On write, `code` is a `ValueSetBoundCoding`. Care checks the coding against the bound value set (see "Bound value sets"). +`code` is a single [`Coding`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/common/coding.py), not a `CodeableConcept`. `extra="forbid"`. -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). +| Field | Type | Notes | +| --- | --- | --- | +| `system` | `str \| None` | Code system URI (e.g. `http://snomed.info/sct`). | +| `version` | `str \| None` | Code system version. | +| `code` | `str` | **Required.** The code value. | +| `display` | `str \| None` | Human-readable label. | -## Related models +### `code` value-set binding -`Condition` has two foreign keys to clinical records. +On write, `code` is typed `ValueSetBoundCoding[CARE_CODITION_CODE_VALUESET.slug]` — a `Coding` checked against the Condition code value set (`care/emr/resources/condition/valueset.py`, slug `system-condition-code`), which covers SNOMED CT concepts that are `is-a` `404684003` (*Clinical finding*). Codes outside it are rejected on `ConditionSpec`, `ConditionUpdateSpec`, and `ChronicConditionUpdateSpec`. The read spec falls back to a plain `Coding` and skips value-set validation, so reads stay cheap. -```text -patient → FK emr.Patient (CASCADE, required) -encounter → FK emr.Encounter (CASCADE, nullable; both create specs require it) -``` +### `body_site` value-set binding -Each create and update through either API also writes a [questionnaire response](./questionnaire-response.mdx) for the condition's patient and encounter. See "Methods & save behaviour". +On write, `body_site` is typed `ValueSetBoundCoding[CARE_BODY_SITE_VALUESET.slug]` and is optional (`None` by default). The value set (`care/emr/resources/observation/valueset.py`, slug `system-body-site-observation`) is the same one [Observation](../clinical/observation.mdx) uses: a curated list of SNOMED CT body-structure concepts plus every descendant of `442083009` (*Body structure, altered from its original anatomical structure*). `ConditionSpec` and `ConditionUpdateSpec` both accept it; `ConditionReadSpec` returns a plain `Coding` or `null`. ## 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`. +Every spec extends `BaseConditionSpec` → `EMRResource` and round-trips through `serialize` (DB → Pydantic) and `de_serialize` (Pydantic → DB). `BaseConditionSpec` sets `__model__ = Condition`, sets `__exclude__ = ["patient", "encounter"]` (both server-maintained, never trusted from the client), and exposes `id: UUID4`. -| Spec class | Role | Fields and behaviour | +| Spec class | Role | Exposes / 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 +| `BaseConditionSpec` | shared base | `id`; excludes `patient` and `encounter` from direct mapping. | +| `ConditionSpec` | write · create | `clinical_status?`, `verification_status` (**required**), `severity?`, `code` (value-set bound, **required**), `body_site?` (value-set bound), `encounter` (UUID4, **required**), `onset` (`={}`), `abatement` (`={}`), `note?`, `category` (**required**). Validates that the encounter exists; on create sets `obj.encounter` and `obj.patient = encounter.patient`. | +| `ConditionUpdateSpec` | write · update | `clinical_status?`, `verification_status` (**required**), `severity?`, `code` (value-set bound, **required**), `body_site?` (value-set bound), `onset` (`={}`), `abatement` (`={}`), `note?`. Does **not** accept `encounter`, `category`, or `patient`. | +| `ChronicConditionUpdateSpec` | write · update (chronic) | Extends `ConditionUpdateSpec` and adds `encounter` (UUID4). On deserialize, if `encounter` is set, resolves it (`get_object_or_404`) and assigns `obj.encounter`. | +| `ConditionReadSpec` | read · detail/list | `clinical_status`, `verification_status`, `category`, `criticality`, `severity` (all plain `str`), `code` (plain `Coding`), `body_site` (plain `Coding \| None`), `encounter` (UUID4), `onset`, `abatement`, `created_by?`, `updated_by?`, `note?`, `created_date`, `modified_date`. | + +### Validation & server-side behaviour + +- Encounter is required and verified on create. `ConditionSpec.validate_encounter_exists` rejects unknown encounter UUIDs; `perform_extra_deserialization` (create only) loads the encounter and derives `patient` from it. Clients never set `patient` or `encounter` directly. +- `verification_status` is mandatory on both `ConditionSpec` and `ConditionUpdateSpec`; `category` is mandatory only on create (`ConditionSpec`). +- `code` must belong to the bound value set (SNOMED CT clinical findings) on every write spec; `body_site`, when sent, must belong to the body-site value set. +- `onset_datetime` cannot be in the future and is forced timezone-aware; `abatement_datetime` carries no such constraint. +- `ConditionReadSpec` exposes `criticality`, a string in the read schema with no backing column on the `Condition` model. The standard serializer never populates it, so it comes back unset. +- Read serialization (`perform_extra_serialization`) maps `id = external_id`, replaces `encounter` with its `external_id`, and expands `created_by`/`updated_by` via `serialize_audit_users` (cached `UserSpec`). +- `body_site` and `recorded_date` exist on the model. `body_site` is read and written by the specs as a bound `Coding`; `recorded_date` is storage-only and outside the standard `Condition` API surface. -| 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 +## Related models -- `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`. +`Condition` links to two clinical records: -### Server-side behaviour +```text +patient → FK Patient (CASCADE, server-derived from encounter) +encounter → FK Encounter (CASCADE, nullable; required on create) +``` -- 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. +Deleting a `Patient` or `Encounter` cascades to its `Condition` rows. The column allows a null `encounter`, but the standard create flow always supplies one and derives `patient` from it. ## 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`. +- `serialize(obj)` and `de_serialize(obj)` (from `EMRResource`) convert between the `Condition` model and the spec. Field mapping uses the model's non-FK column names; `__exclude__` (`patient`, `encounter`) and `id`/`external_id` are skipped during deserialization. +- `ConditionSpec.perform_extra_deserialization(is_update=False, obj)` — create path: resolves the encounter and sets `obj.patient = obj.encounter.patient`. +- `ChronicConditionUpdateSpec.perform_extra_deserialization` — resolves and assigns `encounter` when provided. +- `ConditionReadSpec.perform_extra_serialization` — sets `id`/`encounter` external ids and serializes audit users. +- `external_id`, audit fields, `meta`/`history`, and soft-delete (`deleted`) are platform-maintained via [`EMRBaseModel`](../foundation/base-model.mdx). ## 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. +- Send `code` as a structured `Coding` (`{system, code, display}`) drawn from the SNOMED CT clinical-finding value set, not as free text. Always include `verification_status`; add `category` and `encounter` when creating. Send `body_site` as a `Coding` from the body-site value set when the anatomical location matters. +- `onset` and `abatement` are structured choice-of-type objects (`*_datetime`, `*_age`, `*_string`, `note`), not arbitrary JSON. `onset_datetime` must be timezone-aware and not in the future. +- Don't send `patient`, `external_id`, audit fields, or `deleted` from the client — the server owns them. ## Related -- Concept: [Condition](../../concepts/clinical/condition.mdx) -- Flow: [Record a symptom](../../flows/clinical/condition/record-symptom.mdx) -- Flow: [Record a diagnosis](../../flows/clinical/condition/record-diagnosis.mdx) -- Flow: [Add a symptom or diagnosis from past records](../../flows/clinical/condition/add-condition-from-past-records.mdx) -- Flow: [Update a symptom or diagnosis](../../flows/clinical/condition/update-condition.mdx) -- Flow: [Mark a symptom or diagnosis as entered in error](../../flows/clinical/condition/condition-entered-in-error.mdx) -- Flow: [View a patient's symptoms and diagnoses](../../flows/clinical/condition/view-clinical-history.mdx) - Reference: [Patient](../clinical/patient) -- Reference: [Encounter](./encounter.mdx) -- Reference: [Questionnaire Response](./questionnaire-response.mdx) -- Reference: [Value Set](../definitions/valueset.mdx) -- Reference: [Permission](../access-governance/permission.mdx) · [Role](../access-governance/role.mdx) -- Base: [EMRBaseModel](../foundation/base-model.mdx) -- 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) +- Reference: [Encounter](../clinical/encounter.mdx) +- Reference: [Base model](../foundation/base-model.mdx) +- Source: [condition.py](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) diff --git a/versioned_docs/version-3.1/references/clinical/detected-issue.mdx b/versioned_docs/version-3.1/references/clinical/detected-issue.mdx new file mode 100644 index 00000000..97ce975a --- /dev/null +++ b/versioned_docs/version-3.1/references/clinical/detected-issue.mdx @@ -0,0 +1,193 @@ +--- +sidebar_position: 6 +description: "Technical reference for the Detected Issue module in Care EMR: models, specs, enums, permissions and validation." +--- + +# Detected Issue + +A `DetectedIssue` records a clinical risk found during an encounter — a drug interaction, a dose problem, a duplicate therapy, or a care gap. It maps to the FHIR `DetectedIssue` resource. Each issue points at the clinical records that caused it, and carries the notes that describe how staff mitigated it. + +**Source:** +- Model: [`care/emr/models/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/detected_issue.py) +- Resource spec: [`care/emr/resources/detected_issue/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/spec.py) +- Constants: [`care/emr/resources/detected_issue/constants.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/constants.py) +- Viewsets: [`care/emr/api/viewsets/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/detected_issue.py) +- Permissions: [`care/security/permissions/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/detected_issue.py) + +A detected issue lives across two layers. The Django models are storage: `code` and `metadata` are opaque `JSONField`s, and `status`, `category`, and `severity` are plain `CharField`s. The Pydantic resource specs are the API layer. They supply the enums, the read and write schemas, and the validation. + +## Models + +| Model | Purpose | +| --- | --- | +| `DetectedIssue` | A clinical risk detected for a patient during an encounter | +| `DetectedIssueMitigation` | A note that records the action taken against an issue | +| `DetectedIssueResource` | A link from an issue to the clinical record that caused it | + +All three extend [`EMRBaseModel`](../foundation/base-model.mdx), the shared Care EMR base that gives `external_id`, `created_date`/`modified_date`, `created_by`/`updated_by`, soft-delete through `deleted`, and `history`/`meta` JSON. + +## `DetectedIssue` fields + +| Field | Type | Notes | +| --- | --- | --- | +| `status` | `CharField(25)` | Lifecycle state. Spec binds it to [`DetectedIssueStatusOptions`](#detectedissuestatusoptions-values); required on create | +| `category` | `CharField(25)` | Kind of risk. Spec binds it to [`DetectedIssueCategoryOptions`](#detectedissuecategoryoptions-values); required on create | +| `severity` | `CharField(25)` | How serious the risk is. Spec binds it to [`DetectedIssueSeverityOptions`](#detectedissueseverityoptions-values); required on create | +| `code` | `JSONField`, nullable | Coded detail of the issue. No current spec reads or writes it — storage only | +| `encounter` | `FK → Encounter`, `on_delete=PROTECT` | The encounter the issue belongs to. Required on create as a UUID; the server resolves it | +| `patient` | `FK → Patient`, `on_delete=PROTECT`, not null | Subject of the issue. Taken from the URL, never from the body (`__exclude__`) | + +## Enums + +Every enum is a `str, Enum` in `care/emr/resources/detected_issue/constants.py`. The value stored and serialized is the string in the table. + +### `DetectedIssueStatusOptions` values + +| Value | Meaning | +| --- | --- | +| `draft` | Issue is not yet published | +| `active` | Issue is open | +| `inactive` | Issue no longer applies | +| `not_done` | Issue was not acted on | +| `entered_in_error` | Issue was recorded by mistake | + +### `DetectedIssueSeverityOptions` values + +| Value | +| --- | +| `high` | +| `moderate` | +| `low` | + +### `DetectedIssueMitigationStatusOptions` values + +| Value | Meaning | +| --- | --- | +| `active` | Mitigation applies. Model default | +| `entered_in_error` | Mitigation was recorded by mistake | + +### `DetectedIssueCategoryOptions` values + +The category codes come from the FHIR `DetectedIssue` category value set (`http://hl7.org/fhir/ValueSet/detectedissue-category`), with codes from `http://terminology.hl7.org/CodeSystem/v3-ActCode`. The abstract grouping codes of `v3-ActCode` (the `notSelectable` codes with a `_` prefix) are not included. + +| Group | Values | +| --- | --- | +| Product and interaction alerts | `FOOD`, `TPROD`, `DRG`, `NHP`, `NONRX`, `OBSA` | +| Age alerts | `AGE`, `ADALRT`, `DOSEHINDA`, `DOSELINDA`, `GEALRT`, `PEALRT` | +| Condition alerts | `COND`, `HGHT`, `LACT`, `PREG`, `WGHT` | +| Reaction and allergy alerts | `CREACT`, `GEN`, `GEND`, `LAB`, `REACT`, `ALGY`, `INT`, `RREACT`, `RALG`, `RAR`, `RINT` | +| Compliance alerts | `PREVINEF`, `COMPLY`, `DUPTHPY`, `DUPTHPCLS`, `DUPTHPGEN`, `ABUSE`, `FRAUD`, `PLYDOC`, `PLYPHRM` | +| Dose alerts | `DACT`, `DOSE`, `DOSECOND`, `DOSEDUR`, `DOSEDURH`, `DOSEDURHIND`, `DOSEDURL`, `DOSEDURLIND`, `DOSEH`, `DOSEHIND`, `DOSEHINDSA`, `DOSEHINDW`, `DOSEIVL`, `DOSEIVLIND`, `DOSEL`, `DOSELIND`, `DOSELINDSA`, `DOSELINDW`, `MDOSE` | +| Timing alerts | `TIME`, `ALRTENDLATE`, `ALRTSTRTLATE`, `ENDLATE`, `STRTLATE`, `TIMING`, `INTERVAL`, `MINFREQ`, `HELD`, `TOOLATE`, `TOOSOON` | +| Fulfilment alerts | `ALLDONE`, `FULFIL`, `NOTACTN`, `NOTEQUIV`, `NOTEQUIVGEN`, `NOTEQUIVTHER` | +| Other | `HISTORIC`, `PATPREF`, `PATPREFALT`, `CAREGAP`, `CODINGGAP` | + +### `DetectedIssueResourceType` values + +The record types an issue can point at. Each value maps to a handler in [`care/emr/utils/resource_reference.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/utils/resource_reference.py), which does the read authorization and the rendering. + +| Value | +| --- | +| `diagnostic_report` | +| `observation` | +| `condition` | +| `allergy_intolerance` | +| `service_request` | +| `specimen` | +| `questionnaire_response` | +| `file_upload` | +| `immunization` | +| `medication_request` | + +## Related models + +### `DetectedIssueMitigation` + +Records what staff did about an issue. A mitigation is append-only: the note cannot change after creation, and the only update allowed sets the status to `entered_in_error`. + +| Field | Type | Notes | +| --- | --- | --- | +| `detected_issue` | `FK → DetectedIssue` (CASCADE) | `related_name="mitigation"`. Set from the URL | +| `note` | `TextField` | Required. Stripped of outer whitespace and must not be empty | +| `status` | `CharField(25)`, default `"active"` | One of [`DetectedIssueMitigationStatusOptions`](#detectedissuemitigationstatusoptions-values) | +| `entered_in_error_by` | `FK → users.User` (PROTECT), nullable | Set by the server when the status changes to `entered_in_error` | +| `entered_in_error_at` | `DateTimeField`, nullable | Set by the server at the same time | + +### `DetectedIssueResource` + +Links an issue to the clinical record that caused it. + +| Field | Type | Notes | +| --- | --- | --- | +| `detected_issue` | `FK → DetectedIssue` (CASCADE) | `related_name="resources"`. Set from the URL | +| `resource_type` | `CharField(100)` | One of [`DetectedIssueResourceType`](#detectedissueresourcetype-values) | +| `resource_id` | `UUIDField` | The `external_id` of the linked record | +| `metadata` | `JSONField`, default `{}` | Free-form client metadata about the link | + +A partial `UniqueConstraint` named `unique_detected_issue_resource` covers `resource_type`, `resource_id`, and `detected_issue` where `deleted=False`. A duplicate link returns a validation error ("Resource is already attached to this detected issue"). The resource columns lead the index, so the same index also serves the reverse lookup that finds issues for a set of records. + +### Relationships + +```text +DetectedIssue.patient → FK Patient (PROTECT, from the URL) +DetectedIssue.encounter → FK Encounter (PROTECT, required on create) +DetectedIssueMitigation.detected_issue → FK DetectedIssue (CASCADE, related_name="mitigation") +DetectedIssueResource.detected_issue → FK DetectedIssue (CASCADE, related_name="resources") +``` + +## Resource specs (API schema) + +Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py)) unless the table says otherwise. `DetectedIssueBaseSpec` sets `__model__ = DetectedIssue` and `__exclude__ = ["patient", "encounter", "resources"]`, so none of the three is read from the generic field loop. + +| Spec class | Role | Exposes / behaviour | +| --- | --- | --- | +| `DetectedIssueBaseSpec` | shared base | `id`, `status`, `category`, `severity` | +| `DetectedIssueCreateSpec` | write · create | Base + `encounter` (UUID4, required) and `resources` (`list[DetectedIssueResourceCreateSpec]`, default `[]`). Resolves the encounter and holds the resource list for the viewset | +| `DetectedIssueUpdateSpec` | write · update | `status`, `category`, `severity`, each `MISSING` by default. A field left out keeps its stored value. `encounter`, `patient`, and `resources` cannot change | +| `DetectedIssueListSpec` | read · list | Base + `patient` (UUID4), `encounter` (UUID4), `created_date`, `modified_date`, `created_by?`, `updated_by?` | +| `DetectedIssueRetrieveSpec` | read · detail | List spec + `resources` (`DetectedIssueResourceReadSpec[]`) and `mitigation` (`DetectedIssueMitigationReadSpec[]`) | +| `DetectedIssueResourceCreateSpec` | write · create | `resource_type`, `resource_id` (UUID4), `metadata` (default `{}`) | +| `DetectedIssueResourceReadSpec` | read | Create spec + `id`, `detected_issue` (UUID4), `created_date`, `modified_date`, `created_by?`, `updated_by?` | +| `DetectedIssueMitigationCreateSpec` | write · create | `note` only (`extra="forbid"`, whitespace stripped, `min_length=1`) | +| `DetectedIssueMitigationUpdateSpec` | write · update | Plain `BaseModel`, `extra="forbid"`. `status` is a `Literal["entered_in_error"]` — the only allowed update | +| `DetectedIssueMitigationReadSpec` | read | `id`, `detected_issue`, `note`, `status`, `entered_in_error_by?`, `entered_in_error_at?`, audit fields | +| `DetectedIssueResolvedResourceSpec` | read (action) | `resource_type` and the rendered `resource` dict, returned by the `resolve` action | +| `DetectedIssueResourceLookupRequest` | write (action body) | `encounter` (UUID4), `resource_type`, `resource_ids` (1–100 UUID4s). `extra="forbid"` | +| `DetectedIssueResourceLookupResponse` | read (action) | `results`: a list of `DetectedIssueRetrieveSpec` | + +### Validation & server-maintained behaviour + +- `patient` comes from the URL. On create the viewset checks that the supplied `encounter` belongs to that patient, else "Patient does not match the encounter patient". +- `resources` sent inside the create body are saved in the same transaction as the issue, through the same validation as the standalone resource endpoint. +- A linked record must belong to the issue's patient, and the caller must be able to read it. For a `file_upload`, the file must be uploaded and not archived, and its owning record (`patient`, `encounter`, `diagnostic_report`, `service_request`, `referral`, or `consent`) must resolve to the same patient. +- Updating a mitigation takes a row lock and only writes when the status really changes. It then stamps `entered_in_error_by`, `entered_in_error_at`, and `updated_by`. +- The list endpoint requires an `encounter` query parameter — detected issues are always listed per encounter. `status`, `category`, and `severity` are the supported filters, and `created_date` / `modified_date` are the ordering fields. + +## Permissions + +Detected issues are authorized at the encounter level. Both checks run through the encounter's facility organizations (and the organizations of its current location). + +| Permission | Allows | Default roles | +| --- | --- | --- | +| `can_read_detected_issue` | Read issues, their resources, and their mitigations | Facility Admin, Administrator, Admin, Staff, Doctor, Nurse, Volunteer, Pharmacist | +| `can_write_detected_issue` | Create and update issues, with their resources and mitigations | Facility Admin, Admin, Doctor, Nurse | + +Write access is also refused when the encounter is already in a completed state. + +## API integration notes + +- Endpoints are nested under the patient: `/patient/{patient_external_id}/detected_issue/`, with `resources/` and `mitigations/` nested under an issue. +- `POST .../detected_issue/by_resources/` returns the issues of one encounter that reference a given set of records. Send `encounter`, `resource_type`, and 1–100 `resource_ids`. +- `GET .../resources/{external_id}/resolve/` returns the linked record itself, rendered with that resource type's read spec, after a fresh read-permission check. +- Create and update return the full `DetectedIssueRetrieveSpec`, so the resources and mitigations come back in the same response. +- Do not send `patient`, `external_id`, audit fields, or `deleted` — the server owns them. + +## Related + +- Reference: [Patient](../clinical/patient) +- Reference: [Encounter](../clinical/encounter.mdx) +- Reference: [Condition](../clinical/condition.mdx) +- Reference: [Allergy intolerance](../clinical/allergy-intolerance.mdx) +- Reference: [Medication request](../medications/medication-request.mdx) +- Reference: [Base model](../foundation/base-model.mdx) +- Source: [detected_issue.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/detected_issue.py) · [spec.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/spec.py) · [constants.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/constants.py) diff --git a/versioned_docs/version-3.1/references/clinical/encounter.mdx b/versioned_docs/version-3.1/references/clinical/encounter.mdx index fc3f7ada..9c8f664e 100644 --- a/versioned_docs/version-3.1/references/clinical/encounter.mdx +++ b/versioned_docs/version-3.1/references/clinical/encounter.mdx @@ -1,128 +1,146 @@ --- sidebar_position: 2 -description: "Technical reference for the Encounter module in Care EMR. For the product view, see the Encounter concept." +description: "An Encounter records a single interaction between a patient and a facility — a visit, admission, or consultation — and maps to the FHIR Encounter resource." --- # Encounter -Technical reference for the `Encounter` module in Care EMR. For the product view, see the [Encounter concept](../../concepts/clinical/encounter.mdx). +An `Encounter` records a single interaction between a patient and a facility — a visit, admission, or consultation — and maps to the FHIR `Encounter` resource. You create one when a patient presents, drive it through its status lifecycle, and read it back to render the clinical timeline. -An `Encounter` belongs to one patient and one facility. It carries a status, an encounter type, a priority, a period and hospitalization details. It links to departments, a current location, tags and a care team. +The Django model is only the storage layer: several fields are opaque `JSONField`s whose real shape lives in the Pydantic resource specs, so the model alone won't tell you what a write must look like. The spec tables below carry that detail. **Source:** - - Model: [`care/emr/models/encounter.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/encounter.py) -- Specs: [`care/emr/resources/encounter/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/spec.py) · [`care_team.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/care_team.py) · [`constants.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/constants.py) · [`valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/valueset.py) · [`enum_display_names.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/enum_display_names.py) -- Viewset: [`care/emr/api/viewsets/encounter.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/encounter.py) -- Authorization: [`care/security/authorization/encounter.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/encounter.py) · permissions: [`care/security/permissions/encounter.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/encounter.py) - -The Django model is only the storage layer. Several fields are `JSONField`s whose shape the Pydantic specs set, and the specs decide which fields the API reads and writes. +- Specs: [`care/emr/resources/encounter/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/spec.py) · [`constants.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/constants.py) · [`valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/valueset.py) · [`enum_display_names.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/encounter/enum_display_names.py) ## Models | Model | Purpose | | --- | --- | -| `Encounter` | The encounter of one patient at one facility | -| `EncounterOrganization` | Links an encounter to a department (`FacilityOrganization`). The links drive the encounter's department set | +| `Encounter` | A single interaction between a patient and a facility (visit, admission, consultation) | +| `EncounterOrganization` | Links an `Encounter` to a `FacilityOrganization` for access control | -Both extend [`EMRBaseModel`](../foundation/base-model.mdx). It supplies `external_id`, `created_date`, `modified_date`, the soft-delete flag `deleted`, `created_by`, `updated_by`, `history` and `meta`. +Both extend [`EMRBaseModel`](../foundation/base-model.mdx), the shared Care EMR base that provides `external_id`, audit fields, and soft-delete semantics. ## `Encounter` fields -In the tables below, the model type is the Django column, and the API column is what the specs read and write. +### Classification & status -### Status, type and priority +| Field | Type | Notes | +| --- | --- | --- | +| `status` | `CharField(100)` | Nullable in DB; **required** in API. One of `StatusChoices` (see below) | +| `status_history` | `JSONField` | Default `{}`. Server-maintained. Shape: `{ "history": [{ "status": str, "moved_at": str (ISO datetime) }] }` | +| `encounter_class` | `CharField(100)` | Nullable in DB; **required** in API. One of `ClassChoices` (see below) | +| `encounter_class_history` | `JSONField` | Default `{}`. Server-maintained. Shape: `{ "history": [{ "status": str, "moved_at": str (ISO datetime) }] }` | +| `priority` | `CharField(100)` | Nullable in DB; **required** in API. One of `EncounterPriorityChoices` (see below) | +| `external_identifier` | `CharField(100)` | Nullable. Identifier from an external/source system | -| Field | Model type | API | Notes | -| --- | --- | --- | --- | -| `status` | `CharField(100)`, nullable | `StatusChoices`, required on create and update | See [Status values](#status-values-statuschoices) | -| `status_history` | `JSONField`, default `{}` | Read only (list and retrieve) | Server-maintained. See [`status_history`](#status_history) | -| `encounter_class` | `CharField(100)`, nullable | `ClassChoices`, required on create. Not in the update spec | The encounter type. Fixed after creation | -| `priority` | `CharField(100)`, nullable | `EncounterPriorityChoices`, required on create and update | | -| `external_identifier` | `CharField(100)`, nullable | `str \| None` | The encounter form labels it **Hospital Identifier** | +### Subject & facility -### Subject, facility and location +| Field | Type | Notes | +| --- | --- | --- | +| `patient` | `FK → Patient` | `CASCADE`. The patient this encounter is for. Set on create only | +| `facility` | `FK → Facility` | `PROTECT`. The facility where the encounter takes place. Set on create only | +| `appointment` | `FK → TokenBooking` | `SET_NULL`, nullable. Originating [scheduling booking](../scheduling/booking.mdx), if any | +| `current_location` | `FK → FacilityLocation` | `SET_NULL`, nullable. Cached current [location](../facility/location.mdx) for easier querying | -| Field | Model type | API | Notes | -| --- | --- | --- | --- | -| `patient` | `FK → Patient`, `CASCADE` | `UUID4`, create only | Looked up by `external_id`. Excluded from update | -| `facility` | `FK → Facility`, `PROTECT` | `UUID4`, create only | Looked up by `external_id`. Excluded from update | -| `appointment` | `FK → TokenBooking`, `SET_NULL`, nullable | `UUID4 \| None`, create only | Must belong to the same patient, to a slot whose resource is in the same facility, and have no encounter yet. See [Booking](../scheduling/booking.mdx) | -| `current_location` | `FK → FacilityLocation`, `SET_NULL`, nullable | Read only | A cached field. The location module sets it from the active bed stay. Closing the encounter does not clear it | +### Timing & disposition -### Period and hospitalization +| Field | Type | Notes | +| --- | --- | --- | +| `period` | `JSONField` | Default `{}`. `PeriodSpec { start: datetime (tz-aware, optional), end: datetime (tz-aware, optional) }`. If both set, `start ≤ end` | +| `hospitalization` | `JSONField` | Default `{}`. `HospitalizationSpec` (see shape below). Nullable | +| `discharge_summary_advice` | `TextField` | Nullable. Free-text discharge advice. Explicitly cleared to `None` on update when omitted | -| Field | Model type | API | Notes | -| --- | --- | --- | --- | -| `period` | `JSONField`, default `{}` | `PeriodSpec`, default `{}` | See [`PeriodSpec`](#periodspec-period) | -| `hospitalization` | `JSONField`, default `{}` | `HospitalizationSpec \| None`, default `{}` | All four keys are optional | -| `discharge_summary_advice` | `TextField`, nullable | `str \| None` | An update that leaves it out, or sends `null`, clears it | +### Care team -### Departments, care team, tags and extensions +| Field | Type | Notes | +| --- | --- | --- | +| `care_team` | `JSONField` | Default `{}`. Stored as a list of `{ "user_id": int, "role": Coding }` entries. **Not** writable on create/update (excluded); managed via the dedicated care-team write spec | +| `care_team_users` | `ArrayField[int]` | Platform-maintained denormalized cache of user IDs derived from `care_team` via `sync_care_team_users_cache()` on every save | -| Field | Model type | API | Notes | -| --- | --- | --- | --- | -| `facility_organization_cache` | `ArrayField[int]`, default `[]` | Never returned | The department set: linked departments, their ancestors and the facility's Administration department. Rebuilt on every save | -| `care_team` | `JSONField`, default `{}` | Excluded from create and update. Read as a list of `member` and `role` | Written through `set_care_team_members`. See [Care team](./care-team.mdx) | -| `care_team_users` | `ArrayField[int]`, default `[]` | Never returned | Integer user ids taken from `care_team` on every save | -| `tags` | `ArrayField[int]`, default `[]` | Read as rendered tag configs | Set by `tags` in the create body, `set_tags` and `remove_tags` | -| `tags_data` | `JSONField`, default `{}` | Never returned | Expiry per tag. See [`tags_data`](#tags_data) | -| `extensions` | `JSONField`, default `{}` | `dict` on create and update; returned on retrieve | Checked by `ExtensionValidator` against the extensions registered for `encounter` | +### Organization cache, tags & extensions -## Enum values +| Field | Type | Notes | +| --- | --- | --- | +| `facility_organization_cache` | `ArrayField[int]` | Platform-maintained cache of facility-[organization](../access-governance/organization.mdx) IDs (incl. parent chains). Rebuilt by `sync_organization_cache()` | +| `tags` | `ArrayField[int]` | Tag IDs applied to the encounter. Serialized via `SingleFacilityTagManager().render_tags()` | +| `extensions` | `JSONField` | Default `{}`. Open extension bag for deployment-specific metadata. Validated by `ExtensionValidator` against `ExtensionResource.encounter` | -The screen labels come from the Care frontend locale file, under the keys `encounter_status__`, `encounter_class__`, `encounter_priority__`, `encounter_admit_sources__`, `encounter_discharge_disposition__` and `encounter_diet_preference__` followed by the value. +## Nested JSON shapes -### Status values (`StatusChoices`) +### `PeriodSpec` (`period`) + +Defined in [`resources/base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py). -| Value | Label | Notes | +| Field | Type | Notes | | --- | --- | --- | -| `planned` | Planned | | -| `in_progress` | In Progress | `restart` sets this status | -| `on_hold` | On Hold | | -| `discharged` | Discharged | Not closed. Counts toward the open-encounter limit | -| `completed` | Completed | Closed | -| `cancelled` | Cancelled | Closed | -| `discontinued` | Discontinued | Closed | -| `entered_in_error` | Entered in error | Closed. The only value in `ERROR_CHOICES` | -| `unknown` | Unknown | | - -`COMPLETED_CHOICES` lists the closed statuses: `completed`, `cancelled`, `entered_in_error` and `discontinued`. The code calls them completed; this page calls them closed. +| `start` | `datetime \| None` | Must be timezone-aware if provided | +| `end` | `datetime \| None` | Must be timezone-aware if provided | -### Class values (`ClassChoices`) +`validate_period` rejects naive datetimes, and when both `start` and `end` are set it requires `start` not to exceed `end`. + +### `HospitalizationSpec` (`hospitalization`) + +Defined in `spec.py`. All fields optional/nullable. + +| Field | Type | Values | +| --- | --- | --- | +| `re_admission` | `bool \| None` | — | +| `admit_source` | `AdmitSourcesChoices \| None` | see [Admit source values](#admit-source-values-admitsourceschoices) | +| `discharge_disposition` | `DischargeDispositionChoices \| None` | see [Discharge disposition values](#discharge-disposition-values-dischargedispositionchoices) | +| `diet_preference` | `DietPreferenceChoices \| None` | see [Diet preference values](#diet-preference-values-dietpreferencechoices) | -The class is the encounter type. The create form labels it **Type of Encounter**, and the facility encounter list filter labels it **Encounter Class**. +## Enum values + +### Status values (`StatusChoices`) -| Value | Label | +| Value | | | --- | --- | -| `imp` | Inpatient | -| `amb` | Ambulatory | -| `obsenc` | Observation | -| `emer` | Emergency | -| `vr` | Virtual | -| `hh` | Home Health | +| `planned` | | +| `in_progress` | | +| `on_hold` | | +| `discharged` | | +| `completed` | terminal (in `COMPLETED_CHOICES`) | +| `cancelled` | terminal (in `COMPLETED_CHOICES`) | +| `discontinued` | terminal (in `COMPLETED_CHOICES`) | +| `entered_in_error` | terminal (in `COMPLETED_CHOICES` and `ERROR_CHOICES`) | +| `unknown` | | + +`COMPLETED_CHOICES = [completed, cancelled, entered_in_error, discontinued]`; `ERROR_CHOICES = [entered_in_error]`. -### Priority values (`EncounterPriorityChoices`) +### Class values (`ClassChoices`) -| Value | Label | +| Value | Meaning | | --- | --- | -| `ASAP` | ASAP | -| `callback_results` | Callback results | -| `callback_for_scheduling` | Callback for scheduling | -| `elective` | Elective | -| `emergency` | Emergency | -| `preop` | Pre-op | -| `as_needed` | As needed | -| `routine` | Routine | -| `rush_reporting` | Rush reporting | -| `stat` | Stat | -| `timing_critical` | Timing critical | -| `use_as_directed` | Use as directed | -| `urgent` | Urgent | +| `imp` | inpatient | +| `amb` | ambulatory | +| `obsenc` | observation | +| `emer` | emergency | +| `vr` | virtual | +| `hh` | home health | + +### Priority values (`EncounterPriorityChoices`) + +| Value | +| --- | +| `ASAP` | +| `callback_results` | +| `callback_for_scheduling` | +| `elective` | +| `emergency` | +| `preop` | +| `as_needed` | +| `routine` | +| `rush_reporting` | +| `stat` | +| `timing_critical` | +| `use_as_directed` | +| `urgent` | ### Admit source values (`AdmitSourcesChoices`) -| Value | Label | +| Value | Display (`get_admit_source_display`) | | --- | --- | | `hosp_trans` | Transferred from other hospital | | `emd` | From accident/emergency department | @@ -137,286 +155,114 @@ The class is the encounter type. The create form labels it **Type of Encounter** ### Discharge disposition values (`DischargeDispositionChoices`) -| Value | Label | +| Value | Display (`get_discharge_disposition_display`) | | --- | --- | | `home` | Home | -| `alt_home` | Alternate home | -| `other_hcf` | Other health care facility | -| `hosp` | Hospice | -| `long` | Long term care | -| `aadvice` | Left against advice | +| `alt_home` | Alternate Home | +| `other_hcf` | Other Health Care Facility | +| `hosp` | Hospital | +| `long` | Long-term Care Facility | +| `aadvice` | Against Medical Advice | | `exp` | Expired | -| `psy` | Psychiatric hospital | -| `rehab` | Rehabilitation | -| `snf` | Skilled nursing facility | +| `psy` | Psychiatric Hospital | +| `rehab` | Rehabilitation Facility | +| `snf` | Skilled Nursing Facility | | `oth` | Other | -`enum_display_names.py` defines display helpers for admit source and discharge disposition. Nothing in Care calls them, and some of their names differ from the labels above. - ### Diet preference values (`DietPreferenceChoices`) -| Value | Label | -| --- | --- | -| `vegetarian` | Vegetarian | -| `dairy_free` | Dairy free | -| `nut_free` | Nut free | -| `gluten_free` | Gluten free | -| `vegan` | Vegan | -| `halal` | Halal | -| `kosher` | Kosher | -| `none` | None | - -## Nested JSON shapes - -### `PeriodSpec` (`period`) - -Defined in [`resources/base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py). - -| Key | Type | Notes | -| --- | --- | --- | -| `start` | `datetime \| None` | Must carry a time zone ("Start Date must be timezone aware") | -| `end` | `datetime \| None` | Must carry a time zone ("End Date must be timezone aware") | - -When both are set, `start` cannot be after `end` ("Start Date cannot be greater than End Date"). The backend sets no rule about future dates. +| Value | +| --- | +| `vegetarian` | +| `dairy_free` | +| `nut_free` | +| `gluten_free` | +| `vegan` | +| `halal` | +| `kosher` | +| `none` | -### `HospitalizationSpec` (`hospitalization`) - -Defined in `spec.py`. Every key is optional and defaults to `null`. - -| Key | Type | Values | -| --- | --- | --- | -| `re_admission` | `bool \| None` | | -| `admit_source` | `AdmitSourcesChoices \| None` | See [Admit source values](#admit-source-values-admitsourceschoices) | -| `discharge_disposition` | `DischargeDispositionChoices \| None` | See [Discharge disposition values](#discharge-disposition-values-dischargedispositionchoices) | -| `diet_preference` | `DietPreferenceChoices \| None` | See [Diet preference values](#diet-preference-values-dietpreferencechoices) | - -### `status_history` +## Resource specs (API schema) -The field holds one key, `history`, a list of entries in the order the statuses were set. +All specs build on `EMRResource`, which provides `serialize` / `de_serialize` plus the `perform_extra_serialization` / `perform_extra_deserialization` hooks. `EncounterSpecBase` sets `__exclude__ = [patient, organizations, facility, appointment, current_location, care_team]`; those fields move through hooks or dedicated endpoints rather than direct assignment, which is why the create and read schemas diverge from the raw model. -| Entry key | Type | Notes | +| Spec | Role | Notes | | --- | --- | --- | -| `status` | `StatusChoices` value | The status that was set | -| `moved_at` | `str` | Server time when the status was set | - -### `tags_data` - -`tags_data` has one entry for each tag that was set with an expiry. The key is the tag config id as a string, and the entry holds `expiry`. Removing the tag deletes its entry. +| `EncounterSpecBase` | shared | Fields: `id`, `status`, `encounter_class`, `period` (`PeriodSpec`, default `{}`), `hospitalization` (`HospitalizationSpec \| None`, default `{}`), `priority`, `external_identifier`, `discharge_summary_advice`. `__model__ = Encounter` | +| `EncounterCreateSpec` | write · create | Extends base + `ExtensionValidator`. Adds `patient: UUID4`, `facility: UUID4`, `organizations: list[UUID4] = []`, `appointment: UUID4 \| None`. Resolves FKs by `external_id`; validates appointment belongs to the patient and facility | +| `EncounterUpdateSpec` | write · update | Extends base + `ExtensionValidator`. Does not accept `patient`/`facility`/`organizations`/`appointment` — only mutable fields. Appends to status/class history on change | +| `EncounterListSpec` | read · list | Extends base + `ExtensionListRenderer`. Adds serialized `patient` ([`PatientListSpec`](../clinical/patient)), `facility` (`FacilityBareMinimumSpec`), `status_history`, `encounter_class_history`, `created_date`, `modified_date`, `tags`, `current_location` (`FacilityLocationMinimalListSpec \| None`), `care_team` (`[{ member, role }]`), `extensions` (rendered through `deserialize_extensions_list`) | +| `EncounterRetrieveSpec` | read · detail | Extends list + `ExtensionRetrieveRenderer` + `EncounterPermissionsMixin`. Adds `appointment` (`TokenBookingReadSpec`), `created_by`/`updated_by` ([`UserSpec`](../access-governance/user.mdx)), `organizations` (`FacilityOrganizationReadSpec[]`), `location_history` (`FacilityLocationEncounter[]`, newest first); patient via `PatientRetrieveSpec`; `extensions` re-rendered through `deserialize_extensions_retrieve` | +| `HospitalizationSpec` | nested | Plain `BaseModel`; see shape above | +| `EncounterCareTeamMemberSpec` | nested (write) | `{ user_id: UUID4, role: Coding }`, `role` bound to the `system-practitioner-role-code` value set | +| `EncounterCareTeamMemberWriteSpec` | write · care team | `{ members: list[EncounterCareTeamMemberSpec] }`. Dedicated payload for replacing the care team | -### `care_team` +### Server-maintained behaviour -See the [Care team](./care-team.mdx) reference for the stored and returned shapes. +- **Status history**: on create, `status_history` starts as `{ "history": [{ status, moved_at }] }` carrying the initial status; on update, a new entry is appended only when `status` changes. `encounter_class_history` / `encounter_class` follow the same rule. +- **FK resolution (create)**: `patient`, `facility`, and `appointment` resolve from `external_id` (404 if not found). The appointment must belong to the same patient and to a slot whose resource sits in the same facility. +- **Organizations (create)**: `organizations`, deduplicated to a list of UUIDs, is stashed on `obj._organizations`, and the resulting `EncounterOrganization` rows drive `facility_organization_cache`. +- **Discharge advice (update)**: omitting `discharge_summary_advice` on update clears it to `None` rather than leaving the prior value. +- **Care team**: `role` binds to the `PRACTITIONER_ROLE_VALUESET` (slug `system-practitioner-role-code`), a SNOMED CT value set of descendants of `223366009` (healthcare professional) and `224930009` (healthcare-related occupation). ## Related models ### `EncounterOrganization` +Associates an encounter with a facility-scoped [organization](../access-governance/organization.mdx) to drive organization-based access control on encounters. + ```text encounter → FK Encounter (CASCADE) organization → FK FacilityOrganization (CASCADE) ``` -Saving a link calls `encounter.sync_organization_cache()`, so adding a department updates the department set at once. - -`organizations_remove` deletes the link row without a save. The department set keeps the removed department, and its ancestors, until the encounter's next save. - -### Bed stays (location module) - -Bed stays are `FacilityLocationEncounter` records in the location module. The retrieve spec returns them as `location_history`, newest first. See [Location](../facility/location.mdx). - -## Resource specs (API schema) - -`EncounterSpecBase` and the create, update, list and retrieve specs build on `EMRResource`. The nested and action specs are plain Pydantic models. - -`EncounterSpecBase` excludes `patient`, `organizations`, `facility`, `appointment`, `current_location` and `care_team` from direct assignment. The create spec and the viewset set the first four, `set_care_team_members` sets the care team, and the location module sets `current_location`. - -| Spec | Role | Notes | -| --- | --- | --- | -| `EncounterSpecBase` | shared | `id`, `status` (required), `period`, `hospitalization`, `priority` (required), `external_identifier`, `discharge_summary_advice`. No `encounter_class` | -| `EncounterCreateSpec` | write · create | Base fields plus `patient`, `facility`, `organizations` (default `[]`), `appointment` (optional), `encounter_class` (required) and `extensions` | -| `EncounterUpdateSpec` | write · update | Base fields plus `extensions`. No `patient`, `facility`, `organizations`, `appointment` or `encounter_class` | -| `EncounterListSpec` | read · list | Base fields plus `patient` (`PatientListSpec`), `facility` (`FacilityBareMinimumSpec`), `status_history`, `encounter_class`, `created_date`, `modified_date`, `tags`, `current_location` (`FacilityLocationMinimalListSpec` or `null`) and `care_team` | -| `EncounterRetrieveSpec` | read · detail | List fields, with `patient` as `PatientRetrieveSpec`, plus `appointment` (`TokenBookingReadSpec`), `created_by`, `updated_by`, `organizations` (`FacilityOrganizationReadSpec` list), `location_history`, `extensions` and `permissions` | -| `HospitalizationSpec` | nested | See [`HospitalizationSpec`](#hospitalizationspec-hospitalization) | -| `EncounterCareTeamMemberSpec` | nested · write | `user_id` (`UUID4`) and `role` (a coding bound to `system-practitioner-role-code`) | -| `EncounterCareTeamMemberWriteSpec` | write · care team | `members`: a list of `EncounterCareTeamMemberSpec` | -| `EncounterOrganizationManageSpec` | write · departments | `organization` (`UUID4`). Body of `organizations_add` and `organizations_remove` | -| `EncounterFacilityIdentifierWriteSpec` | write · identifier | `identifier` (`UUID4`), `value` (`str \| None`), `set_default` (default `false`) | -| `TagRequest` | write · tags | `tags`: a list of `TagSetRequest`, each with `tag` (`UUID4`) and an optional `expiry_offset` | - -`permissions` on retrieve is a list of permission slugs. It holds the ENCOUNTER and PATIENT context permissions of the roles the caller holds on the encounter. - -### `PRACTITIONER_ROLE_VALUESET` - -Each care team member's `role` is bound to the active system value set "Practitioner Role", slug `system-practitioner-role-code`. - -It includes the SNOMED CT concepts under `223366009` and under `224930009` (two `is-a` filters). See [Care team](./care-team.mdx) for the care team shape. - -| Concept | Display on Care's default terminology server (SNOMED CT International Edition 20241101) | -| --- | --- | -| `223366009` | Healthcare professional | -| `224930009` | Services | - -### Server-maintained behaviour - -- Status history: create starts `status_history` with the initial status and the time. An update adds an entry only when the status changes. -- `restart` sets the status to `in_progress` without the update spec, so it adds no `status_history` entry. -- Encounter type: `encounter_class` is set on create only. A value sent on update is not applied, and Care keeps no history of it. -- The `encounter_class_history` field was removed in Care commit `3c9f3c297`, together with the class in the update spec. -- Create resolves `patient` and `facility` by `external_id`. Each department must belong to the encounter's facility. The viewset links the departments after the encounter is saved. -- With no departments, the department set holds only the facility's Administration department. -- If the appointment already has an encounter, create fails with "Encounter already has an associated booking". Otherwise Care links the appointment to the new encounter. -- Create applies `tags` from the request body in the same save. -- Under a per-facility lock, create evaluates the patient identifier defaults of the facility and rebuilds the patient's facility identifiers. -- If the lock is busy, create fails with "Encounter creation failed, try again after a while". -- Every update first releases linked devices and closes open bed stays. Both steps act only when the new status is closed. Then the update saves. -- When the status becomes closed, Care frees each bed whose current encounter this is. It marks such a bed unoccupied if it was occupied and has no encounter now. -- It also completes the encounter's open bed stays with the end time now, and ends its device links. -- Closing does not change `current_location`. -- An update applies only the fields whose value differs from the spec default. For example, `external_identifier: null` leaves the stored value. `discharge_summary_advice` is the exception. +Saving an `EncounterOrganization` calls `encounter.sync_organization_cache()`, which rebuilds the encounter's `facility_organization_cache`. ## Methods & save behaviour -### `save()` side effects - -Every save runs `sync_care_team_users_cache()`, then the base `save()`, then `sync_organization_cache()`. The last step writes `facility_organization_cache` in a second save. - -`save()` itself has no transaction and no patient identifier step. The viewset's create does that work. - -### `sync_organization_cache()` - -Builds the department set from every linked department, the ancestors of each (`parent_cache`), and the facility's default internal department. Care creates that department as "Administration" with the facility. - ### `sync_care_team_users_cache()` -When `care_team` is a list, it sets `care_team_users` to the integer `user_id` of each entry, or `-1` when an entry has none. The flat list avoids JSON queries. +When `care_team` is a list, fills `care_team_users` with `int(entry["user_id"])` for each entry, falling back to `-1` when a `user_id` is missing. The flat integer array lets queries skip JSON traversal. -## API integration notes - -### Endpoints - -`{id}` in the paths below is the encounter's `external_id`. Responses return it as `id`. - -| Method | Path | Action | Body → response | -| --- | --- | --- | --- | -| `GET` | `/api/v1/encounter/` | List | Filters below → `EncounterListSpec` items, paginated, newest first | -| `POST` | `/api/v1/encounter/` | Create | `EncounterCreateSpec`, optional `tags` → `EncounterRetrieveSpec` | -| `GET` | `/api/v1/encounter/{id}/` | Retrieve | → `EncounterRetrieveSpec` | -| `PUT` | `/api/v1/encounter/{id}/` | Update | `EncounterUpdateSpec` → `EncounterRetrieveSpec` | -| `POST` | `/api/v1/encounter/{id}/restart/` | Restart a closed encounter | none → `204` | -| `GET` | `/api/v1/encounter/{id}/organizations/` | List the linked departments | → `results`, a list of `FacilityOrganizationReadSpec` | -| `POST` | `/api/v1/encounter/{id}/organizations_add/` | Link a department | `EncounterOrganizationManageSpec` → `FacilityOrganizationReadSpec` | -| `DELETE` | `/api/v1/encounter/{id}/organizations_remove/` | Unlink a department | `EncounterOrganizationManageSpec` → empty object | -| `POST` | `/api/v1/encounter/{id}/set_care_team_members/` | Replace the care team | `EncounterCareTeamMemberWriteSpec` → empty object (the schema declares `EncounterRetrieveSpec`). See [Care team](./care-team.mdx) | -| `POST` | `/api/v1/encounter/{id}/set_facility_identifier/` | Set a patient identifier for the facility | `EncounterFacilityIdentifierWriteSpec` → empty object | -| `POST` | `/api/v1/encounter/{id}/set_tags/` | Apply tags | `TagRequest` → `EncounterRetrieveSpec` | -| `POST` | `/api/v1/encounter/{id}/remove_tags/` | Remove tags | `TagRequest` → `EncounterRetrieveSpec` | - -There is no delete. The Care frontend never calls `set_facility_identifier`. - -`set_facility_identifier` needs an identifier configuration of the encounter's facility, and it refuses an auto-maintained identifier ("Cannot update auto maintained identifier"). - -Bed stays are written through `/api/v1/facility/{facility}/location/{location}/association/`, not through this viewset. See [Location](../facility/location.mdx). - -### Authorization - -A user's roles on an encounter are the roles they hold in the encounter's department set and in the department set of its current location. - -The encounter's department set is its linked departments, their ancestors and the facility's Administration department. - -A location's department set is its linked departments and their ancestors, its parent location's department set and the Administration department. - -| Endpoint | Handler | Requirement | -| --- | --- | --- | -| Create | `can_create_encounter_obj` | "Can Create encounter" in any department of the facility. Else 403 "You do not have permission to create encounter" | -| Create with `tags`, `set_tags`, `remove_tags` | per-tag check | For each tag, "Can Apply Tag Config to Resources" in the tag's managing department or its ancestors, in its managing organization, or else in a department of the facility. Else 403 "You do not have permission to apply tag" (or "remove tag") with the tag name | -| Retrieve, `organizations` | `can_view_patient_obj`, then `can_view_encounter_obj` | "Can list patients" among the user's roles on the patient, or "Can Read encounter" in the encounter's or current location's department set. No status condition. Else 403 "You do not have permission to view this patient" | -| List with `patient` | `can_view_patient_obj` | As above for the patient. Returns that patient's encounters in every facility. Else 403 "User cannot access patient" | -| List with `facility` | `get_filtered_encounters` | Returns only encounters whose department set, or current location's department set, includes a department of that facility where the user holds "Can list encounters" | -| List with neither | | 403 "Cannot access encounters" | -| Update, `organizations_add`, `organizations_remove`, `set_care_team_members`, `set_facility_identifier`, `set_tags`, `remove_tags` | `can_update_encounter_obj` | "Update Encounter non clinical" in the encounter's or current location's department set. Refused when the encounter is closed. Else 403 "You do not have permission to update encounter" | -| `restart` | `can_restart_encounter_obj` | "Update Encounter non clinical" in the same places. Allowed only when the encounter is closed. Else 403 "You do not have permission to update encounter" | - -For an encounter that is not closed, `can_restart_encounter_obj` already refuses with 403. The later check "Encounter is not in a completed state" does not come up. - -Roles on a patient come from three places. These are the departments of the patient's open encounters and of their current locations, the patient's organizations, and direct patient-user links. - -Default roles from the permission definitions: - -| Permission | Default roles | -| --- | --- | -| "Can Create encounter" | Doctor, Nurse, Facility Admin | -| "Can Read encounter" | Doctor, Nurse, Facility Admin | -| "Update Encounter non clinical" | Doctor, Nurse, Facility Admin | -| "Can list encounters" | Doctor, Nurse, Facility Admin. Its description reads "Clinical data is not associated with this permission" | -| "Can list patients" | Staff, Doctor, Nurse, Administrator, Facility Admin, Volunteer, Pharmacist | -| "Can Apply Tag Config to Resources" | Facility Admin, Staff, Doctor, Nurse, Pharmacist | - -The permission definitions also name an Admin role. The only role named Admin can be given in role organizations, not in a facility department, so the table leaves it out. +### `sync_organization_cache()` -The encounter permission file also defines "Update Encounter related clinical data", "Can Read encounter related clinical data" and "Can submit questionnaire about patient encounters". The endpoints on this page do not check them. +Recomputes `facility_organization_cache` as the union of: -Other parts of Care check them. Symptoms, diagnoses, prescriptions, allergy changes and encounter notes check "Update Encounter related clinical data" through `can_update_encounter_clinical_data`. +- every linked `EncounterOrganization` organization plus its `parent_cache` chain, and +- the facility's `default_internal_organization_id`. -Clinical reads check "Can Read encounter related clinical data" through `can_view_encounter_clinical_data`, and the Care frontend reads it from the retrieve `permissions`. +Persists the result with `super().save(update_fields=["facility_organization_cache"])`. -Questionnaire submission for an encounter checks "Can submit questionnaire about patient encounters" through `can_submit_encounter_questionnaire_obj`. +### `save()` side effects -Being on the care team gives no access to the encounter or the patient. Nothing in the authorization code reads the care team. +On every save: -### Filters and ordering +1. `sync_care_team_users_cache()` runs, refreshing `care_team_users`. +2. A record with no `pk` is flagged as newly `created`. +3. Inside a single `transaction.atomic()` block, the base `save()` runs. For newly created encounters, `evaluate_patient_facility_default_values(patient, facility)` then generates facility-scoped patient identifier defaults. +4. After the transaction, `sync_organization_cache()` runs, performing a second write (`update_fields=["facility_organization_cache"]`). -| Parameter | Meaning | -| --- | --- | -| `facility` | Facility `external_id`. Lists that facility's encounters, as the authorization table describes | -| `patient` | Patient `external_id`. Lists that patient's encounters in every facility | -| `patient_filter` | Patient `external_id`, as a plain filter | -| `status` | One or more statuses | -| `encounter_class` | Encounter type, case-insensitive exact match | -| `priority` | Priority, case-insensitive exact match | -| `external_identifier` | Part of the identifier, case-insensitive | -| `name` | Part of the patient's name | -| `phone_number` | Part of the patient's phone number | -| `location` | Current location `external_id` | -| `created_date_after`, `created_date_before` | Creation date range. The Care frontend sends these two | -| `live` | `true` keeps closed encounters only; `false` keeps encounters that are not closed | -| `organization` | Department `external_id`, matched in the department set. A parent department also matches encounters of its sub-departments | -| `care_team_user` | Username, matched in `care_team_users` | -| `tags` | Comma-separated tag config `external_id`s. With `tags_behavior` `any` (default) or `all`. Unknown tags give an empty list | -| `ordering` | `created_date` or `modified_date`. Without it, newest first | - -### Settings - -| Setting | Default | Effect | -| --- | --- | --- | -| `MAX_ACTIVE_ENCOUNTERS_PER_PATIENT_IN_FACILITY` | `5` | Create fails when the patient already has this many encounters at the facility that are not closed: "Patient already has maximum number of active encounters (N) in the facility". Discharged encounters count | -| `ENCOUNTER_RESTART_TIME_LIMIT_HOURS` | `0` | Restart fails when the encounter was last changed more than this many hours ago: "Encounter cannot be restarted after N hours". With `0`, every restart fails | +Expect two write passes per create or update through the ORM, plus identifier-default generation on creation. -### Notes +## API integration notes -- Reads use `EncounterListSpec` and `EncounterRetrieveSpec`. Writes use `EncounterCreateSpec` and `EncounterUpdateSpec`. -- `status`, `priority` and, on create, `encounter_class` are required and checked against their enums, although the columns are nullable. -- A field that is not in the spec is not applied. `status_history`, `care_team_users`, `facility_organization_cache` and `tags_data` are server-maintained. -- To correct a wrong encounter type, set the status to `entered_in_error` and create a new encounter. -- `period.start` and `period.end` must carry a time zone. -- After `organizations_remove`, users with roles in the removed department keep their access to the encounter until the encounter's next save. -- `current_location` is a cached field. The bed stay records, returned as `location_history`, hold the history of its bed stays. +- Reads use `EncounterListSpec` / `EncounterRetrieveSpec`; writes use `EncounterCreateSpec` / `EncounterUpdateSpec`. +- `status`, `encounter_class`, and `priority` are required on write and validated against their enums, even though the DB columns are nullable. +- Never set `status_history`, `encounter_class_history`, `care_team_users`, or `facility_organization_cache` from a client; the server appends history on create and update and derives the caches from `care_team` and `EncounterOrganization`. +- Create and update don't touch the care team. Replace it through the dedicated care-team endpoint with `EncounterCareTeamMemberWriteSpec`, where each member's `role` must resolve within the `system-practitioner-role-code` value set. +- `period` and `hospitalization` carry structured JSON matching the nested-spec shapes above; `period.start` and `period.end` must be timezone-aware. +- `current_location` is a cached convenience field. The authoritative record is `location_history`, from `FacilityLocationEncounter`. +- `extensions` holds custom key-value data without a schema migration, validated by `ExtensionValidator` on write. On read, each registered extension handler renders its own payload — list reads use the short form, detail reads the full form — so a key can hold less data in a list response than in a detail response. ## Related -- Concept: [Encounter](../../concepts/clinical/encounter.mdx) -- Reference: [Care team](./care-team.mdx) - Reference: [Patient](../clinical/patient) +- Reference: [Service request](../clinical/service-request.mdx) - Reference: [Booking](../scheduling/booking.mdx) - Reference: [Location](../facility/location.mdx) -- Reference: [Device](../facility/device.mdx) - Reference: [Organization](../access-governance/organization.mdx) - Reference: [Facility](../facility/facility.mdx) - Reference: [User](../access-governance/user.mdx) -- Reference: [Tagging](../platform/tag-config.mdx) -- Reference: [Value set](../definitions/valueset.mdx) -- Reference: [Permission](../access-governance/permission.mdx) -- Reference: [Base model](../foundation/base-model.mdx) +- Concept: [Patient](../../concepts/clinical/patient) - Source (model): [encounter.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/encounter.py) - Source (specs): [resources/encounter on GitHub](https://github.com/ohcnetwork/care/tree/develop/care/emr/resources/encounter) -- Source (viewset): [viewsets/encounter.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/encounter.py) diff --git a/versioned_docs/version-3.1/references/definitions/product-knowledge.mdx b/versioned_docs/version-3.1/references/definitions/product-knowledge.mdx index 23b112da..9d506c97 100644 --- a/versioned_docs/version-3.1/references/definitions/product-knowledge.mdx +++ b/versioned_docs/version-3.1/references/definitions/product-knowledge.mdx @@ -1,34 +1,26 @@ --- sidebar_position: 8 -description: "Technical reference for the ProductKnowledge module in Care EMR. For what Product Knowledge means to facility users, see the Product Knowledge concept." +description: "ProductKnowledge is the reusable definition of a product — its coding, base presentation unit, ingredients and nutrients, drug characteristics, and storage rules." --- # Product Knowledge -Technical reference for the `ProductKnowledge` module in Care EMR. For what Product Knowledge means to facility users, see the [Product Knowledge concept](../../concepts/definitions/product-knowledge.mdx). +`ProductKnowledge` is the reusable definition of a product — its coding, base presentation unit, ingredients and nutrients, drug characteristics, and storage rules. Define it once and every concrete `Product` points back to it instead of carrying duplicate data. A definition is either instance-wide or scoped to a single facility. -`ProductKnowledge` is the reusable definition of a product: its coding, base unit, names, storage guidelines, and type-specific definition. Every `Product` references one `ProductKnowledge` record. A record is either instance-level (no `facility`) or scoped to one facility. - -The Django model is only the storage layer: `code`, `names`, `storage_guidelines`, `definitional`, and `base_unit` are `JSONField`s whose structure lives in the Pydantic resource specs. The enums, nested shapes, and validation below come from those specs; the endpoints, scoping, and authorization come from the viewset. +The Django model is only the storage layer: `code`, `names`, `storage_guidelines`, `definitional`, and `base_unit` are opaque `JSONField`s whose real structure lives in the Pydantic resource specs. Every enum, nested JSON shape, validation rule, and read/write difference below comes from those specs. **Source:** - - Model: [`care/emr/models/product_knowledge.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/product_knowledge.py) - Spec: [`care/emr/resources/inventory/product_knowledge/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/product_knowledge/spec.py) - Value sets: [`care/emr/resources/inventory/product_knowledge/valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/product_knowledge/valueset.py) -- Viewset: [`care/emr/api/viewsets/inventory/product_knowledge.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/inventory/product_knowledge.py) -- Authorization: [`care/security/authorization/product_knowledge.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/product_knowledge.py) -- Permissions: [`care/security/permissions/product_knowledge.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/product_knowledge.py) ## Models | Model | Purpose | | --- | --- | -| `ProductKnowledge` | Reusable definition of a product (medication, nutritional product, or consumable) | - -`ProductKnowledge` extends [`SlugBaseModel`](../foundation/base-model.mdx), which extends `EMRBaseModel`. The shared base provides `external_id`, `created_date`, `modified_date`, and soft delete through `deleted`; `EMRBaseModel` adds `created_by`, `updated_by`, `history`, and `meta`. +| `ProductKnowledge` | Foundational, reusable definition of a product (medication, nutritional product, or consumable) | -`SlugBaseModel` sets `FACILITY_SCOPED = True` and adds the slug helpers `calculate_slug_from_facility`, `calculate_slug_from_instance`, and `parse_slug`. It defines no `save()`: the viewset prefixes the slug on create and update (see [Slug prefixing](#slug-prefixing)). +`ProductKnowledge` extends [`SlugBaseModel`](../foundation/base-model.mdx), which extends `EMRBaseModel` (the shared base providing `external_id`, `created_date`/`modified_date`, soft-delete via `deleted`, `created_by`/`updated_by`, and `history`/`meta` JSON). `SlugBaseModel` sets `FACILITY_SCOPED = True` and adds the slug helpers `calculate_slug` and `parse_slug`, so a record is addressable by an instance slug (`i-`) or a facility slug (`f--`). ## `ProductKnowledge` fields @@ -36,65 +28,72 @@ The Django model is only the storage layer: `code`, `names`, `storage_guidelines | Field | Type | Notes | | --- | --- | --- | -| `facility` | `FK → facility.Facility` | `PROTECT`, nullable. Null means instance-level; set means facility-scoped. In the spec base's `__exclude__`; only `ProductKnowledgeWriteSpec` (create) sets it, so an update cannot move a record to another facility. Surfaced on read as `is_instance_level` | -| `slug` | `CharField(255)` | Stores the full prefixed slug: `f--` or `i-`. The viewset sets it from `slug_value` on create and update. The API's lookup field | -| `alternate_identifier` | `CharField(255)`, nullable | Secondary identifier. The UI labels it "HSN Code" | -| `status` | `CharField(255)` | Spec-constrained to `ProductKnowledgeStatusOptions` (required) | -| `product_type` | `CharField(255)` | Spec-constrained to `ProductTypeOptions` (required) | -| `category` | `FK → emr.ResourceCategory` | `PROTECT`, nullable. Classifies the record into a [resource category](../platform/resource-category.mdx). Written as a category slug string; read returns the serialized category | +| `facility` | `FK → facility.Facility` | `PROTECT`, nullable. Null means an instance-level definition; set means facility-scoped. Excluded from the spec base (`__exclude__ = ["facility"]`); set on write via a `facility` UUID, surfaced on read as `is_instance_level` | +| `slug` | `CharField(255)` | Slug value; combined with `facility` to form the addressable slug. Set server-side from `slug_value` on write | +| `alternate_identifier` | `CharField(255)` | Nullable; secondary external identifier | +| `status` | `CharField(255)` | Lifecycle status. Spec-constrained to `ProductKnowledgeStatusOptions` (required) | +| `product_type` | `CharField(255)` | Product category. Spec-constrained to `ProductTypeOptions` (required) | +| `category` | `FK → emr.ResourceCategory` | `CASCADE`, nullable; classifies the product into a [resource category](../platform/resource-category.mdx). Write it as a category **slug** string, resolved via `ResourceCategory.objects.get(slug=...)`; read returns it as a nested object | ### Naming | Field | Type | Notes | | --- | --- | --- | | `name` | `CharField(255)` | Primary display name (required in spec) | -| `names` | `JSONField` (list), nullable | `list[ProductName] \| None`. See [ProductName](#productname) | -| `names_cache` | `CharField(2048)`, nullable | `name` plus every `names[].name`, space-joined, rebuilt on each `save()` by `set_names_cache()`. Searched by the `alternate_names` filter. In no spec; never set it from clients | +| `names` | `JSONField` (list) | Nullable; list of `ProductName { name_type: ProductNameTypes, name: str }`. `name_type` is bound to the `ProductNameTypes` enum, not a FHIR value set | +| `names_cache` | `CharField(2048)` | Nullable; denormalized space-joined string of `name` plus every `names` entry, rebuilt on each `save()` to power search. Platform-maintained, absent from every spec — never set it from clients | + +### Tags + +| Field | Type | Notes | +| --- | --- | --- | +| `tags` | `ArrayField[int]`, default `[]` | Applied [tag](../platform/tag-config.mdx) ids. Written through the tag actions, rendered on read by `SingleFacilityTagManager` | +| `tags_data` | `JSONField`, default `{}` | Denormalized tag payload maintained by the tagging layer. Not exposed by any spec | + +A product definition is taggable: `TagConfig` accepts `product_knowledge` as a `resource` value, and the viewset carries `EMRTagMixin` plus `SingleFacilityTagFilter`. Pass `?tags=` on the list endpoint to filter definitions by tag. Instance-level definitions take instance-level tags; facility-scoped definitions take that facility's tags. ### Coding & definition (JSON fields) -The model stores these as nullable `JSONField`s; the spec enforces the shapes below. +The model stores these as bare `JSONField`s; the spec enforces the shapes below. | Field | Model type | Spec type / shape | Notes | | --- | --- | --- | --- | -| `code` | `JSONField` (dict) | `Coding \| None` | Optional product code as a [`Coding`](#coding); not value-set bound at the spec layer. The UI searches `system-medication` for it | -| `base_unit` | `JSONField` (dict) | `ValueSetBoundCoding[CARE_UCUM_UNITS]` | Required. Bound to the UCUM units value set (`system-ucum-units`). The UI offers a fixed list of eight units | +| `code` | `JSONField` (dict) | `Coding \| None` | Nullable; product code as a [`Coding`](#coding), not value-set bound at the spec layer | +| `base_unit` | `JSONField` (dict) | `ValueSetBoundCoding[CARE_UCUM_UNITS]` | **Required**. A `Coding` bound to the UCUM units value set (`system-ucum-units`) | | `names` | `JSONField` (list) | `list[ProductName] \| None` | See [ProductName](#productname) | | `storage_guidelines` | `JSONField` (list) | `list[StorageGuideline] \| None` | See [StorageGuideline](#storageguideline) | -| `definitional` | `JSONField` (dict) | `ProductDefinitionSpec \| None` | See [ProductDefinitionSpec](#productdefinitionspec). The spec does not tie its contents to `product_type` | +| `definitional` | `JSONField` (dict) | `ProductDefinitionSpec \| None` | Type-specific definition payload. See [ProductDefinitionSpec](#productdefinitionspec) | ## Enums ### `ProductTypeOptions` (`product_type`) -| Value | UI label | -| --- | --- | -| `medication` | Medication | -| `nutritional_product` | Nutritional Product | -| `consumable` | None: the locale files have no `consumable` key, so the UI shows the raw word "consumable" | +| Value | +| --- | +| `medication` | +| `nutritional_product` | +| `consumable` | ### `ProductKnowledgeStatusOptions` (`status`) -| Value | Notes | -| --- | --- | -| `draft` | Offered by the UI form as "Draft" | -| `active` | Offered by the UI form as "Active"; the UI's default for new records. The UI's product knowledge pickers list only `active` records | -| `retired` | Offered by the UI form as "Retired"; set by the UI's "Delete" action | -| `unknown` | Accepted by the API; the UI form does not offer it | +| Value | +| --- | +| `draft` | +| `active` | +| `retired` | +| `unknown` | ### `ProductNameTypes` (`names[].name_type`) -| Value | UI label | -| --- | --- | -| `trade_name` | Trade Name (the UI's default) | -| `alias` | Alias | -| `original_name` | Original Name | -| `preferred` | Preferred | +| Value | +| --- | +| `trade_name` | +| `alias` | +| `original_name` | +| `preferred` | ### `DrugCharacteristicCode` (`definitional.drug_characteristic[].code`) -API only: the UI form has no field for drug characteristics. - | Value | | --- | | `imprint_code` | @@ -108,11 +107,11 @@ API only: the UI form has no field for drug characteristics. ## Nested spec shapes -These are plain Pydantic `BaseModel`s in `spec.py`. Every field listed as required has no default. +These are plain Pydantic `BaseModel`s in `spec.py`, not value-set bound unless noted. ### `ProductName` -`names[]`: alternate names for the product. +`names[]` — alternate names for the product. | Field | Type | Required | Notes | | --- | --- | --- | --- | @@ -121,21 +120,21 @@ These are plain Pydantic `BaseModel`s in `spec.py`. Every field listed as requir ### `StorageGuideline` -`storage_guidelines[]`: a storage note paired with a stability duration. +`storage_guidelines[]` — a storage note paired with a stability duration. | Field | Type | Required | Notes | | --- | --- | --- | --- | | `note` | `str` | yes | | -| `stability_duration` | `DurationSpec` = `value: int`, `unit: Coding` | yes | `value` is a whole number; `unit` is a free `Coding`. The UI offers minutes, hours, days, weeks, months, and years | +| `stability_duration` | `DurationSpec { value: int, unit: Coding }` | yes | `value` is an integer count; `unit` is a free `Coding` | ### `ProductDefinitionSpec` -`definitional`: the dosage form, routes, ingredients, nutrients, and drug characteristics. The 3.1 UI form edits only `dosage_form` and `intended_routes`; the other three lists are set through the API only. +`definitional` — type-specific definition payload. | Field | Type | Default | Notes | | --- | --- | --- | --- | -| `dosage_form` | `ValueSetBoundCoding[MEDICATION_FORM_CODES] \| None` | required (nullable) | Bound to medication form codes (`system-medication-form-codes`, SNOMED is-a `736542009`) | -| `intended_routes` | `list[Coding]` | `[]` | Free `Coding`s, not value-set bound. The UI picks them from `system-route` | +| `dosage_form` | `ValueSetBoundCoding[MEDICATION_FORM_CODES] \| None` | required (nullable) | `Coding` bound to medication form codes (`system-medication-form-codes`, SNOMED is-a `736542009`) | +| `intended_routes` | `list[Coding]` | `[]` | Free `Coding`s, not value-set bound | | `ingredients` | `list[ProductIngredient]` | `[]` | See [ProductIngredient](#productingredient) | | `nutrients` | `list[ProductNutrient]` | `[]` | See [ProductNutrient](#productnutrient) | | `drug_characteristic` | `list[DrugCharacteristic]` | `[]` | See [DrugCharacteristic](#drugcharacteristic) | @@ -146,8 +145,8 @@ These are plain Pydantic `BaseModel`s in `spec.py`. Every field listed as requir | Field | Type | Required | Notes | | --- | --- | --- | --- | -| `is_active` | `bool` | yes | Active or inactive ingredient | -| `substance` | `ValueSetBoundCoding[CARE_SUBSTANCE_VALUSET]` | yes | Bound to the substance value set (`system-substance`, SNOMED is-a `105590001`) | +| `is_active` | `bool` | yes | Active vs. inactive ingredient | +| `substance` | `ValueSetBoundCoding[CARE_SUBSTANCE_VALUSET]` | yes | `Coding` bound to the substance value set (`system-substance`, SNOMED is-a `105590001`) | | `strength` | `ProductStrength` | yes | See [ProductStrength](#productstrength) | ### `ProductNutrient` @@ -156,7 +155,7 @@ These are plain Pydantic `BaseModel`s in `spec.py`. Every field listed as requir | Field | Type | Required | Notes | | --- | --- | --- | --- | -| `item` | `ValueSetBoundCoding[CARE_NUTRIENTS_VALUESET]` | yes | Bound to the nutrients value set (`system-nutrients`, SNOMED is-a `226355009`) | +| `item` | `ValueSetBoundCoding[CARE_NUTRIENTS_VALUESET]` | yes | `Coding` bound to the nutrients value set (`system-nutrients`, SNOMED is-a `226355009`) | | `amount` | `ProductStrength` | yes | See [ProductStrength](#productstrength) | ### `ProductStrength` @@ -165,7 +164,7 @@ Shared by `ProductIngredient.strength` and `ProductNutrient.amount`. | Field | Type | Required | Notes | | --- | --- | --- | --- | -| `ratio` | `Ratio` = `numerator: Quantity`, `denominator: Quantity` | yes | | +| `ratio` | `Ratio { numerator: Quantity, denominator: Quantity }` | yes | | | `quantity` | `Quantity` | yes | See [Quantity](#quantity) | ### `DrugCharacteristic` @@ -190,7 +189,7 @@ From `care/emr/resources/common/coding.py` (`extra="forbid"`). | `code` | `str` | yes | | `display` | `str \| None` | no | -A `ValueSetBoundCoding[]` is a `Coding` whose `code` is validated against the named value set on input. +A `ValueSetBoundCoding[]` is a `Coding` subclass that additionally validates `code` against the named value set on deserialization. ### `Quantity` @@ -198,130 +197,62 @@ From `care/emr/resources/common/quantity.py` (`extra="forbid"`). | Field | Type | Notes | | --- | --- | --- | -| `value` | `Decimal \| None` | At most 20 digits, 6 decimal places | -| `unit` | `Coding \| None` | Human-readable form of the unit | -| `code` | `Coding \| None` | Computer-processable form of the unit | +| `value` | `Decimal \| None` | max 20 digits, 6 decimal places | +| `unit` | `Coding \| None` | human-readable unit | +| `code` | `Coding \| None` | machine-processable unit | | `meta` | `dict \| None` | | -`Ratio` has `numerator: Quantity` and `denominator: Quantity`, both required. - -## Related models - -| Model | Field | Relationship | -| --- | --- | --- | -| [`Product`](../supply/product.mdx) | `product_knowledge` | Required FK to `ProductKnowledge`, `PROTECT`. Every product references one record | -| [`InventoryItem`](../supply/inventory-item.mdx) | `product` | Required FK to `Product`, `PROTECT`; reaches `ProductKnowledge` only through the product | -| [`SupplyRequest`](../supply/supply-request.mdx) | `item` | FK to `ProductKnowledge`, `CASCADE` | -| [`MedicationRequest`](../medications/medication-request.mdx) | `requested_product` | Optional FK to `ProductKnowledge`, `SET_NULL` | -| [`MedicationAdministration`](../medications/medication-administration.mdx) | `administered_product` | Optional FK to `ProductKnowledge`, `CASCADE` | +`Ratio { numerator: Quantity, denominator: Quantity }` — both required. ## Resource specs (API schema) -Every spec builds on `EMRResource` (`care/emr/resources/base.py`). +Every spec builds on `EMRResource` (`care/emr/resources/base.py`), which provides `serialize` (DB → Pydantic), `de_serialize` (Pydantic → DB), and the `perform_extra_serialization` / `perform_extra_deserialization` hooks. `EMRResource.serialize` copies only non-FK database fields that are declared spec fields and not in `__exclude__`. | Spec class | Role | Adds / behaviour | | --- | --- | --- | | `BaseProductKnowledgeSpec` | shared base | `__exclude__ = ["facility"]`. Fields: `id`, `alternate_identifier`, `status`, `product_type`, `code`, `base_unit` (required, UCUM-bound), `name`, `names`, `storage_guidelines`, `definitional` | -| `ProductKnowledgeUpdateSpec` | write · update | Adds `category: str \| None` (resource category slug) and `slug_value: SlugType` (required). On deserialize, resolves `category` with `ResourceCategory.objects.get(slug=...)` and sets `obj.slug = slug_value` | -| `ProductKnowledgeWriteSpec` | write · create | Extends the update spec; adds `facility: UUID4 \| None`. On deserialize, runs the update-spec logic, then resolves `facility` by external id | -| `ProductKnowledgeReadSpec` | read · list and detail | Adds `is_instance_level` (true when there is no facility), `category` (serialized resource category), `slug_config` (the parsed slug: `facility` and `slug_value`, or `slug_value` only), and `slug` | +| `ProductKnowledgeUpdateSpec` | write · update | Adds `category: str \| None` (resource-category **slug**) and `slug_value: SlugType` (required). On deserialize, resolves `category` via `ResourceCategory.objects.get(slug=...)` and sets `obj.slug = self.slug_value` | +| `ProductKnowledgeWriteSpec` | write · create | Extends the update spec; adds `facility: UUID4 \| None`. On deserialize, runs the update-spec logic, then resolves `facility` via `Facility.objects.get(external_id=...)` when supplied | +| `ProductKnowledgeReadSpec` | read · detail/list | Adds `is_instance_level: bool`, `category: dict \| None`, `slug_config: dict`, `slug: str`, `tags: list[dict]`. On serialize, sets `id = external_id`, `is_instance_level = not facility_id`, serializes `category` via `ResourceCategoryReadSpec`, sets `slug_config = parse_slug(slug)`, and renders `tags` with `SingleFacilityTagManager` | ### Validation & bound value sets -- `status`, `product_type`, `base_unit`, and `name` are required. -- `base_unit` is bound to `system-ucum-units`. -- `definitional.dosage_form` is bound to `system-medication-form-codes`, `ingredients[].substance` to `system-substance`, and `nutrients[].item` to `system-nutrients`. `code` and `intended_routes` stay free `Coding`s. -- `slug_value` uses `SlugType`: 5–50 characters, starting and ending with a letter or digit, and containing only letters, digits, `-`, and `_`. -- Create and update reject a slug that already exists in the same scope (the same facility, or instance level), compared without case, with the validation error "Slug already exists.". -- For a facility record, the viewset returns 404 for an unknown `category` slug. +- `status` ∈ `ProductKnowledgeStatusOptions` and `product_type` ∈ `ProductTypeOptions`, both required. +- `base_unit` is **required** and bound to `CARE_UCUM_UNITS` (`system-ucum-units`, system `http://unitsofmeasure.org`). +- `definitional.dosage_form` is bound to `MEDICATION_FORM_CODES`; `ingredients[].substance` to `CARE_SUBSTANCE_VALUSET`; `nutrients[].item` to `CARE_NUTRIENTS_VALUESET`. `code` and `intended_routes` stay free `Coding`s. +- `slug_value` uses `SlugType`: 5–50 chars, URL-safe (`^[a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9]$`), starting and ending alphanumeric. +- `category` on write is a slug string; an unknown slug raises `DoesNotExist` from `.get(...)`. ### Server-maintained behaviour -- `facility` is set only on create, from `ProductKnowledgeWriteSpec.facility`. -- The viewset prefixes `slug` on create and update; the model rebuilds `names_cache` in `save()`. -- `is_instance_level`, `slug_config`, and the serialized `category` are computed on read; none of them is a stored column. +- `facility` never flows through the generic field loop (it sits in `__exclude__`); only `ProductKnowledgeWriteSpec` (create) sets it, from the `facility` UUID. +- `slug` is set server-side from `slug_value`; `names_cache` is rebuilt in the model's `save()` (see below). +- On read, `is_instance_level`, `slug_config`, the serialized `category`, and `tags` are computed in `perform_extra_serialization` — none are stored columns. ## Methods & save behaviour ### `save()` side effects -`save()` calls `set_names_cache()` before it writes the record: +`save()` rebuilds `names_cache` before persisting: 1. `names_cache` is reset to `" "`. -2. The `name` of each entry in `names` is appended, separated by spaces. -3. `super().save()` writes the record. - -`names_cache` is platform-maintained: write `name` and `names` instead. +2. For each entry in `names`, the entry's `name` (dict key or attribute) is appended, space-separated. +3. `super().save()` persists the record, including the slug logic inherited from `SlugBaseModel`. -### Slug prefixing - -`ProductKnowledgeViewSet.recalculate_slug()` runs in `perform_create` and `perform_update`. It stores `f--` for a facility record and `i-` for an instance-level record. `SlugBaseModel` has no `save()` of its own. +`names_cache` is platform-maintained — write to `name` and `names` instead of setting it directly. ## API integration notes -### Endpoints - -The API is registered at `/api/v1/product_knowledge/`, not nested under a facility. Records are addressed by `slug`, the full prefixed slug. - -| Method and path | Action | Notes | -| --- | --- | --- | -| `GET /api/v1/product_knowledge/` | list | See filters and scoping below | -| `POST /api/v1/product_knowledge/` | create | Body: `ProductKnowledgeWriteSpec` | -| `GET /api/v1/product_knowledge//` | retrieve | Returns `ProductKnowledgeReadSpec` | -| `PUT /api/v1/product_knowledge//` | update | Body: `ProductKnowledgeUpdateSpec`. The UI sends `PUT` | -| `POST /api/v1/product_knowledge/upsert/` | upsert | Body: a `datapoints` list. A datapoint with `id` (the slug) updates that record; one without `id` creates a record. If any datapoint fails, the batch is rolled back and the response is 400 with the per-datapoint results | -| `GET /api/v1/product_knowledge/favorite_lists/` | favorites | The caller's favorite list names | -| `POST /api/v1/product_knowledge//add_favorite/` | favorites | Body: optional `favorite_list` | -| `POST /api/v1/product_knowledge//remove_favorite/` | favorites | Body: optional `favorite_list` | - -There is no delete endpoint. The UI's "Delete" action sends a `PUT` that sets `status` to `retired`. - -### Filters and ordering - -| Parameter | Behaviour | -| --- | --- | -| `facility` | Scopes the list to one facility. See scoping below | -| `include_instance` | With `facility`: `true` adds instance-level records | -| `category` | A category slug, looked up in the same facility. With `include_children=true`, records in descendant categories are also returned | -| `status`, `product_type`, `alternate_identifier` | Exact match, case-insensitive | -| `name`, `alternate_names` | Trigram similarity above 0.1 on `name` or `names_cache`, ordered by similarity | -| `facility_is_null` | Null filter on `facility` | -| `ordering` | `created_date` or `modified_date` | - -### Scoping and authorization - -- List with `facility`: requires `can_read_product_knowledge` in any organization of that facility. Returns that facility's records, plus instance-level records when `include_instance=true`. -- List without `facility`: returns only instance-level records, with no permission check. -- Retrieve a facility record: requires `can_read_product_knowledge` in any organization of its facility; otherwise 403 "Cannot read product knowledge". Retrieving an instance-level record has no permission check. -- Create a facility record: requires `can_write_product_knowledge` in the facility's root organization (named "Administration"); otherwise 403 "Cannot create product knowledge". A role holding the permission in another department of the facility is refused. -- Update a facility record: requires `can_write_product_knowledge` in the root organization of the record's facility; otherwise 403 "Cannot update product knowledge". -- Instance-level records cannot be created or updated through facility permissions. -- Only facility-organization memberships count; governance-organization memberships are not consulted. -- The frontend's list calls send `include_instance=true` by default, so pickers that do not override it also list instance-level records. - -| Permission | Display name | Checked in | Default roles | -| --- | --- | --- | --- | -| `can_write_product_knowledge` | Can Create Product Knowledge on Facility | The facility's root organization | Facility Admin | -| `can_read_product_knowledge` | Can Read Product Knowledge | Any organization of the facility | Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist | - -Authorization reads role permissions from the database. Each permission sync rewrites the default roles from code; custom roles can also hold these permissions. - -### UI notes - -- The UI labels `alternate_identifier` "HSN Code". -- The UI creates records only inside a category with no subcategories, and always sends the current `facility`. -- The 3.1 UI form has no fields for `ingredients`, `nutrients`, or `drug_characteristic`. -- The UI's create form opens with the `definitional` block added, and requires `dosage_form` until the user removes the block. +- Exposed through Care's REST API; aligns with the FHIR `MedicationKnowledge` and `NutritionProduct` concepts. +- `product_type` decides what `definitional` means (`medication`, `nutritional_product`, or `consumable`). +- `facility` controls scope: omit it for instance-wide, set it for facility-local. Address records by slug (`i-` or `f--`); the parsed parts come back as `slug_config`. +- `code`, `names`, `storage_guidelines`, `definitional`, and `base_unit` carry their structure and value-set binding in the spec, not the model. `base_unit` is required. ## Related -- Concept: [Product Knowledge](../../concepts/definitions/product-knowledge.mdx) - Reference: [Product](../supply/product.mdx) +- Reference: [Tagging](../platform/tag-config.mdx) - Reference: [Inventory Item](../supply/inventory-item.mdx) -- Reference: [Supply Request](../supply/supply-request.mdx) -- Reference: [Medication Request](../medications/medication-request.mdx) -- Reference: [Medication Administration](../medications/medication-administration.mdx) - Reference: [Resource Category](../platform/resource-category.mdx) -- Reference: [Favorites](../platform/favorites.mdx) - Base: [Base model](../foundation/base-model.mdx) -- Source: [model](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/product_knowledge.py) · [spec](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/product_knowledge/spec.py) · [value sets](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/product_knowledge/valueset.py) · [viewset](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/inventory/product_knowledge.py) +- Source: [model](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/product_knowledge.py) · [spec](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/product_knowledge/spec.py) · [value sets](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/product_knowledge/valueset.py) diff --git a/versioned_docs/version-3.1/references/platform/tag-config.mdx b/versioned_docs/version-3.1/references/platform/tag-config.mdx index 8933749b..f74df901 100644 --- a/versioned_docs/version-3.1/references/platform/tag-config.mdx +++ b/versioned_docs/version-3.1/references/platform/tag-config.mdx @@ -18,8 +18,7 @@ Two layers back the tag. The Django model (`care/emr/models/tag_config.py`) is s | Model | Purpose | | --- | --- | -| `TagConfig` | Definition of a single tag — its display, category, scope, status, metadata, expiry settings, and position in the tag tree | -| `TagDeleteRequest` | Scheduled removal of one expiring tag from one tagged resource. Fields: `resource_type` (`CharField(255)`), `resource_id` (`IntegerField`), `tag_config` (`FK → TagConfig`, `CASCADE`), `trigger_at` (`DateTimeField`, indexed). Unique on (`resource_type`, `resource_id`, `tag_config`) | +| `TagConfig` | Definition of a single tag — its display, category, scope, status, metadata, and position in the tag tree | `TagConfig` extends [`EMRBaseModel`](../foundation/base-model.mdx), the shared Care EMR base providing `external_id`, the audit fields `created_by`/`updated_by` and `created_date`/`modified_date`, soft-delete via `deleted`, and `history`/`meta` JSON. Applied tag IDs live on the tagged resource itself — for example `Patient.instance_tags` / `Patient.facility_tags` and `Encounter.tags`. @@ -46,7 +45,6 @@ A tag is scoped to at most one owner — an instance-wide organization, a facili | `category` | `CharField(255)` | Grouping category. Constrained by `TagCategoryChoices` in the spec (see [enum](#tagcategorychoices-values)) | | `priority` | `IntegerField` | `default=100`. Ordering weight | | `metadata` | `JSONField` | `default=None`, nullable. Shape defined by `TagConfigMetadata`: `{ color: str?, icon: str? }` (see [nested spec](#tagconfigmetadata-shape-of-metadata)) | -| `expiry_metadata` | `JSONField` | `default=dict`. Expiry settings used when the tag is set on a resource. Shape defined by `TagConfigExpiryMetadata` (see [nested spec](#tagconfigexpirymetadata-shape-of-expiry_metadata)). An empty object means the tag never expires | ### Tree structure & caches @@ -97,6 +95,8 @@ A tag is scoped to at most one owner — an instance-wide organization, a facili | `supply_request_order` | | `supply_delivery_order` | | `account` | +| `location` | +| `product_knowledge` | ### `TagStatus` values @@ -118,40 +118,13 @@ Gives the opaque `metadata` `JSONField` a real structure. A plain Pydantic `Base | `color` | `str \| None` | no | `None` | Display color hint | | `icon` | `str \| None` | no | `None` | Display icon hint | -### `TagConfigExpiryMetadata` (shape of `expiry_metadata`) - -A plain Pydantic `BaseModel`. Every field defaults to Pydantic's `MISSING` sentinel, so a field that the client leaves out is left out of the stored JSON (an empty spec dumps to `{}`). - -| Field | Type | Required | Default | Notes | -| --- | --- | --- | --- | --- | -| `autoset_expiry` | `bool` | no | `MISSING` | When `true`, setting the tag on a resource gives it an expiry of now + `expiry_offset` | -| `expiry_offset` | `ExpiryOffset` | no | `MISSING` | Default offset. Required when `autoset_expiry` is `true` | -| `modification_allowed` | `bool` | no | `MISSING` | When `true`, the `expiry_offset` of a tag set request replaces the default | - -Validation: a `model_validator(mode="after")` rejects `autoset_expiry=true` without `expiry_offset` — `ValueError("Expiry offset is required when autoset expiry is set")`. - -### `ExpiryOffset` - -A duration, passed to Python's `timedelta`. Each unit is an `int` that defaults to `MISSING`, so only the units sent are stored (for example `{ "hours": 2 }`). - -| Field | Type | Required | Default | -| --- | --- | --- | --- | -| `days` | `int` | no | `MISSING` | -| `hours` | `int` | no | `MISSING` | -| `minutes` | `int` | no | `MISSING` | -| `seconds` | `int` | no | `MISSING` | - -The tag config form in care_fe offers days, hours and minutes only, requires a total above zero when `autoset_expiry` is on, caps the total at 3650 days, and sends `expiry_offset` only when `autoset_expiry` is on. The backend spec itself sets no bounds. - -`TagSetRequest` (the body item for setting a tag on a resource) carries `tag` (`UUID4`) and an optional `expiry_offset` (`ExpiryOffset \| None`). - ## Resource specs (API schema) Every spec extends `EMRResource` (`care/emr/resources/base.py`), which supplies `serialize` (DB object → spec) and `de_serialize` (spec → DB object) plus the `perform_extra_serialization` / `perform_extra_deserialization` hooks. `__exclude__` on the base spec keeps the FK fields (`facility`, `facility_organization`, `organization`, `parent`) out of the generic field copy so each spec can resolve them explicitly. | Spec class | Role | Notes | | --- | --- | --- | -| `TagConfigBaseSpec` | shared | `__model__ = TagConfig`; `__exclude__ = [facility, facility_organization, organization, parent]`. Fields: `id` (`UUID4?`), `display`, `category` (`TagCategoryChoices`), `description` (`str \| None`), `priority` (`int = 100`), `status` (`TagStatus`), `metadata` (`TagConfigMetadata?`), `expiry_metadata` (`TagConfigExpiryMetadata`, defaults to `MISSING`; when omitted on update, the stored value is kept) | +| `TagConfigBaseSpec` | shared | `__model__ = TagConfig`; `__exclude__ = [facility, facility_organization, organization, parent]`. Fields: `id` (`UUID4?`), `display`, `category` (`TagCategoryChoices`), `description` (`str \| None`), `priority` (`int = 100`), `status` (`TagStatus`), `metadata` (`TagConfigMetadata?`) | | `TagConfigWriteSpec` | write · create | Base + `facility?`, `facility_organization?`, `organization?`, `parent?` (all `UUID4`), `resource` (`TagResource`, required). Runs two `model_validator(after)` checks and resolves FKs in `perform_extra_deserialization` | | `TagConfigUpdateSpec` | write · update | Base + `facility_organization?`, `organization?` (`UUID4`). Cannot change `facility`, `parent`, or `resource`. Resolves `organization`/`facility_organization` in `perform_extra_deserialization` (facility organization scoped to `obj.facility`) | | `TagConfigReadSpec` | read · list | `@cacheable`. Base + `level_cache` (`int = 0`), `system_generated` (`bool`), `has_children` (`bool`), `parent` (`dict \| None`), `resource` (`str`), `facility` (`dict \| None`). Inlines parent via `get_parent_json()` and a `FacilityBareMinimumSpec` for `facility` | @@ -173,14 +146,6 @@ Two `@model_validator(mode="after")` checks run before deserialization: - `TagConfigReadSpec.perform_extra_serialization` sets `id = external_id`, inlines the parent record via `obj.get_parent_json()` (only when non-empty), and serializes `facility` with `FacilityBareMinimumSpec` (`{ id, name }`). - `TagConfigRetrieveSpec.perform_extra_serialization` calls the read-spec hook, then `serialize_audit_users` (populates `created_by`/`updated_by` from cache) and serializes `facility_organization` / `organization` with their full read specs. - Tree caches (`level_cache`, `parent_cache`, `root_tag_config`, `has_children`) are populated by the model's `set_tag_config_cache()` on insert — never accepted from clients. -- Tag expiry, when a tag is set on a resource (`SingleFacilityTagManager.set_tag` in `care/emr/tagging/base.py`): - - If `expiry_metadata.autoset_expiry` is true and `expiry_offset` is set, the expiry is `care_now() + timedelta(**expiry_offset)`. - - If `expiry_metadata.modification_allowed` is true and the `TagSetRequest` carries an `expiry_offset`, that offset is used instead. Otherwise a requested `expiry_offset` is ignored. - - With an expiry, the manager writes `tags_data[str(tag_config.id)] = { "expiry": str(expiry) }` on the resource and upserts a `TagDeleteRequest` with `trigger_at = expiry`. - - Unsetting the tag deletes its `tags_data` entry. - - The Celery task `autohandle_expired_tasks` runs every hour (`crontab(minute="0")`). It queues `handle_expired_tag` for each due `TagDeleteRequest` and deletes the request. `handle_expired_tag` removes every expired tag id and its `tags_data` entry from the resource. - - `render_tags` adds `expiry` to each tag that has one, and adds `expired: true` and queues `handle_expired_tag` when the expiry has passed. - - Editing a `TagConfig` does not change expiries already stored on resources. - `system_generated` is declared on `TagConfigReadSpec` but is not a field on the current `TagConfig` model (nor on `EMRBaseModel`). The generic `serialize` only copies model fields, so it is not populated from storage unless something else provides it. Treat it as a read-only flag and verify against the live model before relying on it. ### Cache invalidation @@ -207,12 +172,12 @@ On insert (no `id` yet), the base `save()` runs first, then `set_tag_config_cach ## API integration notes -The REST API exposes only the definitions. Applied tags are stored as integer ID arrays on each tagged resource (e.g. `Patient.instance_tags`/`facility_tags`, `Encounter.tags`), not as join rows. Expiry times of applied tags live in the resource's `tags_data` JSON, keyed by tag id. +The REST API exposes only the definitions. Applied tags are stored as integer ID arrays on each tagged resource (e.g. `Patient.instance_tags`/`facility_tags`, `Encounter.tags`), not as join rows. Each operation maps to one spec: - Create — `TagConfigWriteSpec`. Sets `resource`, the scope FKs, and `parent`. `resource` must match a [`TagResource`](#tagresource-values) value. -- Update — `TagConfigUpdateSpec`. Reassigns org/facility-org only, plus the shared display/category/status/metadata/expiry_metadata fields; `facility`, `parent`, and `resource` are fixed. +- Update — `TagConfigUpdateSpec`. Reassigns org/facility-org only, plus the shared display/category/status/metadata fields; `facility`, `parent`, and `resource` are fixed. - List — `TagConfigReadSpec`. Detail — `TagConfigRetrieveSpec`. `metadata` carries display hints (`color`, `icon`) without a schema migration, shaped by `TagConfigMetadata`. diff --git a/versioned_docs/version-3.1/references/scheduling/schedule.mdx b/versioned_docs/version-3.1/references/scheduling/schedule.mdx index 5184ede1..4cadeb86 100644 --- a/versioned_docs/version-3.1/references/scheduling/schedule.mdx +++ b/versioned_docs/version-3.1/references/scheduling/schedule.mdx @@ -10,7 +10,6 @@ A schedule is a repeatable block of time during which a resource — a practitio **Source:** - Model: [`care/emr/models/scheduling/schedule.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/scheduling/schedule.py) - Resource specs: [`schedule/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/scheduling/schedule/spec.py), [`availability_exception/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/scheduling/availability_exception/spec.py), [`resource/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/scheduling/resource/spec.py) -- Viewsets: [`scheduling/schedule.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/scheduling/schedule.py), [`scheduling/availability_exceptions.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/scheduling/availability_exceptions.py) The Django model (`care/emr/models/scheduling/schedule.py`) is storage only, down to the opaque `Availability.availability` `JSONField`. The contract lives in the Pydantic resource specs (`care/emr/resources/scheduling/...`): the enums, the real shape of that JSON field, the validation rules, and the separate read/write schemas. Everything below `## Models` describes the specs. @@ -29,24 +28,15 @@ All four extend [`EMRBaseModel`](../foundation/base-model.mdx), which supplies ` | Field | Type | Req. | Notes | | --- | --- | --- | --- | -| `resource` | `FK → SchedulableResource` (CASCADE) | server | Resolved server-side from `resource_type` + `resource_id` (get-or-create). Not a spec field; the body cannot set it | +| `resource` | `FK → SchedulableResource` (CASCADE) | server | Resolved server-side from `resource_type` + `resource_id` (get-or-create). Reject this in the body | | `name` | `CharField(255)` | yes | Display name (e.g. "Morning OPD") | -| `valid_from` | `DateTimeField` | yes | Start of the effective window. On create, its local date must not be before today, and it must be ≤ `valid_to`. Update does not check either rule | -| `valid_to` | `DateTimeField` | yes | End of the effective window. On create, its local date must not be before today | +| `valid_from` | `DateTimeField` | yes | Start of the effective window. Must be ≥ now and ≤ `valid_to` | +| `valid_to` | `DateTimeField` | yes | End of the effective window. Must be ≥ now | | `revisit_allowed_days` | `IntegerField` | no | Nullable. Window within which a follow-up uses the revisit charge. Settable only via the `set_charge_item_definition` action | | `is_public` | `BooleanField` | yes | Exposes the schedule for public booking. Model default `False` | - -### Encounter defaults - -The server stores and returns these fields and does not act on them. care_fe uses them to prefill the encounter form for a booking on this schedule. - -| Field | Type | Req. | Notes | -| --- | --- | --- | --- | -| `organizations` | `ArrayField[int]`, default `[]` | no | Integer IDs of `FacilityOrganization`s. Write as `organizations: list[UUID4]`; each must be an organization of the schedule's facility (`"Organizations must belong to the schedule facility"`). Read (detail only) as a `FacilityOrganizationReadSpec` list | -| `care_team` | `JSONField`, default `[]` | no | Stored as `[{user_id: int, role: Coding}]`. Write as `list[EncounterCareTeamMemberSpec]` (`{user_id: UUID4, role}`, `role` bound to `system-practitioner-role-code`). Users must be unique, active, and members of an organization of the schedule's facility. Read (detail only) as `[{member: UserSpec, role}]` | -| `encounter_type` | `CharField(100)`, nullable | no | One of the encounter [`ClassChoices`](../clinical/encounter.mdx) values: `imp`, `amb`, `obsenc`, `emer`, `vr`, `hh` | - -On create and update, the server writes `organizations` and `care_team` only when the request includes them. It writes `encounter_type` only when the request includes it; `null` clears it. +| `encounter_type` | `CharField(100)` | no | Nullable. Class of encounter started from a booking. Bound to `ClassChoices` in the specs | +| `questionnaire_id` | `TextField` | no | Nullable. Identifier (slug or UUID) of the questionnaire to show for a booking against this schedule. Free text — the server does not resolve it | +| `extensions` | `JSONField`, default `{}` | no | Open extension bag for deployment-specific metadata. Validated by `ExtensionValidator` against `ExtensionResource.schedule` | ### Billing links @@ -77,9 +67,9 @@ The type of an individual `Availability` block (`Availability.slot_type` on the | Value | Meaning | | --- | --- | -| `open` | Open block; `validate_for_slot_type` clears `slot_size_in_minutes` / `tokens_per_slot` to `null` | -| `appointment` | Time-precise appointment block; requires both `slot_size_in_minutes` and `tokens_per_slot`. Only this type produces `TokenSlot`s and counts in `availability_stats` | -| `closed` | Closed block; `validate_for_slot_type` clears `slot_size_in_minutes` / `tokens_per_slot` to `null` | +| `open` | Open block; `slot_size_in_minutes` / `tokens_per_slot` are cleared to `null` on save | +| `appointment` | Time-precise appointment block; requires both `slot_size_in_minutes` and `tokens_per_slot` | +| `closed` | Closed block; `slot_size_in_minutes` / `tokens_per_slot` are cleared to `null` on save | ## Related models @@ -114,9 +104,9 @@ Decides how a schedule's time divides into bookable slots. One schedule can carr | `schedule` | `FK Schedule` (CASCADE) | server | Excluded from the availability spec; set from the URL / parent schedule | | `name` | `CharField(255)` | yes | Block name | | `slot_type` | `CharField` | yes | One of [`SlotTypeOptions`](#slottypeoptions) | -| `slot_size_in_minutes` | `IntegerField` (nullable) | conditional | `int \| None`, `ge=1`, no default, so the key is always required (it may be `null`). A value is required when `slot_type == appointment`; forced to `null` otherwise | -| `tokens_per_slot` | `IntegerField` (nullable) | conditional | `int \| None`, `ge=1`, no default, so the key is always required (it may be `null`). Capacity per slot. A value is required when `slot_type == appointment`; forced to `null` otherwise | -| `create_tokens` | `BooleanField` | no | Default `False`. Stored and returned; no backend code reads it | +| `slot_size_in_minutes` | `IntegerField` (nullable) | conditional | `int \| None`, `ge=1`. Required when `slot_type == appointment`; forced to `null` otherwise | +| `tokens_per_slot` | `IntegerField` (nullable) | conditional | `int \| None`, `ge=1`. Capacity per slot. Required when `slot_type == appointment`; forced to `null` otherwise | +| `create_tokens` | `BooleanField` | no | Default `False`. When `True`, each booking gets a token (queue/token workflows) | | `reason` | `TextField` (nullable) | no | Spec default `""` | | `availability` | `JSONField`, default `dict` | yes | Despite the `dict` default, the spec models it as a `list[AvailabilityDateTimeSpec]` (weekly recurrence). See below | @@ -126,7 +116,7 @@ Each entry is one weekly recurrence window. The field stores a list of these obj ```text AvailabilityDateTimeSpec { - day_of_week: int # Monday=0 … Sunday=6 (Python date.weekday()); only le=6 is validated, no lower bound + day_of_week: int # 0–6, validated le=6 (Monday=0 … Sunday=6, ISO-style) start_time: time # HH:MM:SS end_time: time # HH:MM:SS } @@ -134,7 +124,7 @@ AvailabilityDateTimeSpec { The list is validated by `AvailabilityForScheduleSpec.validate_availability` + `validate_for_slot_type`: - Every entry needs `start_time < end_time` (strict). -- No two entries on the **same** `day_of_week` may overlap (`has_overlapping_availability`: ranges overlap when `a.start ≤ b.end and b.start ≤ a.end`, so windows that only touch also count as overlapping). `ScheduleCreateSpec` checks overlap across all availabilities in the request; `AvailabilityCreateSpec` checks it against every existing availability of the schedule. +- No two entries on the **same** `day_of_week` may overlap (`has_overlapping_availability`: ranges overlap when `a.start ≤ b.end and b.start ≤ a.end`). On create, overlap is checked across all availabilities of the same schedule. - For `slot_type == appointment`: `slot_size_in_minutes` and `tokens_per_slot` are mandatory, each window's duration must be an exact multiple of `slot_size_in_minutes`, and the resulting slot count must not exceed `settings.MAX_SLOTS_PER_AVAILABILITY` (default `30`). ### `AvailabilityException` @@ -144,7 +134,7 @@ Blocks a resource for a date/time range regardless of its schedules — leave, h | Field | Type | Req. | Spec detail | | --- | --- | --- | --- | | `resource` | `FK SchedulableResource` (CASCADE) | server | Resolved from `resource_type` + `resource_id` (get-or-create); excluded from the spec body | -| `name` | `CharField(255)` | — | Not in any spec, so the API cannot write or read it. Rows created through the API store the Django default `""` | +| `name` | `CharField(255)` | yes | Exception name | | `reason` | `TextField` (nullable) | no | `str \| None` | | `valid_from` | `DateField` | yes | `date`. Must be ≥ today and ≤ `valid_to` | | `valid_to` | `DateField` | yes | `date`. Must be ≥ today | @@ -157,38 +147,38 @@ Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care | Spec | Role | Exposes / behaviour | | --- | --- | --- | -| `ScheduleBaseSpec` | shared | `id`, `is_public`, `encounter_type: ClassChoices \| None = None`. `__exclude__ = ["resource", "facility"]` | -| `ScheduleWriteSpec` | write · shared | Base + `organizations: list[UUID4] = []`, `care_team: list[EncounterCareTeamMemberSpec] = []`, `encounter_type: ClassChoices \| None \| MISSING = MISSING`. Adds `organizations` and `care_team` to `__exclude__` and resolves them in `perform_extra_deserialization` (see [Encounter defaults](#encounter-defaults)) | -| `ScheduleCreateSpec` | write · create | `ScheduleWriteSpec` + `facility`, `name`, `valid_from`, `valid_to`, `availabilities: list[AvailabilityForScheduleSpec]`, `resource_type`, `resource_id`. Validates that neither date's local date is before today, `valid_from ≤ valid_to`, and cross-availability non-overlap. `perform_extra_deserialization` sets `facility`, `_resource_id`, `_resource_type`, and `availabilities` on the instance for the viewset, then runs the `ScheduleWriteSpec` step | -| `ScheduleUpdateSpec` | write · update | `ScheduleWriteSpec` + `name`, `valid_from`, `valid_to`. `perform_extra_deserialization` blocks narrowing validity that would drop allocated slots — it compares `Sum(TokenSlot.allocated)` across the old vs new range and raises if they differ — then runs the `ScheduleWriteSpec` step | -| `ScheduleReadSpec` | read · list | Base fields plus `name`, `valid_from`, `valid_to`, `availabilities` (re-serialized from `Availability` rows), `resource_type`, `charge_item_definition` / `revisit_charge_item_definition` (full `ChargeItemDefinitionReadSpec` or `null`), `revisit_allowed_days`, `created_by`, `updated_by`. Also the response of `set_charge_item_definition`. `resource_type` is declared, but `perform_extra_serialization` does not set it and `Schedule` has no field with that name | -| `ScheduleRetrieveSpec` | read · detail | `ScheduleReadSpec` + `organizations: list[dict]`, `care_team: list[dict]`, filled (with `encounter_type`) by `serialize_schedule_metadata()`. The viewset's `pydantic_retrieve_model` | +| `ScheduleBaseSpec` | shared | `id`, `is_public`, `encounter_type`, `questionnaire_id`. `__exclude__ = ["resource", "facility"]`; `___extension_resource_type__ = ExtensionResource.schedule` | +| `ScheduleWriteSpec` | shared write | Adds `organizations: list[UUID4]`, `care_team: list[EncounterCareTeamMemberSpec]`, and `extensions` (through `ExtensionValidator`). `encounter_type` and `questionnaire_id` default to `MISSING`, so a field left out of the body keeps its stored value. Checks that every organization and care-team member belongs to the schedule facility | +| `ScheduleCreateSpec` | write · create | Extends `ScheduleWriteSpec` with `facility`, `name`, `valid_from`, `valid_to`, `availabilities: list[AvailabilityForScheduleSpec]`, `resource_type`, `resource_id`. Validates dates ≥ now, `valid_from ≤ valid_to`, and cross-availability non-overlap. `perform_extra_deserialization` stashes `facility`, `_resource_id`, `_resource_type`, and `availabilities` on the instance for the viewset | +| `ScheduleUpdateSpec` | write · update | Extends `ScheduleWriteSpec` with `name`, `valid_from`, `valid_to`. `perform_extra_deserialization` blocks narrowing validity that would drop allocated slots — it compares `Sum(TokenSlot.allocated)` across the old vs new range and raises if they differ | +| `ScheduleReadSpec` | read · list | All of the above plus `availabilities` (re-serialized from `Availability` rows), `resource_type`, `charge_item_definition` / `revisit_charge_item_definition` (full `ChargeItemDefinitionReadSpec` or `null`), `revisit_allowed_days`, `created_by`, `updated_by`, and `extensions` rendered through `ExtensionListRenderer` | +| `ScheduleRetrieveSpec` | read · detail | Extends the read spec with `organizations` and `care_team` (both serialized), and renders `extensions` through `ExtensionRetrieveRenderer` | | `AvailabilityBaseSpec` | shared | `id`. `__exclude__ = ["schedule"]` | | `AvailabilityForScheduleSpec` | write/read (nested in schedule) | `name`, `slot_type`, `slot_size_in_minutes`, `tokens_per_slot`, `create_tokens`, `reason`, `availability: list[AvailabilityDateTimeSpec]`. Carries the availability + slot-type validators | | `AvailabilityCreateSpec` | write · create (standalone) | Adds `schedule: UUID4`; on create, re-checks overlap against all existing availabilities of that schedule | | `AvailabilityDateTimeSpec` | nested | `day_of_week` (le=6), `start_time`, `end_time` — the shape of the `availability` JSON field | | `AvailabilityExceptionBaseSpec` | shared | `id`, `reason`, `valid_from`, `valid_to`, `start_time`, `end_time`. `__exclude__ = ["resource", "facility"]` | -| `AvailabilityExceptionWriteSpec` | write · create/upsert | Adds `facility: UUID4 \| None = None`, `resource_type`, `resource_id`. Validates dates ≥ today and `valid_from ≤ valid_to`; stashes `_resource_type`/`_resource_id`. No check that `start_time < end_time` | +| `AvailabilityExceptionWriteSpec` | write · create/upsert | Adds `facility`, `resource_type`, `resource_id`. Validates dates ≥ today and `valid_from ≤ valid_to`; stashes `_resource_type`/`_resource_id` | | `AvailabilityExceptionReadSpec` | read · list + detail | Base fields; `perform_extra_serialization` maps `id` → `external_id` | -| `ChargeItemDefinitionSetSpec` | write (action body) | `charge_item_definition: str \| None`, `re_visit_allowed_days: int`, `re_visit_charge_item_definition: str \| None` (all three keys required) — body for `POST .../set_charge_item_definition` (charge fields resolved by `slug` within the facility; `null` clears a link). Requires `can_set_charge_item_definition_in_facility` | +| `ChargeItemDefinitionSetSpec` | write (action body) | `charge_item_definition: str \| None`, `re_visit_allowed_days: int`, `re_visit_charge_item_definition: str \| None` — body for `POST .../set_charge_item_definition` (charge fields resolved by `slug` within the facility) | ### Server-maintained behaviour (viewset hooks) -- **Routes.** All are nested under `facility/{facility_external_id}/`: `schedule/` (`ScheduleViewSet`, full CRUD plus `set_charge_item_definition` and `upsert`), `schedule/{schedule_id}/availability/`, and `schedule_exceptions/` (`AvailabilityExceptionsViewSet`). - **Resource resolution.** On schedule or exception create, `get_or_create_resource(resource_type, resource_id, facility)` checks the target is in the facility (a practitioner must be a `FacilityOrganizationUser`; a location or healthcare service must belong to the facility), then gets-or-creates the `SchedulableResource`. `facility` is injected from the URL via `clean_create_data`. - **Nested availability create.** `ScheduleViewSet.perform_create` (atomic) sets `resource`, saves the schedule, then de-serializes and saves each `availability` linked to it. -- **Standalone availability.** `AvailabilityViewSet` (`schedule/{schedule_id}/availability/`) has only create and delete. Both require `can_write_schedule` on the schedule's resource. The schedule comes from the URL. -- **Authorization.** Schedule and exception writes require `can_write_schedule` on the `SchedulableResource`; reads require `can_list_schedule`. `authorize_create` calls `get_or_create_resource` before the permission check, so the `SchedulableResource` row exists even when the check fails. - **Charge items.** `revisit_allowed_days`, `charge_item_definition`, and `revisit_charge_item_definition` move only through the `set_charge_item_definition` detail action, never the create/update body. - **Locking + slot guards.** Update and destroy take a `Lock("booking:resource:")`. Deleting a schedule or availability is rejected when future allocated `TokenSlot`s exist; otherwise availabilities and slots are soft-deleted (`deleted=True`). -- **Exception slot clearing.** Creating an `AvailabilityException` soft-deletes the resource's `TokenSlot`s whose start date is within `valid_from`–`valid_to` and whose start time is within `start_time`–`end_time` (inclusive). It rejects the request if any of those slots are already allocated ("There are bookings during this exception"). The viewset has no update endpoint. -- **List requires resource.** The `Schedule` and `AvailabilityException` list endpoints require `resource_type` and `resource_id` query params and scope results to that `SchedulableResource`. They return an empty list when no `SchedulableResource` exists yet for that target. Both also filter by `user` (practitioner `external_id`) and by a `valid_from` / `valid_to` window overlap. +- **Exception slot clearing.** Creating an `AvailabilityException` soft-deletes overlapping `TokenSlot`s, but rejects the request if any are already allocated ("There are bookings during this exception"). +- **List requires resource.** The `Schedule` and `AvailabilityException` list endpoints require `resource_type` and `resource_id` query params and scope results to that `SchedulableResource`. +- **Extensions.** `extensions` is validated on write against the handlers registered for `ExtensionResource.schedule`, and rendered on read — the list form through `deserialize_extensions_list`, the detail form through `deserialize_extensions_retrieve`. An unregistered key is dropped. +- **Booking metadata.** `serialize_schedule_metadata` carries `organizations`, `care_team`, `encounter_type`, and `questionnaire_id` onto the schedule block of a [booking](../scheduling/booking.mdx) read, so a client can open the right questionnaire at check-in without a second call. ## Integration notes -- `TokenSlot` rows are not created with the schedule. `SlotViewSet.get_slots_for_day` creates them on demand for one day from the `appointment` availabilities, minus exception windows (see [Booking](../scheduling/booking.mdx)). +- Slots are computed from `Availability` at read time, not stored as rows on the schedule. - When reading a `SchedulableResource`, dispatch on `resource_type` to pick the populated relation (`user`, `location`, or `healthcare_service`) — only one is set, and you can't assume which. - A `ChargeItemDefinition` referenced by a schedule can't be deleted while the schedule exists (`PROTECT`). +- `encounter_type` and `questionnaire_id` are `MISSING`-defaulted on write. Omit the key to keep the stored value; send `null` to clear it. ## Related