Skip to main content
Version: 3.1

Procedure

Technical reference for the Procedure module in Care EMR. For what a procedure is, see the Procedure concept.

A Procedure row records one procedure for a patient. Every row belongs to one encounter, and the API serves procedures under the patient.

Source:

The Django model stores the data. Six of its own fields are JSON fields, and the Pydantic resource specs define their shape. The specs also define the enums, the value set bindings, the validation and the read and write schemas.

Models​

ModelPurpose
ProcedureOne procedure recorded for a patient, against an encounter

Procedure extends EMRBaseModel. From it, the model inherits external_id, created_date, modified_date, deleted (soft delete), created_by, updated_by, history and meta. The model file defines no other class.

Procedure fields​

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

Context​

FieldStorage typeAPI shapeNotes
patientFK → emr.Patient (CASCADE), requiredExcluded from the specsSet on create from the encounter's patient. An update drops patient from the request
encounterFK → emr.Encounter (CASCADE), requiredUUID4 on create; the encounter's external_id in single-record responses, not in the listRequired on create. Must exist, else 400 "Encounter not found". Must belong to the patient in the URL. An update ignores it, so a procedure never moves to another encounter

Status and outcome​

FieldStorage typeAPI shapeNotes
statusCharField(100)ProcedureStatusRequired on create, optional on update
status_reasonJSONField, nullableCoding bound to system-procedure-status-reason, optionalNo rule ties it to status. On update, null clears it
outcomeCharField(32), nullableProcedureOutcome, optionalNo rule ties it to status. On update, null clears it

Coded concepts​

FieldStorage typeAPI shapeNotes
codeJSONField (default=dict)Coding bound to system-procedure-codeRequired on create, optional on update. One Coding, not a list. The name list filter searches its display
categoryJSONField (default=list)List of Coding bound to system-procedure-categoryOptional. Default is an empty list
body_siteJSONField (default=list)List of Coding bound to system-body-siteOptional. Default is an empty list
reasonJSONField (default=list)List of Coding bound to system-procedure-reasonOptional. Default is an empty list

Timing​

FieldStorage typeAPI shapeNotes
occurrenceJSONField (default=dict)ProcedureOccurrenceSpecOptional on create. Default is an empty occurrence. Shape below
recorded_dateDateTimeField, nullableAwareDatetime | None (write), datetime | None (read)Optional. If a create leaves it empty, the server sets it to the time of saving. On update, null clears it. A list ordering field

Provenance and note​

FieldStorage typeAPI shapeNotes
is_primary_sourceBooleanField (default=False)bool, read onlyA create always saves False. No write spec accepts it, so an update keeps the stored value
noteTextField, nullablestr | NoneOptional. On update, null clears it

Inherited fields​

FieldStorage typeAPI shapeNotes
external_idUUIDField, uniqueReturned as idPath key for retrieve, update and delete
created_dateDateTimeField, set on first savedatetime (read)A list ordering field
modified_dateDateTimeField, set on every savedatetime (read)A list ordering field
deletedBooleanField (default=False)Not exposedDelete sets it to True. The default manager hides deleted rows
created_byFK → users.User (SET_NULL), nullabledict | None, not in the list responseSet on create to the requesting user. Returned as a cached UserSpec
updated_byFK → users.User (SET_NULL), nullabledict | None, not in the list responseSet on create and on every update. Returned as a cached UserSpec
historyJSONField (default=dict)Not exposedThe update path does not write it
metaJSONField (default=dict)Not returned, not writableResponses leave out meta. Care discards a meta sent in a request

Enum values​

ProcedureStatus values​

status accepts only these five values. A create with a workflow status such as preparation, in_progress, on_hold or planned fails with 400.

Value
completed
not_done
stopped
entered_in_error
unknown

A create accepts every value, entered_in_error included. The update path has no status-transition rule, so it accepts any value, also on an entered_in_error record.

ProcedureOutcome values​

Value
successful
unsuccessful
partially_successful

Nested JSON shapes​

occurrence (ProcedureOccurrenceSpec)​

occurrence holds at most one of three forms. An empty object is valid. The spec refuses keys that it does not declare.

KeyTypeDefaultValidation
occurrence_datetimeAwareDatetime | NoneNoneNot in the future
occurrence_periodPeriodSpec | NoneNoneNeither start nor end in the future
occurrence_stringstr | None, min_length=1NoneAn empty string fails the min_length check. A whitespace-only string fails with "Occurrence description cannot be blank"

Two or more forms fail with "Only one occurrence type can be supplied". A date in the future fails with "Procedure occurrence cannot be in the future".

occurrence_period (PeriodSpec)​

KeyTypeDefaultValidation
startdatetime | NoneNoneMust carry a time zone: "Start Date must be timezone aware"
enddatetime | NoneNoneMust carry a time zone: "End Date must be timezone aware"

start cannot be after end: "Start Date cannot be greater than End Date".

Coding​

code, status_reason and each item of category, body_site and reason is a Coding. Coding refuses keys that it does not declare.

KeyTypeRequired
systemstr | NoneNo
versionstr | NoneNo
codestrYes
displaystr | NoneNo

On write, each coded field is a ValueSetBoundCoding. Care parses the input as a Coding and checks it against the bound value set. On read, the specs use a plain Coding and run no value set check.

Procedure has two foreign keys to clinical records, plus the two audit links from the base model.

FieldTargetOn delete
patientemr.PatientCASCADE
encounteremr.EncounterCASCADE
created_byusers.UserSET_NULL
updated_byusers.UserSET_NULL

Procedure has no link to a facility, a service request, an activity definition or a questionnaire response. A service request, by contrast, belongs to a facility and can link to an activity definition.

Each create and update writes a questionnaire response that names the procedure's id inside structured_responses. This link is a value in JSON, not a foreign key.

Resource specs (API schema)​

ProcedureCreateSpec, ProcedureUpdateSpec and ProcedureReadSpec extend BaseProcedureSpec, which extends EMRResource. ProcedureRetrieveSpec extends ProcedureReadSpec.

BaseProcedureSpec sets __model__ = Procedure and __exclude__ = ["patient", "encounter"], and declares id: UUID4 | None. These specs also inherit meta from EMRResource, but Care discards a meta sent in a request and leaves it out of responses.

The nested ProcedureOccurrenceSpec and PeriodSpec extend pydantic's BaseModel, not EMRResource.

EMRResource.de_serialize copies only the model columns that are not excluded and are not id or external_id. The create spec's hook sets patient and encounter. The update spec has no hook, so an update keeps the stored values.

Spec classRoleFields and behaviour
BaseProcedureSpecShared baseid
ProcedureCreateSpecWrite: create (POST, and upsert datapoints without id)Required: encounter (UUID4), status, code. Optional: status_reason, category, occurrence, recorded_date, body_site, reason, outcome, note. On deserialization, sets encounter, patient and is_primary_source = False
ProcedureUpdateSpecWrite: update (PUT, PATCH, and upsert datapoints with id)The same fields without encounter, each optional (MISSING default). An omitted field keeps its value. Only status_reason, recorded_date, outcome and note accept null, which clears them. null for any other field fails with 400. Send [] to empty a list. Same value set bindings as create
ProcedureReadSpecRead: listid, status, status_reason, category, code, occurrence, recorded_date, is_primary_source, body_site, reason, outcome, note, created_date, modified_date. Coded fields as plain Coding
ProcedureRetrieveSpecRead: retrieve, and the response of create, update and each successful upsert datapointAll of ProcedureReadSpec, plus encounter (UUID4), created_by and updated_by
ProcedureOccurrenceSpecNested: shape of occurrenceoccurrence_datetime, occurrence_period, occurrence_string; at most one
PeriodSpecNested: shape of occurrence_periodstart, end

The list returns ProcedureReadSpec, which has no encounter, created_by or updated_by. Retrieve, create and update return ProcedureRetrieveSpec, which adds those three fields.

Bound value sets​

The write specs bind the coded fields to these value sets. All five are SNOMED CT (http://snomed.info/sct) value sets with status active.

FieldValue setConstantSlugDefault composition
codeProcedureCARE_PROCEDURE_CODE_VALUESETsystem-procedure-codeSNOMED CT concepts is-a 71388002
categoryProcedure CategoryCARE_PROCEDURE_CATEGORY_VALUESETsystem-procedure-categorySeven listed SNOMED CT concepts (table below)
reasonProcedure ReasonCARE_PROCEDURE_REASON_VALUESETsystem-procedure-reasonSNOMED CT concepts is-a 404684003, plus concepts is-a 71388002
status_reasonProcedure Status ReasonCARE_PROCEDURE_STATUS_REASON_VALUESETsystem-procedure-status-reasonSNOMED CT concepts is-a any of eight codes (below), plus the concept 410536001 (Contraindicated)
body_siteBody SiteCARE_BODY_SITE_VALUESETsystem-body-siteSNOMED CT concepts is-a 91723000. Defined in care/emr/resources/medication/valueset/body_site.py

The default category concepts:

CodeDisplay
24642003Psychiatry procedure or service
409063005Counseling
409073007Education
387713003Surgical procedure (procedure)
103693007Diagnostic procedure
46947000Chiropractic manipulation
410606002Social service procedure (procedure)

The eight is-a codes of the status reason value set are 183932001, 416406003, 416237000, 428119001, 416064006, 416432009, 183944003 and 394908001.

Each of these value sets registers as a system value set. The sync_valueset management command writes the system value sets to the database.

The command skips a value set that already exists, unless you give its --overwrite option a value. The option takes an argument, and any non-empty value, False included, turns overwriting on.

So the compositions above are defaults. A superuser can edit a stored instance-level value set.

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

Service requests and activity definitions bind their code to a different value set, activity-definition-procedure-code. Its default rule is the same (is-a 71388002), but Care stores it as a separate value set.

Validation​

  • encounter, status and code are required on create.
  • The encounter in the request must exist. Otherwise the request fails with 400 "Encounter not found".
  • The encounter must belong to the patient in the URL. Otherwise the request fails with "Patient does not match the encounter's patient".
  • status must be a ProcedureStatus value, and outcome must be a ProcedureOutcome value.
  • Each coded field must hold a code from its bound value set, on create and on update.
  • occurrence takes at most one form, cannot be in the future, and refuses an empty or blank occurrence_string. A period needs time zones, and start must not be after end.
  • The specs type occurrence_datetime and recorded_date as AwareDatetime.
  • Care does not check recorded_date against the current time or against the occurrence.
  • No rule ties status_reason or outcome to status. The specs accept a status reason on a completed procedure.
  • No rule controls status changes. An update can set any status, also on an entered_in_error record.
  • On update, null clears status_reason, recorded_date, outcome or note. For any other field, null fails with 400.
  • Care ignores is_primary_source in a create or update request.

Server-side behaviour​

  • Create: Care takes patient from the encounter and saves is_primary_source as False.
  • Create: if recorded_date is empty, Care sets it to the time of saving.
  • Create: Care sets created_by and updated_by to the requesting user.
  • Update: Care drops id, external_id, patient and encounter from the request before validation.
  • Update: Care sets updated_by to the requesting user. It does not write history.
  • Read: Care returns external_id as id. Retrieve also returns the encounter's external_id, and the audit users as cached UserSpec objects.
  • Read: the specs build the response with model_construct, so no validator runs on read.

Methods & save behaviour​

  • The Procedure model defines no methods and no save() override. It uses the base model behaviour.
  • Delete is a soft delete. Care sets deleted = True and saves only that column. Deleted procedures disappear from every query.
  • patient and encounter use on_delete=CASCADE.
  • Each create and update writes a QuestionnaireResponse in the same transaction as the procedure save.
  • The questionnaire response has structured_response_type set to procedure. It links the patient and the encounter of the procedure.
  • Its structured_responses is {"procedure": {"submit_type": "CREATE", "id": "<procedure id>"}} on create. On update, UPDATE replaces CREATE.
  • A delete writes no questionnaire response.
  • On create, a request can send form_submission. It must be a draft form submission for the same patient and encounter, else the request fails with 404. Care attaches it to the questionnaire response.
  • Care reads form_submission from the top level of the request body. An update never attaches one.

API integration notes​

Endpoints​

The base path is /api/v1/patient/{patient_id}/procedure/, where {patient_id} is the patient's external_id. An unknown patient gives 404.

Care finds a single procedure by its external_id, inside the patient in the URL.

Method and pathActionRequestResponse
GET /listFilters belowPaginated ProcedureReadSpec
GET /{id}/retrieveNoneProcedureRetrieveSpec
POST /createProcedureCreateSpec200 (not 201), ProcedureRetrieveSpec
PUT /{id}/, PATCH /{id}/updateProcedureUpdateSpec (the same for both methods)200, ProcedureRetrieveSpec
DELETE /{id}/delete (soft delete)None204 No Content
POST /upsert/bulk create and updatedatapoints list200 or 400, with a list of per-datapoint results

The viewset adds no actions of its own.

If a request sends encounter as a query parameter, Care also limits retrieve, update and delete to that encounter. The encounter must belong to the patient, else the request fails with 404.

Upsert​

  • The body is a JSON object with a datapoints list. A body that is not a JSON object fails with "Invalid request data".
  • An object without datapoints, or with an empty list, fails with "No datapoints provided". More than MAX_DATAPOINTS_PER_UPSERT datapoints (default 100) fail with "Too many datapoints provided".
  • A datapoint with id updates that procedure through ProcedureUpdateSpec. A datapoint without id creates a procedure through ProcedureCreateSpec.
  • An update datapoint must belong to the patient in the URL and match the encounter filter, if one is sent.
  • Each datapoint goes through the same validation and authorization as a single create or update.
  • Each datapoint writes its own questionnaire response of type procedure.
  • A top-level form_submission applies to each created procedure. A form_submission inside a datapoint has no effect.
  • The upsert is all-or-nothing. Care processes the datapoints in order, in one transaction. If one datapoint fails, Care rolls back every change, questionnaire responses included.
  • The response is a list with one result per datapoint: 200 when all succeed, 400 when any fails.
  • A successful result is a ProcedureRetrieveSpec object. In a 400 response, these results stay in the list, but Care has rolled them back.
  • A failed result holds its error body: errors for a validation error, or detail for a permission refusal.
  • If Care cannot turn an exception into an error body, it raises the exception again, and the upsert fails with a server error.

Filters and ordering​

ParameterBehaviour
encounterEncounter external_id. Returns only that encounter's procedures. The encounter must belong to the patient, else 404
statusOne or more statuses, comma-separated
exclude_statusLeaves out one or more statuses, comma-separated
nameCase-insensitive partial match on code.display
orderingcreated_date, modified_date or recorded_date. A leading - sorts in descending order
limit, offsetPage size and start position. Default page size 14, maximum limit 200

Without ordering, the list returns the most recently created procedures first. The response has count and results.

The list hides no status by default. To leave out procedures entered in error, send exclude_status=entered_in_error.

Authorization​

Every call needs a signed-in user. The viewset checks clinical-data permissions for each action, as the table shows.

ActionCare checksPermission (slug)Refusal
list, no encounterPatient clinical-data read on the patient in the URL"Can view clinical data about patients" (can_view_clinical_data), through a role on the patient403 "Permission denied to user"
list with encounterPatient clinical-data read. If that fails, encounter clinical-data read on the given encounterAs above, or "Can Read encounter related clinical data" (can_read_encounter_clinical_data) in the encounter's organizations403 "Permission denied to user"
retrievePatient clinical-data read. If that fails, encounter clinical-data read on the procedure's own encounterAs for list with encounter403 "You do not have permission to view clinical data"
createEncounter clinical-data update on the encounter in the request"Update Encounter related clinical data" (can_write_encounter_clinical_data) in the encounter's organizations. The encounter must not be closed403 "You do not have permission to update encounter"
updateThe same check, on the procedure's own encounterAs for createAs for create
deleteThe same check, on the procedure's own encounterAs for createAs for create
upsertThe create or update check for each datapointAs for create and updateThe whole upsert fails with 400. The failed result holds detail with the message
  • Care counts these organizations for an encounter: the organizations linked to the encounter, their parents, and the facility's root organization, Administration. It also counts the organizations of the encounter's current location.
  • A user gets a role on the patient through three routes. These are the organizations of the patient's open encounters, an organization the patient belongs to, and a direct assignment on the patient.
  • An encounter is closed when its status is completed, cancelled, entered_in_error or discontinued. On a closed encounter, create, update and delete fail with the same 403 message. discharged is not closed.
  • The encounter clinical-data read check does not look at the encounter status.
  • By default, Doctor, Nurse and Facility Admin hold both encounter clinical-data permissions. Staff, Doctor, Nurse and Facility Admin hold "Can view clinical data about patients". These role lists are defaults. The permission definitions also name an Admin role. Roles are matched by name, and the only role named Admin in the database is for role organizations, which the facility screens do not offer. These lists leave it out.
  • The write permission alone allows create, update and delete, but not list or retrieve. The patient read permission alone allows retrieve, but not writes.
  • Create and update return ProcedureRetrieveSpec without a read check.
  • The write permission in one encounter's organizations does not allow writes to the procedures of another encounter.
  • Patient and encounter permissions that do not cover clinical data give no access to procedures.
  • Create and update validate the request before the permission check. So a user without permission can get a 400 or a 404 before a 403.

Errors​

CaseStatus and body
A spec validation fails, such as a body encounter that does not exist400. errors holds the pydantic errors. The msg of a validator error starts with "Value error, "
Another validation error, such as the patient mismatch400. errors holds one item of type validation_error
The patient in the URL, the procedure, the encounter query parameter, a form_submission or an upsert id is not found, or its id is malformed404. errors holds one item of type object_not_found
A permission check fails403. The body is {"detail": "<message>"}, with the message from the authorization table. It has no errors key
The call has no valid authentication403, with a detail body

Other notes​

  • Send each coded field as a Coding from its bound value set, not as free text.
  • Do not send patient. Care takes it from encounter on create and ignores it on update.
  • Care serves procedures under the patient, not under a facility. It serves service requests under a facility.
  • The viewset registers procedure as an internal questionnaire type. Its title is "Procedure", its description is "Historical procedure", and its subject type is patient.
  • A questionnaire cannot use the slug procedure. Care refuses it with "Slug cannot shadow internal question types".
  • A questionnaire can hold a structured question, which names the resource it records in structured_type. The backend does not validate structured_type, and answer validation skips structured questions.
  • Care's web frontend saves the procedure rows of a form as one upsert, inside one POST /api/v1/batch_requests/.
  • To combine procedure writes with other requests, use POST /api/v1/batch_requests/. A batch holds up to 20 requests by default, and Care rolls back the whole batch if any request fails.