diff --git a/versioned_docs/version-3.0/references/clinical/condition.mdx b/versioned_docs/version-3.0/references/clinical/condition.mdx index ea3c2e50..af1f289b 100644 --- a/versioned_docs/version-3.0/references/clinical/condition.mdx +++ b/versioned_docs/version-3.0/references/clinical/condition.mdx @@ -15,6 +15,7 @@ A `Condition` records a clinical problem, diagnosis, or symptom against a patien A `Condition` lives across two layers, and the split matters when you read the code: - 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 @@ -41,7 +42,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. On write, an optional single [`Coding`](#coding-shape) bound to the body-site value set (`system-body-site-observation`, `CARE_BODY_SITE_VALUESET`). On read, a plain `Coding` or `null`. | ### Timing @@ -139,6 +140,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]` — a `Coding` checked against the body-site value set (`care/emr/resources/observation/valueset.py`, slug `system-body-site-observation`), the same value set observations use. It is optional on `ConditionSpec` and `ConditionUpdateSpec`, and defaults to `null`. The read spec 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 +151,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, and `body_site` must belong to the body-site value set when it is supplied. - `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. +- `recorded_date` exists on the model but no current spec reads or writes it — storage-only, outside the standard `Condition` API surface. ## Related models 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..e99ad32e --- /dev/null +++ b/versioned_docs/version-3.0/references/clinical/detected-issue.mdx @@ -0,0 +1,201 @@ +--- +sidebar_position: 16 +description: "A DetectedIssue records a clinical risk found against an encounter, the records that caused it, and the mitigations recorded against it." +--- + +# Detected Issue + +A `DetectedIssue` records a clinical risk found against an encounter — a drug interaction, a dose problem, an allergy conflict, or a care gap. It maps to the FHIR `DetectedIssue` resource. Each issue points at the clinical records that caused it, and carries the mitigations that clinicians record against 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) +- Resource reference registry: [`care/emr/utils/resource_reference.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/utils/resource_reference.py) +- Permissions: [`care/security/permissions/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/detected_issue.py) + +A `DetectedIssue` lives across two layers: + +- The Django model (`care/emr/models/detected_issue.py`) is storage. `status`, `category`, and `severity` are plain `CharField`s, and `code` is an opaque `JSONField`. +- The Pydantic resource specs (`care/emr/resources/detected_issue/spec.py`) are the API. They define the enums, the read and write schemas, and the rules that bind an issue to its encounter, its attached resources, and its mitigations. + +## Models + +| Model | Purpose | +| --- | --- | +| `DetectedIssue` | A clinical risk detected for a patient within an encounter | +| `DetectedIssueMitigation` | A recorded action or note that answers an issue | +| `DetectedIssueResource` | A link from an issue to a clinical record that caused it | + +All three extend [`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. + +## `DetectedIssue` fields + +| Field | Model type | Spec type | Notes | +| --- | --- | --- | --- | +| `status` | `CharField(25)` | `DetectedIssueStatusOptions` | Lifecycle state. Required on create. See [status values](#detectedissuestatusoptions-values) | +| `category` | `CharField(25)` | `DetectedIssueCategoryOptions` | The kind of risk, as a FHIR v3 `ActCode`. Required on create. See [category values](#detectedissuecategoryoptions-values) | +| `severity` | `CharField(25)` | `DetectedIssueSeverityOptions` | How serious the issue is. Required on create. See [severity values](#detectedissueseverityoptions-values) | +| `code` | `JSONField`, nullable | (not in any spec) | Exists on the model, but no current spec reads or writes it — storage only | +| `encounter` | `FK → emr.Encounter` (`PROTECT`) | `UUID4` (create only) | Encounter the issue belongs to. Required on create, then immutable. An encounter with a detected issue cannot be deleted | +| `patient` | `FK → emr.Patient` (`PROTECT`, not null) | (derived) | Subject of the issue. Set server-side from the URL, never read from the client | + +The spec base sets `__exclude__ = ["patient", "encounter", "resources"]`, so the client never maps those fields directly. + +## 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` | The issue is being drafted | +| `active` | The issue is open and needs attention | +| `inactive` | The issue no longer applies | +| `not_done` | No action was taken on the issue | +| `entered_in_error` | The issue was recorded in error | + +### `DetectedIssueSeverityOptions` values + +| Value | +| --- | +| `high` | +| `moderate` | +| `low` | + +### `DetectedIssueMitigationStatusOptions` values + +| Value | Meaning | +| --- | --- | +| `active` | The mitigation stands. Model default | +| `entered_in_error` | The mitigation was recorded in error | + +### `DetectedIssueCategoryOptions` values + +`category` holds a code from the FHIR `detectedissue-category` value set, system `http://terminology.hl7.org/CodeSystem/v3-ActCode`. The abstract grouping codes of that code system (the `notSelectable` ones, prefixed with `_`) are left out. + +| Group | Values | +| --- | --- | +| Product & interaction alerts | `FOOD`, `TPROD`, `DRG`, `NHP`, `NONRX` | +| Patient-context alerts | `OBSA`, `AGE`, `ADALRT`, `DOSEHINDA`, `DOSELINDA`, `GEALRT`, `PEALRT`, `COND`, `HGHT`, `LACT`, `PREG`, `WGHT`, `GEN`, `GEND`, `LAB` | +| Reaction, allergy & intolerance alerts | `CREACT`, `REACT`, `ALGY`, `INT`, `RREACT`, `RALG`, `RAR`, `RINT`, `PREVINEF` | +| Compliance & duplicate-therapy alerts | `COMPLY`, `DUPTHPY`, `DUPTHPCLS`, `DUPTHPGEN`, `ABUSE`, `FRAUD`, `PLYDOC`, `PLYPHRM` | +| Dosage 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 & equivalence alerts | `ALLDONE`, `FULFIL`, `NOTACTN`, `NOTEQUIV`, `NOTEQUIVGEN`, `NOTEQUIVTHER` | +| Record & preference alerts | `HISTORIC`, `PATPREF`, `PATPREFALT`, `CAREGAP`, `CODINGGAP` | + +### `DetectedIssueResourceType` values + +The kinds of record an issue can point at. Each value has a handler in the resource-reference registry that supplies the model, the read spec, and the read-authorization rule. + +| Value | Model | Read spec | Read check | +| --- | --- | --- | --- | +| `diagnostic_report` | `DiagnosticReport` | `DiagnosticReportSpecBase` | `can_read_diagnostic_report` on the linked service request; a report with no service request is never readable | +| `observation` | `Observation` | `ObservationReadSpec` | Clinical-data access on the patient, or on the encounter | +| `condition` | `Condition` | `ConditionReadSpec` | Clinical-data access on the patient, or on the encounter | +| `allergy_intolerance` | `AllergyIntolerance` | `AllergyIntoleranceReadSpec` | Clinical-data access on the patient, or on the encounter | +| `service_request` | `ServiceRequest` | `BaseServiceRequestSpec` | `can_read_service_request` | +| `specimen` | `Specimen` | `BaseSpecimenSpec` | `can_read_specimen` on the linked service request | +| `questionnaire_response` | `QuestionnaireResponse` | `QuestionnaireResponseReadSpec` | Clinical-data access; a response with no encounter falls back to `can_view_patient_questionnaire_responses` | +| `file_upload` | `FileUpload` | `FileUploadRetrieveSpec` | `file_authorizer` on the file type and its associated record | +| `immunization` | `Immunization` | `ImmunizationListSpec` | Clinical-data access on the patient, or on the encounter | +| `medication_request` | `MedicationRequest` | `MedicationRequestReadSpec` | Clinical-data access, or `can_view_as_pharmacist` on the encounter facility | + +## Related models + +```text +DetectedIssue + encounter → FK Encounter (PROTECT) + patient → FK Patient (PROTECT) + mitigation ← DetectedIssueMitigation (CASCADE, related_name "mitigation") + resources ← DetectedIssueResource (CASCADE, related_name "resources") +``` + +### `DetectedIssueMitigation` + +The action a clinician took, or the reason the issue was accepted. + +| Field | Model type | Spec type | Notes | +| --- | --- | --- | --- | +| `detected_issue` | `FK DetectedIssue` (`CASCADE`) | `UUID4` (read) | Set server-side from the URL | +| `note` | `TextField` | `str` | Required. Whitespace is stripped and the value must not be empty | +| `status` | `CharField(25)`, default `"active"` | `DetectedIssueMitigationStatusOptions` (read) | Write accepts only `entered_in_error`. See [below](#mitigations-are-append-only) | +| `entered_in_error_by` | `FK users.User` (`PROTECT`), nullable | `dict \| None` (read) | Set server-side when the status moves to `entered_in_error`. Read returns a cached `UserSpec` dict | +| `entered_in_error_at` | `DateTimeField`, nullable | `datetime \| None` (read) | Set server-side at the same time | + +### `DetectedIssueResource` + +A link from an issue to one clinical record. + +| Field | Model type | Spec type | Notes | +| --- | --- | --- | --- | +| `detected_issue` | `FK DetectedIssue` (`CASCADE`) | `UUID4` (read) | Set server-side from the URL | +| `resource_type` | `CharField(100)` | `DetectedIssueResourceType` | The kind of record. Required | +| `resource_id` | `UUIDField` | `UUID4` | The `external_id` of the record. Required | +| `metadata` | `JSONField`, default `dict` | `dict` | Free-form payload about the link. Defaults to `{}` | + +A partial `UniqueConstraint` named `unique_detected_issue_resource` covers `resource_type`, `resource_id`, and `detected_issue` where `deleted=False`. The resource columns lead, so the same index also serves the reverse lookup (which issues reference a set of records). A duplicate link is rejected with "Resource is already attached to this detected issue". + +## Resource specs (API schema) + +Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py)), except the plain `BaseModel` request and response bodies. + +| Spec | Role | Exposes / behaviour | +| --- | --- | --- | +| `DetectedIssueBaseSpec` | shared | `id`, `status`, `category`, `severity`. `__exclude__ = ["patient", "encounter", "resources"]` | +| `DetectedIssueCreateSpec` | write · create | Adds `encounter: UUID4` and `resources: list[DetectedIssueResourceCreateSpec]` (default `[]`). On create, resolves the encounter and stashes the resource list for the viewset to save | +| `DetectedIssueUpdateSpec` | write · update | `status`, `category`, `severity`, each defaulting to the `MISSING` sentinel, so an omitted field is left unchanged. Does not accept `encounter` or `resources` | +| `DetectedIssueListSpec` | read · list | Base fields plus `patient`, `encounter` (both `external_id`), `created_date`, `modified_date`, `created_by`, `updated_by` | +| `DetectedIssueRetrieveSpec` | read · detail | Extends the list spec with `resources` (`DetectedIssueResourceReadSpec[]`) and `mitigation` (`DetectedIssueMitigationReadSpec[]`) | +| `DetectedIssueMitigationCreateSpec` | write · create | `note` only (stripped, min length 1). `extra="forbid"` | +| `DetectedIssueMitigationUpdateSpec` | write · update | `status: Literal["entered_in_error"]` only. `extra="forbid"` | +| `DetectedIssueMitigationReadSpec` | read | `id`, `detected_issue`, `note`, `status`, `entered_in_error_by`, `entered_in_error_at`, audit fields | +| `DetectedIssueResourceCreateSpec` | write · create | `resource_type`, `resource_id`, `metadata` | +| `DetectedIssueResourceReadSpec` | read | Extends the create spec with `id`, `detected_issue`, and audit fields | +| `DetectedIssueResolvedResourceSpec` | read (action body) | `{ resource_type, resource }` — the response of the `resolve` action | +| `DetectedIssueResourceLookupRequest` | write (action body) | `encounter`, `resource_type`, `resource_ids` (1–100 UUIDs). `extra="forbid"` | +| `DetectedIssueResourceLookupResponse` | read (action body) | `{ results: DetectedIssueRetrieveSpec[] }` | + +### Server-maintained behaviour + +- **Patient comes from the URL.** Every endpoint is nested under a patient. `perform_create` sets `patient` from the URL, and the create call is rejected when the encounter belongs to a different patient. +- **Create is atomic.** The issue and each entry of its `resources` list are saved in one transaction, through the same validation as the standalone resource endpoint. +- **List is per encounter.** The list endpoint needs an `encounter` query parameter. Without it, the request fails with "Detected issues are listed per encounter". Results are also scoped to the patient in the URL. +- **Filters.** `status` accepts several values at once (`MultiSelectFilter`); `category` and `severity` each accept one value. Results can be ordered by `created_date` or `modified_date`. The resource endpoint filters on `resource_type`. +- **Attached records are checked twice.** On attach, the record must resolve through the registry, must belong to the issue's patient, and the caller must be able to read it. A file must also be upload-complete, not archived, and associated with the same patient, encounter, diagnostic report, service request, referral, or consent. + +### Mitigations are append-only + +A mitigation is created with a note and nothing else. The only update allowed is to set `status` to `entered_in_error`. That update takes a row lock, and when the status changes, the server also records `entered_in_error_by`, `entered_in_error_at`, and `updated_by`. A mitigation is never deleted and its note is never edited. + +## Authorization + +Detected issues are encounter-level only. Every check runs against the facility organizations of the issue's encounter, through `EncounterAccess.check_permission_in_encounter`. + +| Permission | Grants | Default roles | +| --- | --- | --- | +| `can_read_detected_issue` | Read the detected issues of an encounter | Facility Admin, Administrator, Admin, Staff, Doctor, Nurse, Volunteer, Pharmacist | +| `can_write_detected_issue` | Create and update detected issues of an encounter, with their resources and mitigations | Facility Admin, Admin, Doctor, Nurse | + +Write access is also refused when the encounter is in a completed state, so a closed encounter cannot gain new issues, resources, or mitigations. + +## API integration notes + +- Endpoints are nested under a patient: the issue list and detail, then `resources` and `mitigation` under an issue. +- `POST .../detected_issue/by_resources/` takes an encounter, one `resource_type`, and up to 100 `resource_ids`, and returns the full issues that reference any of them. Use it to show risk flags beside a list of records. +- `GET .../resources/{id}/resolve/` returns the attached record itself, serialized with that resource type's read spec, after it re-checks read access. +- `patient` is always server-derived. `encounter` is set once on create and cannot be changed afterwards. +- `code` is on the model but outside the API surface. Use `category` for the kind of risk. + +## Related + +- Reference: [Encounter](../clinical/encounter.mdx) +- Reference: [Patient](../clinical/patient) +- Reference: [Condition](../clinical/condition.mdx) +- Reference: [Allergy Intolerance](../clinical/allergy-intolerance.mdx) +- Reference: [Medication Request](../medications/medication-request.mdx) +- Base: [Base model](../foundation/base-model.mdx) +- Source: [model](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/detected_issue.py) · [spec](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/spec.py) · [constants](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/constants.py) · [viewsets](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/detected_issue.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..94e93744 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 | 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 }]`), and `extensions` rendered through `ExtensionListRenderer` | +| `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); re-renders `extensions` through `ExtensionRetrieveRenderer`; patient via `PatientRetrieveSpec` | | `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. It is rendered on both list and detail reads: list reads use each handler's list renderer, detail reads use its retrieve renderer, so an extension can return a lighter payload in a list. ## 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..17228309 100644 --- a/versioned_docs/version-3.0/references/definitions/product-knowledge.mdx +++ b/versioned_docs/version-3.0/references/definitions/product-knowledge.mdx @@ -34,6 +34,8 @@ The Django model is only the storage layer: `code`, `names`, `storage_guidelines | `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 | +| `tags` | `ArrayField[int]` | Tag IDs applied to the definition. Model default `[]`. Serialized on read via `SingleFacilityTagManager().render_tags()`; set through the tag actions, not the create/update body | +| `tags_data` | `JSONField` | Default `{}`. Platform-maintained payload behind the applied tags | ### Naming @@ -204,7 +206,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,6 +220,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). +- `tags` are applied and removed through the tag actions of the viewset (`EMRTagMixin`), under the `product_knowledge` tag resource type, never through the create or update body. The list endpoint can filter on them with the single-facility tag filter. - On read, `is_instance_level`, `slug_config`, and the serialized `category` are computed in `perform_extra_serialization` — none are stored columns. ## Methods & save behaviour diff --git a/versioned_docs/version-3.0/references/definitions/questionnaire.mdx b/versioned_docs/version-3.0/references/definitions/questionnaire.mdx index 83ceb8bb..a2ab9ab8 100644 --- a/versioned_docs/version-3.0/references/definitions/questionnaire.mdx +++ b/versioned_docs/version-3.0/references/definitions/questionnaire.mdx @@ -41,7 +41,7 @@ All extend [`EMRBaseModel`](../foundation/base-model.mdx), which supplies `exter | Field | Type | Req | Notes | | --- | --- | --- | --- | | `version` | `CharField(255)` | yes | Version label. The write spec freezes it to `"1.0"` | -| `slug` | `CharField(255)` | yes | `unique`; defaults to a generated `uuid4`. The write spec validates `SlugType`: 5–50 chars, URL-safe, and may not shadow an internal questionnaire type | +| `slug` | `CharField(255)` | yes | `unique`; defaults to a generated `uuid4`. The write spec validates `SlugType`: 5–50 chars, URL-safe, and may not shadow an internal questionnaire type. The viewset also checks the slug is free within the auth context — see [Slug uniqueness](#slug-uniqueness) | | `title` | `CharField(255)` | yes | Display title. The write spec strips it and rejects blank/whitespace | | `description` | `TextField` | no | Defaults to `""` | | `subject_type` | `CharField(255)` | yes | `SubjectType` enum — see [values](#subjecttype-values) | @@ -371,6 +371,15 @@ Saving any organization link triggers a second write to the `Questionnaire` row. ## API integration notes +### Slug uniqueness + +On create and on update, the questionnaire viewset checks the slug before it saves, so a duplicate returns a `400` validation error ("Questionnaire with this slug already exists.") instead of a database integrity error. The check: + +- Compares slugs case-insensitively, and looks only at current revisions (rows with no `latest_revision`). +- Is scoped by `auth_context`: a `facility` questionnaire is compared within its facility, a `facility_organization` one within its facility organization, and a `user` one within its facility and creator. +- Excludes the record being updated. + + - Questionnaires expose CRUD plus a submit endpoint (`/questionnaire//submit/`). Create uses `QuestionnaireSpec` (requires ≥1 `organizations`); update uses `QuestionnaireUpdateSpec`; reads use `QuestionnaireReadSpec`. - `questions` and `styling_metadata` are open `JSONField`s at the DB layer, but the API validates `questions` against the recursive [`Question`](#question-nested-shape) spec — unique `link_id`/`id`, the choice/quantity/group constraints, and value-set existence. `styling_metadata` is never validated. - `organization_cache` / `internal_organization_cache` and `QuestionnaireResponseTemplate.available_keys` are platform-maintained. Don't set them from clients; write through the through-models or `template_data`. diff --git a/versioned_docs/version-3.0/references/facility/location.mdx b/versioned_docs/version-3.0/references/facility/location.mdx index 8d980066..ee275aff 100644 --- a/versioned_docs/version-3.0/references/facility/location.mdx +++ b/versioned_docs/version-3.0/references/facility/location.mdx @@ -197,6 +197,13 @@ On update, `cached_parent_json` is cleared so it rebuilds lazily. After every `s - `get_parent_json()` — returns the cached parent chain, refreshing `cached_parent_json` (via `FacilityLocationListSpec.serialize(parent)`) once it expires (`cache_expiry_days = 15`). - `cascade_changes()` / `handle_cascade(base_location)` — a Celery task that walks every descendant and re-saves it to invalidate each node's `cached_parent_json`. It fires when a location's organizations change, so propagation is eventually consistent, not immediate. +### Delete guards + +`validate_destroy()` refuses the delete in two cases: + +- The location has children (`"Location has active children"`). +- The location has patients assigned to it (`"Location has patients assigned to it"`). The check looks for a `FacilityLocationEncounter` on the location whose status is `planned`, `active`, or `reserved`. A `completed` association does not block the delete. + ### `validate_uniqueness()` Classmethod that enforces `name` uniqueness among siblings at the same `level_cache` within the same `root_location` — or among root-level locations when there's no root. For a new instance with a `parent`, `level_cache` and `root_location` are computed from that parent before the check runs. diff --git a/versioned_docs/version-3.0/references/scheduling/schedule.mdx b/versioned_docs/version-3.0/references/scheduling/schedule.mdx index c4615bd8..8fbd8c17 100644 --- a/versioned_docs/version-3.0/references/scheduling/schedule.mdx +++ b/versioned_docs/version-3.0/references/scheduling/schedule.mdx @@ -35,6 +35,20 @@ All four extend [`EMRBaseModel`](../foundation/base-model.mdx), which supplies ` | `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, scope & extensions + +These fields are the schedule's metadata. They are carried into the encounter a booking creates, and they are returned with a booking so the front end can prepare the consultation. + +| Field | Type | Req. | Notes | +| --- | --- | --- | --- | +| `encounter_type` | `CharField(100)`, nullable | no | Encounter class to use for consultations started from this schedule. One of `ClassChoices`; see [Encounter](../clinical/encounter.mdx) | +| `questionnaire_id` | `TextField`, nullable | no | Questionnaire to open for consultations started from this schedule. A questionnaire `external_id` or slug, stored as free text and not resolved server-side | +| `organizations` | `ArrayField[int]` | no | Facility-organization IDs the schedule belongs to. Write them as `external_id`s; every one must belong to the schedule facility | +| `care_team` | `JSONField` (list) | no | Default care team, stored as `{ "user_id": int, "role": Coding }` entries. Write them as `EncounterCareTeamMemberSpec` objects; every member must belong to the schedule facility | +| `extensions` | `JSONField` | no | Default `{}`. Open extension bag for deployment-specific metadata. Validated by `ExtensionValidator` against `ExtensionResource.schedule` | + +`encounter_type`, `questionnaire_id`, `organizations`, and `care_team` use the `MISSING` sentinel on write, so a field you omit keeps its stored value. `organizations` and `care_team` come back only on retrieve, and in the schedule metadata rendered with a booking. + ### Billing links Both charge links are set only through the `set_charge_item_definition` action (see [Resource specs](#resource-specs-api-schema)) — never the create/update body. @@ -144,10 +158,12 @@ Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care | Spec | Role | Exposes / behaviour | | --- | --- | --- | -| `ScheduleBaseSpec` | shared | `id`, `is_public`. `__exclude__ = ["resource", "facility"]` | +| `ScheduleBaseSpec` | shared | `id`, `is_public`, `encounter_type`, `questionnaire_id`. `__exclude__ = ["resource", "facility"]` | +| `ScheduleWriteSpec` | shared · write | Adds `ExtensionValidator`, so write specs also accept `extensions`. Adds `organizations: list[UUID4]` and `care_team: list[EncounterCareTeamMemberSpec]`, both excluded from direct mapping and resolved in `perform_extra_deserialization`, which rejects organizations or care-team members outside the schedule facility. `encounter_type` and `questionnaire_id` default to the `MISSING` sentinel, so omitting them leaves the stored value alone | | `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` | +| `ScheduleUpdateSpec` | write · update | `name`, `valid_from`, `valid_to`, `is_public`. Both dates must include or omit timezone information together, and `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` (`FacilityOrganizationReadSpec[]`) and `care_team`, 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 | @@ -169,6 +185,8 @@ Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care ## Integration notes - Slots are computed from `Availability` at read time, not stored as rows on the schedule. +- `encounter_type` and `questionnaire_id` are defaults for the consultation, not constraints. The schedule metadata (`organizations`, `care_team`, `encounter_type`, `questionnaire_id`) is also returned with a booking, so the front end can start the encounter with the right class and form. +- `extensions` holds custom key-value data without a schema migration, validated against the `schedule` extension resource type. - 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`). diff --git a/versioned_docs/version-3.0/references/scheduling/token.mdx b/versioned_docs/version-3.0/references/scheduling/token.mdx index 66547635..91915037 100644 --- a/versioned_docs/version-3.0/references/scheduling/token.mdx +++ b/versioned_docs/version-3.0/references/scheduling/token.mdx @@ -38,7 +38,7 @@ All four extend [`EMRBaseModel`](../foundation/base-model.mdx), the shared Care | `queue` | `FK → TokenQueue` (CASCADE) | yes (server) | Taken from the URL queue, not the body | | `category` | `FK → TokenCategory` (CASCADE) | yes | Resolved from the `category` UUID on create. Must be in the same facility as the queue | | `sub_queue` | `FK → TokenSubQueue` (CASCADE) | optional | Nullable. Must match the queue's facility **and** resource | -| `number` | `IntegerField` | yes (server) | Auto-assigned: `count(tokens in queue with same category) + 1` | +| `number` | `IntegerField` | yes (server) | Auto-assigned by `Token.get_next_number(queue, category)`: one more than the highest number ever used for that queue and category. Numbers of deleted tokens are not given out again | | `status` | `CharField(255)` | yes (server) | `TokenStatusOptions` enum (below). Starts at `CREATED` | | `is_next` | `BooleanField` (default `False`) | server | Queue-progression flag; clients never write it | | `note` | `TextField` | optional | Nullable free-text note | @@ -98,6 +98,8 @@ The spec binds `status` to `TokenSubQueueStatusOptions`: `current_token` is whichever token is being served at that point. The progression actions (`set_next`, `set_next_token_to_subqueue`) keep it current server-side. +A sub-queue cannot be deleted while tokens reference it. `validate_destroy` rejects the delete with "Cannot delete a token sub-queue referenced by tokens" when any token — including a soft-deleted one — points at the sub-queue, or when `current_token` is set. + ### `TokenCategory` A reusable category scoped to a facility and resource type — "General", "Priority", and so on. @@ -146,7 +148,7 @@ What happens on write, from `perform_extra_deserialization` and the viewset: - `TokenGenerateSpec.perform_extra_deserialization` resolves the `patient`, `category`, and `sub_queue` UUIDs to model instances, returning 404 if any is missing. - `TokenUpdateSpec.perform_extra_deserialization` resolves the `sub_queue` UUID, or sets `sub_queue = None` when it's omitted — so an update can clear it. -- On create (`perform_create`), `queue` and `facility` come from the URL queue, category-vs-queue and sub-queue-vs-queue facility/resource matching is enforced, `number` is computed under a per-queue lock, and `status` is forced to `CREATED`. +- On create (`perform_create`), `queue` and `facility` come from the URL queue, category-vs-queue and sub-queue-vs-queue facility/resource matching is enforced, `number` is computed under a per-queue lock from `Token.get_next_number`, and `status` is forced to `CREATED`. - On update, changing the sub-queue clears the old sub-queue's `current_token` if it pointed at this token. A sub-queue that already has a current token can't be reassigned. - On delete (`perform_destroy`), the token is soft-deleted: `status = ENTERED_IN_ERROR`, `deleted = True`. - `TokenRetrieveSpec` embeds the booking (via `TokenBookingMinimumReadSpec`), the booking's `associated_encounter` ([Encounter](../clinical/encounter.mdx)) when present, and the resolved `resource` (practitioner `UserSpec` / `HealthcareServiceReadSpec` / `FacilityLocationListSpec`) keyed by `resource_type`. @@ -186,7 +188,7 @@ What happens on write, from `perform_extra_deserialization` and the viewset: ## Methods & save behaviour -- **Number assignment** — `Token.number` is `count(tokens with same queue + category) + 1`, computed inside a `Lock("booking:token:{queue.id}")` and an atomic transaction so two tokens can't claim the same number. +- **Number assignment** — `Token.get_next_number(queue, category)` returns `Max(number) + 1` over every token of that queue and category, including soft-deleted ones, so a number is never given out twice. It runs inside a `Lock("booking:token:{queue.id}")` and an atomic transaction, so two tokens cannot claim the same number. - **Status lifecycle** — create forces `CREATED`; `set_next` and `set_next_token_to_subqueue` set `IN_PROGRESS`; delete sets `ENTERED_IN_ERROR`. Status is a single field, with no separate history table. - **Queue progression** — custom actions maintain `current_token` (on `TokenSubQueue`) and `is_next`; clients never write them directly: - `Token` action `set_next` (`POST .../{id}/set_next`, body `{ sub_queue }`) points the sub-queue's `current_token` at this token and marks it `IN_PROGRESS`. diff --git a/versioned_docs/version-3.1/references/clinical/condition.mdx b/versioned_docs/version-3.1/references/clinical/condition.mdx index 725c081d..787782a3 100644 --- a/versioned_docs/version-3.1/references/clinical/condition.mdx +++ b/versioned_docs/version-3.1/references/clinical/condition.mdx @@ -19,7 +19,7 @@ A `Condition` row records one symptom or one diagnosis for a patient. Care serve The Django model stores the data. Its `code`, `body_site`, `onset` and `abatement` fields are JSON fields. -The Pydantic resource specs define the shape of `code`, `onset` and `abatement`. The specs also define the enums, the value set bindings, the validation and the read and write schemas. +The Pydantic resource specs define the shape of `code`, `body_site`, `onset` and `abatement`. The specs also define the enums, the value set bindings, the validation and the read and write schemas. ## Models @@ -47,7 +47,7 @@ Each table gives the storage type from the Django model and the API shape from t | 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 | +| `body_site` | `JSONField` (`default=dict`), not null | Write: `ValueSetBoundCoding`, bound to `system-body-site-observation`. Read: `Coding \| None` | Optional on create and update, and `null` when unset | ### Timing @@ -172,12 +172,12 @@ Both APIs read with `ConditionReadSpec`. | Spec class | Role | Fields and behaviour | | --- | --- | --- | -| `ConditionSpec` | Diagnosis API: create, and upsert datapoints without `id` | Required: `verification_status`, `code` (Condition value set), `encounter` (UUID4), `category`. Optional fields include `clinical_status`, `severity`, `onset`, `abatement` and `note`. Checks that the encounter exists. On create, sets `encounter` and takes `patient` from it | +| `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`, `body_site` (Body Site value set), `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` | +| `ConditionUpdateSpec` | Diagnosis API: update, and upsert datapoints with `id` | Extends `BaseConditionSpec`. Required: `verification_status`, `code` (Condition value set). Optional: `clinical_status`, `severity`, `body_site` (Body Site value set), `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 | +| `ConditionReadSpec` | Both APIs: read | `id` (the record's `external_id`), `clinical_status`, `verification_status`, `category`, `severity` (each `str`), `code` (`Coding`), `body_site` (`Coding \| None`), `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` | @@ -187,6 +187,7 @@ Both APIs read with `ConditionReadSpec`. | --- | --- | --- | --- | --- | | `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` | +| Every write spec, for `body_site` | Body Site | `CARE_BODY_SITE_VALUESET` | `system-body-site-observation` | The body-site value set that observations also use | 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. @@ -204,7 +205,7 @@ Care's frontend searches the same value sets. The symptom search uses `system-sy - `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. +- `code` must hold a code from the bound value set, on create and on update. `body_site`, when sent, must hold a code from the body-site value set. - 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. 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..ef561230 --- /dev/null +++ b/versioned_docs/version-3.1/references/clinical/detected-issue.mdx @@ -0,0 +1,201 @@ +--- +sidebar_position: 18 +description: "A DetectedIssue records a clinical risk found against an encounter, the records that caused it, and the mitigations recorded against it." +--- + +# Detected Issue + +A `DetectedIssue` records a clinical risk found against an encounter — a drug interaction, a dose problem, an allergy conflict, or a care gap. It maps to the FHIR `DetectedIssue` resource. Each issue points at the clinical records that caused it, and carries the mitigations that clinicians record against 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) +- Resource reference registry: [`care/emr/utils/resource_reference.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/utils/resource_reference.py) +- Permissions: [`care/security/permissions/detected_issue.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/detected_issue.py) + +A `DetectedIssue` lives across two layers: + +- The Django model (`care/emr/models/detected_issue.py`) is storage. `status`, `category`, and `severity` are plain `CharField`s, and `code` is an opaque `JSONField`. +- The Pydantic resource specs (`care/emr/resources/detected_issue/spec.py`) are the API. They define the enums, the read and write schemas, and the rules that bind an issue to its encounter, its attached resources, and its mitigations. + +## Models + +| Model | Purpose | +| --- | --- | +| `DetectedIssue` | A clinical risk detected for a patient within an encounter | +| `DetectedIssueMitigation` | A recorded action or note that answers an issue | +| `DetectedIssueResource` | A link from an issue to a clinical record that caused it | + +All three extend [`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. + +## `DetectedIssue` fields + +| Field | Model type | Spec type | Notes | +| --- | --- | --- | --- | +| `status` | `CharField(25)` | `DetectedIssueStatusOptions` | Lifecycle state. Required on create. See [status values](#detectedissuestatusoptions-values) | +| `category` | `CharField(25)` | `DetectedIssueCategoryOptions` | The kind of risk, as a FHIR v3 `ActCode`. Required on create. See [category values](#detectedissuecategoryoptions-values) | +| `severity` | `CharField(25)` | `DetectedIssueSeverityOptions` | How serious the issue is. Required on create. See [severity values](#detectedissueseverityoptions-values) | +| `code` | `JSONField`, nullable | (not in any spec) | Exists on the model, but no current spec reads or writes it — storage only | +| `encounter` | `FK → emr.Encounter` (`PROTECT`) | `UUID4` (create only) | Encounter the issue belongs to. Required on create, then immutable. An encounter with a detected issue cannot be deleted | +| `patient` | `FK → emr.Patient` (`PROTECT`, not null) | (derived) | Subject of the issue. Set server-side from the URL, never read from the client | + +The spec base sets `__exclude__ = ["patient", "encounter", "resources"]`, so the client never maps those fields directly. + +## 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` | The issue is being drafted | +| `active` | The issue is open and needs attention | +| `inactive` | The issue no longer applies | +| `not_done` | No action was taken on the issue | +| `entered_in_error` | The issue was recorded in error | + +### `DetectedIssueSeverityOptions` values + +| Value | +| --- | +| `high` | +| `moderate` | +| `low` | + +### `DetectedIssueMitigationStatusOptions` values + +| Value | Meaning | +| --- | --- | +| `active` | The mitigation stands. Model default | +| `entered_in_error` | The mitigation was recorded in error | + +### `DetectedIssueCategoryOptions` values + +`category` holds a code from the FHIR `detectedissue-category` value set, system `http://terminology.hl7.org/CodeSystem/v3-ActCode`. The abstract grouping codes of that code system (the `notSelectable` ones, prefixed with `_`) are left out. + +| Group | Values | +| --- | --- | +| Product & interaction alerts | `FOOD`, `TPROD`, `DRG`, `NHP`, `NONRX` | +| Patient-context alerts | `OBSA`, `AGE`, `ADALRT`, `DOSEHINDA`, `DOSELINDA`, `GEALRT`, `PEALRT`, `COND`, `HGHT`, `LACT`, `PREG`, `WGHT`, `GEN`, `GEND`, `LAB` | +| Reaction, allergy & intolerance alerts | `CREACT`, `REACT`, `ALGY`, `INT`, `RREACT`, `RALG`, `RAR`, `RINT`, `PREVINEF` | +| Compliance & duplicate-therapy alerts | `COMPLY`, `DUPTHPY`, `DUPTHPCLS`, `DUPTHPGEN`, `ABUSE`, `FRAUD`, `PLYDOC`, `PLYPHRM` | +| Dosage 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 & equivalence alerts | `ALLDONE`, `FULFIL`, `NOTACTN`, `NOTEQUIV`, `NOTEQUIVGEN`, `NOTEQUIVTHER` | +| Record & preference alerts | `HISTORIC`, `PATPREF`, `PATPREFALT`, `CAREGAP`, `CODINGGAP` | + +### `DetectedIssueResourceType` values + +The kinds of record an issue can point at. Each value has a handler in the resource-reference registry that supplies the model, the read spec, and the read-authorization rule. + +| Value | Model | Read spec | Read check | +| --- | --- | --- | --- | +| `diagnostic_report` | `DiagnosticReport` | `DiagnosticReportSpecBase` | `can_read_diagnostic_report` on the linked service request; a report with no service request is never readable | +| `observation` | `Observation` | `ObservationReadSpec` | Clinical-data access on the patient, or on the encounter | +| `condition` | `Condition` | `ConditionReadSpec` | Clinical-data access on the patient, or on the encounter | +| `allergy_intolerance` | `AllergyIntolerance` | `AllergyIntoleranceReadSpec` | Clinical-data access on the patient, or on the encounter | +| `service_request` | `ServiceRequest` | `BaseServiceRequestSpec` | `can_read_service_request` | +| `specimen` | `Specimen` | `BaseSpecimenSpec` | `can_read_specimen` on the linked service request | +| `questionnaire_response` | `QuestionnaireResponse` | `QuestionnaireResponseReadSpec` | Clinical-data access; a response with no encounter falls back to `can_view_patient_questionnaire_responses` | +| `file_upload` | `FileUpload` | `FileUploadRetrieveSpec` | `file_authorizer` on the file type and its associated record | +| `immunization` | `Immunization` | `ImmunizationListSpec` | Clinical-data access on the patient, or on the encounter | +| `medication_request` | `MedicationRequest` | `MedicationRequestReadSpec` | Clinical-data access, or `can_view_as_pharmacist` on the encounter facility | + +## Related models + +```text +DetectedIssue + encounter → FK Encounter (PROTECT) + patient → FK Patient (PROTECT) + mitigation ← DetectedIssueMitigation (CASCADE, related_name "mitigation") + resources ← DetectedIssueResource (CASCADE, related_name "resources") +``` + +### `DetectedIssueMitigation` + +The action a clinician took, or the reason the issue was accepted. + +| Field | Model type | Spec type | Notes | +| --- | --- | --- | --- | +| `detected_issue` | `FK DetectedIssue` (`CASCADE`) | `UUID4` (read) | Set server-side from the URL | +| `note` | `TextField` | `str` | Required. Whitespace is stripped and the value must not be empty | +| `status` | `CharField(25)`, default `"active"` | `DetectedIssueMitigationStatusOptions` (read) | Write accepts only `entered_in_error`. See [below](#mitigations-are-append-only) | +| `entered_in_error_by` | `FK users.User` (`PROTECT`), nullable | `dict \| None` (read) | Set server-side when the status moves to `entered_in_error`. Read returns a cached `UserSpec` dict | +| `entered_in_error_at` | `DateTimeField`, nullable | `datetime \| None` (read) | Set server-side at the same time | + +### `DetectedIssueResource` + +A link from an issue to one clinical record. + +| Field | Model type | Spec type | Notes | +| --- | --- | --- | --- | +| `detected_issue` | `FK DetectedIssue` (`CASCADE`) | `UUID4` (read) | Set server-side from the URL | +| `resource_type` | `CharField(100)` | `DetectedIssueResourceType` | The kind of record. Required | +| `resource_id` | `UUIDField` | `UUID4` | The `external_id` of the record. Required | +| `metadata` | `JSONField`, default `dict` | `dict` | Free-form payload about the link. Defaults to `{}` | + +A partial `UniqueConstraint` named `unique_detected_issue_resource` covers `resource_type`, `resource_id`, and `detected_issue` where `deleted=False`. The resource columns lead, so the same index also serves the reverse lookup (which issues reference a set of records). A duplicate link is rejected with "Resource is already attached to this detected issue". + +## Resource specs (API schema) + +Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py)), except the plain `BaseModel` request and response bodies. + +| Spec | Role | Exposes / behaviour | +| --- | --- | --- | +| `DetectedIssueBaseSpec` | shared | `id`, `status`, `category`, `severity`. `__exclude__ = ["patient", "encounter", "resources"]` | +| `DetectedIssueCreateSpec` | write · create | Adds `encounter: UUID4` and `resources: list[DetectedIssueResourceCreateSpec]` (default `[]`). On create, resolves the encounter and stashes the resource list for the viewset to save | +| `DetectedIssueUpdateSpec` | write · update | `status`, `category`, `severity`, each defaulting to the `MISSING` sentinel, so an omitted field is left unchanged. Does not accept `encounter` or `resources` | +| `DetectedIssueListSpec` | read · list | Base fields plus `patient`, `encounter` (both `external_id`), `created_date`, `modified_date`, `created_by`, `updated_by` | +| `DetectedIssueRetrieveSpec` | read · detail | Extends the list spec with `resources` (`DetectedIssueResourceReadSpec[]`) and `mitigation` (`DetectedIssueMitigationReadSpec[]`) | +| `DetectedIssueMitigationCreateSpec` | write · create | `note` only (stripped, min length 1). `extra="forbid"` | +| `DetectedIssueMitigationUpdateSpec` | write · update | `status: Literal["entered_in_error"]` only. `extra="forbid"` | +| `DetectedIssueMitigationReadSpec` | read | `id`, `detected_issue`, `note`, `status`, `entered_in_error_by`, `entered_in_error_at`, audit fields | +| `DetectedIssueResourceCreateSpec` | write · create | `resource_type`, `resource_id`, `metadata` | +| `DetectedIssueResourceReadSpec` | read | Extends the create spec with `id`, `detected_issue`, and audit fields | +| `DetectedIssueResolvedResourceSpec` | read (action body) | `{ resource_type, resource }` — the response of the `resolve` action | +| `DetectedIssueResourceLookupRequest` | write (action body) | `encounter`, `resource_type`, `resource_ids` (1–100 UUIDs). `extra="forbid"` | +| `DetectedIssueResourceLookupResponse` | read (action body) | `{ results: DetectedIssueRetrieveSpec[] }` | + +### Server-maintained behaviour + +- **Patient comes from the URL.** Every endpoint is nested under a patient. `perform_create` sets `patient` from the URL, and the create call is rejected when the encounter belongs to a different patient. +- **Create is atomic.** The issue and each entry of its `resources` list are saved in one transaction, through the same validation as the standalone resource endpoint. +- **List is per encounter.** The list endpoint needs an `encounter` query parameter. Without it, the request fails with "Detected issues are listed per encounter". Results are also scoped to the patient in the URL. +- **Filters.** `status` accepts several values at once (`MultiSelectFilter`); `category` and `severity` each accept one value. Results can be ordered by `created_date` or `modified_date`. The resource endpoint filters on `resource_type`. +- **Attached records are checked twice.** On attach, the record must resolve through the registry, must belong to the issue's patient, and the caller must be able to read it. A file must also be upload-complete, not archived, and associated with the same patient, encounter, diagnostic report, service request, referral, or consent. + +### Mitigations are append-only + +A mitigation is created with a note and nothing else. The only update allowed is to set `status` to `entered_in_error`. That update takes a row lock, and when the status changes, the server also records `entered_in_error_by`, `entered_in_error_at`, and `updated_by`. A mitigation is never deleted and its note is never edited. + +## Authorization + +Detected issues are encounter-level only. Every check runs against the facility organizations of the issue's encounter, through `EncounterAccess.check_permission_in_encounter`. + +| Permission | Grants | Default roles | +| --- | --- | --- | +| `can_read_detected_issue` | Read the detected issues of an encounter | Facility Admin, Administrator, Admin, Staff, Doctor, Nurse, Volunteer, Pharmacist | +| `can_write_detected_issue` | Create and update detected issues of an encounter, with their resources and mitigations | Facility Admin, Admin, Doctor, Nurse | + +Write access is also refused when the encounter is in a completed state, so a closed encounter cannot gain new issues, resources, or mitigations. + +## API integration notes + +- Endpoints are nested under a patient: the issue list and detail, then `resources` and `mitigation` under an issue. +- `POST .../detected_issue/by_resources/` takes an encounter, one `resource_type`, and up to 100 `resource_ids`, and returns the full issues that reference any of them. Use it to show risk flags beside a list of records. +- `GET .../resources/{id}/resolve/` returns the attached record itself, serialized with that resource type's read spec, after it re-checks read access. +- `patient` is always server-derived. `encounter` is set once on create and cannot be changed afterwards. +- `code` is on the model but outside the API surface. Use `category` for the kind of risk. + +## Related + +- Reference: [Encounter](../clinical/encounter.mdx) +- Reference: [Patient](../clinical/patient) +- Reference: [Condition](../clinical/condition.mdx) +- Reference: [Allergy Intolerance](../clinical/allergy-intolerance.mdx) +- Reference: [Medication Request](../medications/medication-request.mdx) +- Base: [Base model](../foundation/base-model.mdx) +- Source: [model](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/detected_issue.py) · [spec](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/spec.py) · [constants](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/detected_issue/constants.py) · [viewsets](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/detected_issue.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..9d782e59 100644 --- a/versioned_docs/version-3.1/references/clinical/encounter.mdx +++ b/versioned_docs/version-3.1/references/clinical/encounter.mdx @@ -67,7 +67,7 @@ In the tables below, the model type is the Django column, and the API column is | `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` | +| `extensions` | `JSONField`, default `{}` | `dict` on create and update; returned on list and on retrieve | Checked by `ExtensionValidator` against the extensions registered for `encounter`. List reads use each handler's list renderer, retrieve reads use its retrieve renderer | ## Enum values @@ -235,8 +235,8 @@ Bed stays are `FacilityLocationEncounter` records in the location module. The re | `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` | +| `EncounterListSpec` | read · list | Base fields plus `patient` (`PatientListSpec`), `facility` (`FacilityBareMinimumSpec`), `status_history`, `encounter_class`, `created_date`, `modified_date`, `tags`, `current_location` (`FacilityLocationMinimalListSpec` or `null`), `care_team` and `extensions` rendered through `ExtensionListRenderer` | +| `EncounterRetrieveSpec` | read · detail | List fields, with `patient` as `PatientRetrieveSpec`, plus `appointment` (`TokenBookingReadSpec`), `created_by`, `updated_by`, `organizations` (`FacilityOrganizationReadSpec` list), `location_history`, `permissions`, and `extensions` re-rendered through `ExtensionRetrieveRenderer` | | `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` | 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..4b8ec167 100644 --- a/versioned_docs/version-3.1/references/definitions/product-knowledge.mdx +++ b/versioned_docs/version-3.1/references/definitions/product-knowledge.mdx @@ -42,6 +42,8 @@ The Django model is only the storage layer: `code`, `names`, `storage_guidelines | `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 | +| `tags` | `ArrayField[int]`, default `[]` | Tag IDs applied to the record. Rendered on read by `SingleFacilityTagManager`; set through the tag actions, not the create or update body | +| `tags_data` | `JSONField`, default `{}` | Platform-maintained payload behind the applied tags. In no spec | ### Naming @@ -224,7 +226,7 @@ Every spec builds on `EMRResource` (`care/emr/resources/base.py`). | `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` | +| `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), `slug`, and `tags` rendered by `SingleFacilityTagManager` | ### Validation & bound value sets @@ -273,6 +275,8 @@ The API is registered at `/api/v1/product_knowledge/`, not nested under a facili | `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` | +| `POST /api/v1/product_knowledge//set_tags/` | tags | Applies tags. The viewset uses `EMRTagMixin` with the `product_knowledge` tag resource type | +| `POST /api/v1/product_knowledge//remove_tags/` | tags | Removes tags | There is no delete endpoint. The UI's "Delete" action sends a `PUT` that sets `status` to `retired`. @@ -286,6 +290,7 @@ There is no delete endpoint. The UI's "Delete" action sends a `PUT` that sets `s | `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` | +| `tags` | Single-facility tag filter. Narrows the list to records carrying the given tags. See [Tag config](../platform/tag-config.mdx) | | `ordering` | `created_date` or `modified_date` | ### Scoping and authorization diff --git a/versioned_docs/version-3.1/references/facility/location.mdx b/versioned_docs/version-3.1/references/facility/location.mdx index 3c37ab79..21533384 100644 --- a/versioned_docs/version-3.1/references/facility/location.mdx +++ b/versioned_docs/version-3.1/references/facility/location.mdx @@ -290,7 +290,7 @@ The Pydantic specs in `care/emr/resources/location/spec.py` define the request/r - `parent`, `organizations`, and `mode` are settable only at creation (`FacilityLocationWriteSpec`). Updates go through `FacilityLocationUpdateSpec`, which omits all three. - For fields you can't write, see [Server-maintained behaviour](#server-maintained-behaviour). - Create checks: the parent must be in the same facility (`Parent Incompatible with Location`), must not be an `instance`, and must have `level_cache` below `LOCATION_MAX_DEPTH` (default 10). A facility holds at most `MAX_LOCATION_IN_FACILITY` (default 1000) non-deleted locations. -- Delete is a soft delete. It fails with `Location has active children` while the location has non-deleted children. +- Delete is a soft delete. It fails with `Location has active children` while the location has non-deleted children, and with `Location has patients assigned to it` while a `FacilityLocationEncounter` on the location has the status `planned`, `active`, or `reserved`. A `completed` association does not block it. - Organizations: `GET .../organizations/` lists the linked organizations. `POST .../organizations_add/` and `POST .../organizations_remove/` take `{ organization: uuid }`. Both need `can_update_facility_location_obj` on the location and `can_manage_facility_organization_obj` on an organization of the same facility. Remove hard-deletes the link row, then re-saves the location and runs `cascade_changes()`. - Tags: the viewset uses `EMRTagMixin` with `resource_type = location`. The create body can carry `tags: [{ tag, expiry_offset? }]`, and `POST .../set_tags/` and `POST .../remove_tags/` change them later. A tag must have `resource` `location` and belong to this facility or to the instance. `?tags=,` with `tags_behavior=any` (default) or `all` filters the list. See [Tag config](../platform/tag-config.mdx). - List filters: `parent` (UUID; an empty `?parent=` returns top-level locations), `name` (contains), `mode`, `form`, `operational_status`, `status` (case-insensitive exact), `available` (no current encounter), `has_beds`, `has_sub_locations`, and `mine` (locations linked to the user's organizations). Ordering: `sort_index`. diff --git a/versioned_docs/version-3.1/references/scheduling/schedule.mdx b/versioned_docs/version-3.1/references/scheduling/schedule.mdx index 5184ede1..4835384b 100644 --- a/versioned_docs/version-3.1/references/scheduling/schedule.mdx +++ b/versioned_docs/version-3.1/references/scheduling/schedule.mdx @@ -45,8 +45,10 @@ The server stores and returns these fields and does not act on them. care_fe use | `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` | +| `questionnaire_id` | `TextField`, nullable | no | Questionnaire to open for a consultation on this schedule. Free text (an `external_id` or a slug); the server does not resolve or check it | +| `extensions` | `JSONField`, default `{}` | no | Open extension bag for deployment-specific data. `ExtensionValidator` checks it against the `schedule` extension resource type | -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. +On create and update, the server writes `organizations` and `care_team` only when the request includes them. It writes `encounter_type` and `questionnaire_id` only when the request includes them; `null` clears either one. ### Billing links @@ -157,12 +159,12 @@ 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)) | +| `ScheduleBaseSpec` | shared | `id`, `is_public`, `encounter_type: ClassChoices \| None = None`, `questionnaire_id: str \| None = None`. `__exclude__ = ["resource", "facility"]` | +| `ScheduleWriteSpec` | write · shared | Base + `ExtensionValidator` (so writes take `extensions`) + `organizations: list[UUID4] = []`, `care_team: list[EncounterCareTeamMemberSpec] = []`, `encounter_type: ClassChoices \| None \| MISSING = MISSING`, `questionnaire_id: str \| 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` | +| `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`, and `extensions` rendered through `ExtensionListRenderer`. 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` and `questionnaire_id`) by `serialize_schedule_metadata()`, and `extensions` re-rendered through `ExtensionRetrieveRenderer`. The viewset's `pydantic_retrieve_model` | | `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 | diff --git a/versioned_docs/version-3.1/references/scheduling/token.mdx b/versioned_docs/version-3.1/references/scheduling/token.mdx index fc2c96eb..ed5bcc2f 100644 --- a/versioned_docs/version-3.1/references/scheduling/token.mdx +++ b/versioned_docs/version-3.1/references/scheduling/token.mdx @@ -38,7 +38,7 @@ All four extend [`EMRBaseModel`](../foundation/base-model.mdx), the shared Care | `queue` | `FK → TokenQueue` (CASCADE) | yes (server) | Taken from the URL queue, not the body | | `category` | `FK → TokenCategory` (CASCADE) | yes | Resolved from the `category` UUID on create. Must be in the same facility as the queue | | `sub_queue` | `FK → TokenSubQueue` (CASCADE) | optional | Nullable. Must match the queue's facility **and** resource | -| `number` | `IntegerField` | yes (server) | Auto-assigned: `count(tokens in queue with same category) + 1` | +| `number` | `IntegerField` | yes (server) | Auto-assigned by `Token.get_next_number(queue, category)`: one more than the highest number ever used for that queue and category. Numbers of deleted tokens are not given out again | | `status` | `CharField(255)` | yes (server) | `TokenStatusOptions` enum (below). Starts at `CREATED` | | `is_next` | `BooleanField` (default `False`) | server | Queue-progression flag; clients never write it | | `note` | `TextField` | optional | Nullable free-text note | @@ -98,6 +98,8 @@ The spec binds `status` to `TokenSubQueueStatusOptions`: `current_token` is whichever token is being served at that point. The progression actions (`set_next`, `set_next_token_to_subqueue`) keep it current server-side. +A sub-queue cannot be deleted while tokens reference it. `validate_destroy` rejects the delete with "Cannot delete a token sub-queue referenced by tokens" when any token — including a soft-deleted one — points at the sub-queue, or when `current_token` is set. + ### `TokenCategory` A reusable category scoped to a facility and resource type — "General", "Priority", and so on. @@ -146,7 +148,7 @@ What happens on write, from `perform_extra_deserialization` and the viewset: - `TokenGenerateSpec.perform_extra_deserialization` resolves the `patient`, `category`, and `sub_queue` UUIDs to model instances, returning 404 if any is missing. - `TokenUpdateSpec.perform_extra_deserialization` resolves the `sub_queue` UUID, or sets `sub_queue = None` when it's omitted — so an update can clear it. -- On create (`perform_create`), `queue` and `facility` come from the URL queue, category-vs-queue and sub-queue-vs-queue facility/resource matching is enforced, `number` is computed under a per-queue lock, and `status` is forced to `CREATED`. +- On create (`perform_create`), `queue` and `facility` come from the URL queue, category-vs-queue and sub-queue-vs-queue facility/resource matching is enforced, `number` is computed under a per-queue lock from `Token.get_next_number`, and `status` is forced to `CREATED`. - On update, changing the sub-queue clears the old sub-queue's `current_token` if it pointed at this token. A sub-queue that already has a current token can't be reassigned. - On delete (`perform_destroy`), the token is soft-deleted: `status = ENTERED_IN_ERROR`, `deleted = True`. - `TokenRetrieveSpec` embeds the booking (via `TokenBookingMinimumReadSpec`), the booking's `associated_encounter` ([Encounter](../clinical/encounter.mdx)) when present, and the resolved `resource` (practitioner `UserSpec` / `HealthcareServiceReadSpec` / `FacilityLocationListSpec`) keyed by `resource_type`. @@ -186,7 +188,7 @@ What happens on write, from `perform_extra_deserialization` and the viewset: ## Methods & save behaviour -- **Number assignment** — `Token.number` is `count(tokens with same queue + category) + 1`, computed inside a `Lock("booking:token:{queue.id}")` and an atomic transaction so two tokens can't claim the same number. +- **Number assignment** — `Token.get_next_number(queue, category)` returns `Max(number) + 1` over every token of that queue and category, including soft-deleted ones, so a number is never given out twice. It runs inside a `Lock("booking:token:{queue.id}")` and an atomic transaction, so two tokens cannot claim the same number. - **Status lifecycle** — create forces `CREATED`; `set_next` and `set_next_token_to_subqueue` set `IN_PROGRESS`; delete sets `ENTERED_IN_ERROR`. Status is a single field, with no separate history table. - **Queue progression** — custom actions maintain `current_token` (on `TokenSubQueue`) and `is_next`; clients never write them directly: - `Token` action `set_next` (`POST .../{id}/set_next`, body `{ sub_queue }`) points the sub-queue's `current_token` at this token and marks it `IN_PROGRESS`.