Skip to main content
Version: 3.1

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:

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​

ModelPurpose
EncounterThe encounter of one patient at one facility
EncounterOrganizationLinks 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​

FieldModel typeAPINotes
statusCharField(100), nullableStatusChoices, required on create and updateSee Status values
status_historyJSONField, default {}Read only (list and retrieve)Server-maintained. See status_history
encounter_classCharField(100), nullableClassChoices, required on create. Not in the update specThe encounter type. Fixed after creation
priorityCharField(100), nullableEncounterPriorityChoices, required on create and update
external_identifierCharField(100), nullablestr | NoneThe encounter form labels it Hospital Identifier

Subject, facility and location​

FieldModel typeAPINotes
patientFK → Patient, CASCADEUUID4, create onlyLooked up by external_id. Excluded from update
facilityFK → Facility, PROTECTUUID4, create onlyLooked up by external_id. Excluded from update
appointmentFK → TokenBooking, SET_NULL, nullableUUID4 | None, create onlyMust belong to the same patient, to a slot whose resource is in the same facility, and have no encounter yet. See Booking
current_locationFK → FacilityLocation, SET_NULL, nullableRead onlyA cached field. The location module sets it from the active bed stay. Closing the encounter does not clear it

Period and hospitalization​

FieldModel typeAPINotes
periodJSONField, default {}PeriodSpec, default {}See PeriodSpec
hospitalizationJSONField, default {}HospitalizationSpec | None, default {}All four keys are optional
discharge_summary_adviceTextField, nullablestr | NoneAn update that leaves it out, or sends null, clears it

Departments, care team, tags and extensions​

FieldModel typeAPINotes
facility_organization_cacheArrayField[int], default []Never returnedThe department set: linked departments, their ancestors and the facility's Administration department. Rebuilt on every save
care_teamJSONField, default {}Excluded from create and update. Read as a list of member and roleWritten through set_care_team_members. See Care team
care_team_usersArrayField[int], default []Never returnedInteger user ids taken from care_team on every save
tagsArrayField[int], default []Read as rendered tag configsSet by tags in the create body, set_tags and remove_tags
tags_dataJSONField, default {}Never returnedExpiry per tag. See tags_data
extensionsJSONField, default {}dict on create and update; returned on retrieveChecked 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)​

ValueLabelNotes
plannedPlanned
in_progressIn Progressrestart sets this status
on_holdOn Hold
dischargedDischargedNot closed. Counts toward the open-encounter limit
completedCompletedClosed
cancelledCancelledClosed
discontinuedDiscontinuedClosed
entered_in_errorEntered in errorClosed. The only value in ERROR_CHOICES
unknownUnknown

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.

ValueLabel
impInpatient
ambAmbulatory
obsencObservation
emerEmergency
vrVirtual
hhHome Health

Priority values (EncounterPriorityChoices)​

ValueLabel
ASAPASAP
callback_resultsCallback results
callback_for_schedulingCallback for scheduling
electiveElective
emergencyEmergency
preopPre-op
as_neededAs needed
routineRoutine
rush_reportingRush reporting
statStat
timing_criticalTiming critical
use_as_directedUse as directed
urgentUrgent

Admit source values (AdmitSourcesChoices)​

ValueLabel
hosp_transTransferred from other hospital
emdFrom accident/emergency department
outpFrom outpatient department
bornBorn in hospital
gpGeneral Practitioner referral
mpMedical Practitioner/physician referral
nursingFrom nursing home
psychFrom psychiatric hospital
rehabFrom rehabilitation facility
otherOther

Discharge disposition values (DischargeDispositionChoices)​

ValueLabel
homeHome
alt_homeAlternate home
other_hcfOther health care facility
hospHospice
longLong term care
aadviceLeft against advice
expExpired
psyPsychiatric hospital
rehabRehabilitation
snfSkilled nursing facility
othOther

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)​

ValueLabel
vegetarianVegetarian
dairy_freeDairy free
nut_freeNut free
gluten_freeGluten free
veganVegan
halalHalal
kosherKosher
noneNone

Nested JSON shapes​

PeriodSpec (period)​

Defined in resources/base.py.

KeyTypeNotes
startdatetime | NoneMust carry a time zone ("Start Date must be timezone aware")
enddatetime | NoneMust 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.

KeyTypeValues
re_admissionbool | None
admit_sourceAdmitSourcesChoices | NoneSee Admit source values
discharge_dispositionDischargeDispositionChoices | NoneSee Discharge disposition values
diet_preferenceDietPreferenceChoices | NoneSee Diet preference values

status_history​

The field holds one key, history, a list of entries in the order the statuses were set.

Entry keyTypeNotes
statusStatusChoices valueThe status that was set
moved_atstrServer 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.

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.

SpecRoleNotes
EncounterSpecBasesharedid, status (required), period, hospitalization, priority (required), external_identifier, discharge_summary_advice. No encounter_class
EncounterCreateSpecwrite · createBase fields plus patient, facility, organizations (default []), appointment (optional), encounter_class (required) and extensions
EncounterUpdateSpecwrite · updateBase fields plus extensions. No patient, facility, organizations, appointment or encounter_class
EncounterListSpecread · listBase fields plus patient (PatientListSpec), facility (FacilityBareMinimumSpec), status_history, encounter_class, created_date, modified_date, tags, current_location (FacilityLocationMinimalListSpec or null) and care_team
EncounterRetrieveSpecread · detailList fields, with patient as PatientRetrieveSpec, plus appointment (TokenBookingReadSpec), created_by, updated_by, organizations (FacilityOrganizationReadSpec list), location_history, extensions and permissions
HospitalizationSpecnestedSee HospitalizationSpec
EncounterCareTeamMemberSpecnested · writeuser_id (UUID4) and role (a coding bound to system-practitioner-role-code)
EncounterCareTeamMemberWriteSpecwrite · care teammembers: a list of EncounterCareTeamMemberSpec
EncounterOrganizationManageSpecwrite · departmentsorganization (UUID4). Body of organizations_add and organizations_remove
EncounterFacilityIdentifierWriteSpecwrite · identifieridentifier (UUID4), value (str | None), set_default (default false)
TagRequestwrite · tagstags: 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.

ConceptDisplay on Care's default terminology server (SNOMED CT International Edition 20241101)
223366009Healthcare professional
224930009Services

Server-maintained behaviour​

  • Status history: create starts status_history with the initial status and the time. An update adds an entry only when the status changes.
  • restart sets the status to in_progress without the update spec, so it adds no status_history entry.
  • Encounter type: encounter_class is set on create only. A value sent on update is not applied, and Care keeps no history of it.
  • The encounter_class_history field was removed in Care commit 3c9f3c297, together with the class in the update spec.
  • Create resolves patient and facility by external_id. Each department must belong to the encounter's facility. The viewset links the departments after the encounter is saved.
  • With no departments, the department set holds only the facility's Administration department.
  • If the appointment already has an encounter, create fails with "Encounter already has an associated booking". Otherwise Care links the appointment to the new encounter.
  • Create applies tags from the request body in the same save.
  • Under a per-facility lock, create evaluates the patient identifier defaults of the facility and rebuilds the patient's facility identifiers.
  • If the lock is busy, create fails with "Encounter creation failed, try again after a while".
  • Every update first releases linked devices and closes open bed stays. Both steps act only when the new status is closed. Then the update saves.
  • When the status becomes closed, Care frees each bed whose current encounter this is. It marks such a bed unoccupied if it was occupied and has no encounter now.
  • It also completes the encounter's open bed stays with the end time now, and ends its device links.
  • Closing does not change current_location.
  • An update applies only the fields whose value differs from the spec default. For example, external_identifier: null leaves the stored value. discharge_summary_advice is the exception.

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.

MethodPathActionBody → response
GET/api/v1/encounter/ListFilters below → EncounterListSpec items, paginated, newest first
POST/api/v1/encounter/CreateEncounterCreateSpec, optional tags → EncounterRetrieveSpec
GET/api/v1/encounter/{id}/Retrieve→ EncounterRetrieveSpec
PUT/api/v1/encounter/{id}/UpdateEncounterUpdateSpec → EncounterRetrieveSpec
POST/api/v1/encounter/{id}/restart/Restart a closed encounternone → 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 departmentEncounterOrganizationManageSpec → FacilityOrganizationReadSpec
DELETE/api/v1/encounter/{id}/organizations_remove/Unlink a departmentEncounterOrganizationManageSpec → empty object
POST/api/v1/encounter/{id}/set_care_team_members/Replace the care teamEncounterCareTeamMemberWriteSpec → empty object (the schema declares EncounterRetrieveSpec). See Care team
POST/api/v1/encounter/{id}/set_facility_identifier/Set a patient identifier for the facilityEncounterFacilityIdentifierWriteSpec → empty object
POST/api/v1/encounter/{id}/set_tags/Apply tagsTagRequest → EncounterRetrieveSpec
POST/api/v1/encounter/{id}/remove_tags/Remove tagsTagRequest → 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.

EndpointHandlerRequirement
Createcan_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_tagsper-tag checkFor 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, organizationscan_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 patientcan_view_patient_objAs above for the patient. Returns that patient's encounters in every facility. Else 403 "User cannot access patient"
List with facilityget_filtered_encountersReturns 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 neither403 "Cannot access encounters"
Update, organizations_add, organizations_remove, set_care_team_members, set_facility_identifier, set_tags, remove_tagscan_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"
restartcan_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:

PermissionDefault 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​

ParameterMeaning
facilityFacility external_id. Lists that facility's encounters, as the authorization table describes
patientPatient external_id. Lists that patient's encounters in every facility
patient_filterPatient external_id, as a plain filter
statusOne or more statuses
encounter_classEncounter type, case-insensitive exact match
priorityPriority, case-insensitive exact match
external_identifierPart of the identifier, case-insensitive
namePart of the patient's name
phone_numberPart of the patient's phone number
locationCurrent location external_id
created_date_after, created_date_beforeCreation date range. The Care frontend sends these two
livetrue keeps closed encounters only; false keeps encounters that are not closed
organizationDepartment external_id, matched in the department set. A parent department also matches encounters of its sub-departments
care_team_userUsername, matched in care_team_users
tagsComma-separated tag config external_ids. With tags_behavior any (default) or all. Unknown tags give an empty list
orderingcreated_date or modified_date. Without it, newest first

Settings​

SettingDefaultEffect
MAX_ACTIVE_ENCOUNTERS_PER_PATIENT_IN_FACILITY5Create 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_HOURS0Restart 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 EncounterListSpec and EncounterRetrieveSpec. Writes use EncounterCreateSpec and EncounterUpdateSpec.
  • status, priority and, on create, encounter_class are required and checked against their enums, although the columns are nullable.
  • A field that is not in the spec is not applied. status_history, care_team_users, facility_organization_cache and tags_data are server-maintained.
  • To correct a wrong encounter type, set the status to entered_in_error and create a new encounter.
  • period.start and period.end must carry a time zone.
  • After organizations_remove, users with roles in the removed department keep their access to the encounter until the encounter's next save.
  • current_location is a cached field. The bed stay records, returned as location_history, hold the history of its bed stays.