Encounter
Technical reference for the Encounter module in Care EMR. For the product view, see the Encounter concept.
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.
Source:
- Model:
care/emr/models/encounter.py - Specs:
care/emr/resources/encounter/spec.py·care_team.py·constants.py·valueset.py·enum_display_names.py - Viewset:
care/emr/api/viewsets/encounter.py - Authorization:
care/security/authorization/encounter.py· permissions:care/security/permissions/encounter.py
The Django model is only the storage layer. Several fields are JSONFields whose shape the Pydantic specs set, and the specs decide which fields the API reads and writes.
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 |
Both extend EMRBaseModel. It supplies external_id, created_date, modified_date, the soft-delete flag deleted, created_by, updated_by, history and meta.
Encounter fields
In the tables below, the model type is the Django column, and the API column is what the specs read and write.
Status, type and priority
| Field | Model type | API | Notes |
|---|---|---|---|
status | CharField(100), nullable | StatusChoices, required on create and update | See Status values |
status_history | JSONField, default {} | Read only (list and retrieve) | Server-maintained. See 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 and location
| 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 |
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 |
Period and hospitalization
| Field | Model type | API | Notes |
|---|---|---|---|
period | JSONField, default {} | PeriodSpec, default {} | See PeriodSpec |
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 |
Departments, care team, tags and extensions
| 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_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 |
extensions | JSONField, default {} | dict on create and update; returned on retrieve | Checked by ExtensionValidator against the extensions registered for encounter |
Enum values
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.
Status values (StatusChoices)
| Value | Label | 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.
Class values (ClassChoices)
The class is the encounter type. The create form labels it Type of Encounter, and the facility encounter list filter labels it Encounter Class.
| Value | Label |
|---|---|
imp | Inpatient |
amb | Ambulatory |
obsenc | Observation |
emer | Emergency |
vr | Virtual |
hh | Home Health |
Priority values (EncounterPriorityChoices)
| Value | Label |
|---|---|
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 |
Admit source values (AdmitSourcesChoices)
| Value | Label |
|---|---|
hosp_trans | Transferred from other hospital |
emd | From accident/emergency department |
outp | From outpatient department |
born | Born in hospital |
gp | General Practitioner referral |
mp | Medical Practitioner/physician referral |
nursing | From nursing home |
psych | From psychiatric hospital |
rehab | From rehabilitation facility |
other | Other |
Discharge disposition values (DischargeDispositionChoices)
| Value | Label |
|---|---|
home | Home |
alt_home | Alternate home |
other_hcf | Other health care facility |
hosp | Hospice |
long | Long term care |
aadvice | Left against advice |
exp | Expired |
psy | Psychiatric hospital |
rehab | Rehabilitation |
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.
| 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.
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 |
discharge_disposition | DischargeDispositionChoices | None | See Discharge disposition values |
diet_preference | DietPreferenceChoices | None | See Diet preference values |
status_history
The field holds one key, history, a list of entries in the order the statuses were set.
| Entry key | Type | 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.
care_team
See the Care team reference for the stored and returned shapes.
Related models
EncounterOrganization
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.
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 |
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 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_historywith the initial status and the time. An update adds an entry only when the status changes. restartsets the status toin_progresswithout the update spec, so it adds nostatus_historyentry.- Encounter type:
encounter_classis set on create only. A value sent on update is not applied, and Care keeps no history of it. - The
encounter_class_historyfield was removed in Care commit3c9f3c297, together with the class in the update spec. - Create resolves
patientandfacilitybyexternal_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
tagsfrom 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: nullleaves the stored value.discharge_summary_adviceis the exception.
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.
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 |
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.
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.
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.
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.
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.
Questionnaire submission for an encounter checks "Can submit questionnaire about patient encounters" through can_submit_encounter_questionnaire_obj.
Being on the care team gives no access to the encounter or the patient. Nothing in the authorization code reads the care team.
Filters and ordering
| 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_ids. 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 |
Notes
- Reads use
EncounterListSpecandEncounterRetrieveSpec. Writes useEncounterCreateSpecandEncounterUpdateSpec. status,priorityand, on create,encounter_classare 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_cacheandtags_dataare server-maintained. - To correct a wrong encounter type, set the status to
entered_in_errorand create a new encounter. period.startandperiod.endmust 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_locationis a cached field. The bed stay records, returned aslocation_history, hold the history of its bed stays.
Related
- Concept: Encounter
- Reference: Care team
- Reference: Patient
- Reference: Booking
- Reference: Location
- Reference: Device
- Reference: Organization
- Reference: Facility
- Reference: User
- Reference: Tagging
- Reference: Value set
- Reference: Permission
- Reference: Base model
- Source (model): encounter.py on GitHub
- Source (specs): resources/encounter on GitHub
- Source (viewset): viewsets/encounter.py on GitHub