Skip to main content
Version: 3.1

Service Request

A ServiceRequest records a proposal, plan, directive or order to perform a procedure for a patient.

Only two records point to a service request: a Specimen, through an optional service_request foreign key, and a DiagnosticReport, through a required one. Observations link to diagnostic reports, not to service requests. A ChargeItem links to a request through its service resource service_request.

The Care frontend orders through the apply_activity_definition action, which builds the request from an activity definition and creates its charge items. It never calls the plain create.

Source:

The Django model is only storage: several columns are opaque JSONFields and free-text CharFields. Their real structure, enums, bound value sets, and read/write API schemas live in the Pydantic resource specs (care/emr/resources/service_request/spec.py). Both layers are covered below.

The viewset adds the API rules on top of the specs: location and healthcare service checks, status rules, the custom actions and authorization. See API integration notes.

Models​

ModelPurpose
ServiceRequestAn order or proposal to perform an action for a patient

ServiceRequest extends EMRBaseModel, the shared Care EMR base. It supplies external_id, created_date/modified_date, the audit fields created_by/updated_by, history, meta, and soft delete through deleted. See Base model.

ServiceRequest fields​

Request definition​

FieldModel typeSpec type / shapeNotes
titleCharField(1024)strHuman-readable summary. Required on create, optional on update.
categoryCharField(255)ActivityDefinitionCategoryOptions enumCoded category. Required on create. See category values. apply_activity_definition fills it from the activity definition's category field unless the body sends one.
statusCharField(255)ServiceRequestStatusChoices enumLifecycle status. Required on create. See status values.
intentCharField(255)ServiceRequestIntentChoices enumRequired on create. See intent values.
priorityCharField(255)ServiceRequestPriorityChoices enumRequired on create. See priority values.
do_not_performBooleanFieldbool | NoneDo-not-perform flag. Model default False; spec default None. A write that leaves it out or sends null keeps the stored value, so a create without it stores False. The Care frontend's Service Request form always sends false; the service request page shows a "Do not perform" badge when it is set.
codeJSONField (nullable)Coding bound to activity-definition-procedure-codeThe requested service/procedure. Required on create. A single Coding, not a CodeableConcept, validated against the bound value set.
body_siteJSONField (nullable)Coding bound to system-body-site-observation, optionalCoded location on the body. A single Coding, validated against the bound value set.

A bound Coding (ValueSetBoundCoding) has the shape:

{
"system": "<str | null>",
"version": "<str | null>",
"code": "<str>", // required; must resolve in the bound value set
"display": "<str | null>"
}

Other keys are refused. A code outside the bound value set fails with "Code does not exist in the valueset".

Clinical detail​

FieldModel typeSpec typeNotes
noteTextField (nullable)str | NoneFree-text note. The frontend's "Save & Complete" replaces it with the completion note.
patient_instructionTextField (nullable)str | NoneFree-text instructions for the patient. The service request page shows it as "Patient Instruction".
occuranceDateTimeField (nullable)datetime | NoneOccurrence date and time. Spelled occurance in both model and spec; send it with that spelling. The Service Request form always sends it empty, and the service request page does not show it.

Relationships​

FieldModel typeSpec typeNotes
facilityFK → facility.Facility(not in any spec)Owning facility. PROTECT. Set by the server to the facility in the URL.
patientFK → emr.Patient(derived)Subject of the request. CASCADE. Not accepted from clients — set server-side from encounter.patient on create.
encounterFK → emr.Encounter (nullable)UUID4 (create only)Encounter the request belongs to. CASCADE. Nullable in the model, but required as a UUID on create and resolved with get_object_or_404; the create's permission check also needs the encounter in the facility. apply_activity_definition also requires an encounter in the facility. An update drops encounter from the body. Read back as a serialized encounter (EncounterListSpec).
healthcare_serviceFK → emr.HealthcareService (nullable)UUID4 | NoneHealthcare service for the request. PROTECT. Write accepts its external_id, looked up with HealthcareService.objects.get, so an unknown ID does not give a 404. Must belong to the request's facility ("Healthcare Service must be from the same facility"). On create and update, its locations are added to locations. Excluded from base serialize; returned only on retrieve (HealthcareServiceReadSpec).
activity_definitionFK → emr.ActivityDefinition (nullable)(read only)Activity definition the request was built from. PROTECT. Set only by apply_activity_definition; no write spec has the field. Returned only on retrieve.
requesterFK → users.User (nullable)UUID4 | None (write) / dict | None (read)Requesting user. CASCADE. Write accepts external_id, resolved with get_object_or_404; read returns a cached UserSpec dict. Only the plain create checks that the requester is a member of the facility, and it also refuses a request without a requester ("requester must be a member of the facility"); update and apply_activity_definition do not check. Ordering makes the requester the performer of the new charge items.
locationsArrayField[int]list[UUID4] (write) / list[dict] (read)Facility-location IDs the request applies to. Model default []. Write accepts location external_ids, kept on obj._locations for the viewset to resolve; each must be a location of the facility. On create and update, the healthcare service's locations are added. Every write replaces the list: a body without locations leaves only the healthcare service's locations. Serialized as FacilityLocationListSpec dicts only on retrieve. Decides which location lists show the request and where its permissions count.
tagsArrayField[int]list[dict] (read)Tag IDs. Model default []. Rendered with SingleFacilityTagManager().render_tags(obj) on read. No write spec has the field, but the plain create applies a tags list from the request body. After that, tags change through set_tags / remove_tags, which need the write permission and have no status check.
tags_dataJSONField—Default {}. Server-maintained expiry of each expiring tag, keyed by tag ID: {"<tag id>": {"expiry": "<datetime>"}}. Written when a tag with an expiry is set; the entry is deleted when the tag is removed. Read tags carry this expiry, and expired: true once it has passed; a background task then removes the tag.

Enums​

Status values​

ServiceRequestStatusChoices values use underscores, for example on_hold and entered_in_error.

ValueLabelHow it is set
draftDraftDefault when apply_activity_definition gets no status. No Care screen sets it
activeActiveThe Care frontend's Service Request form always sends it
on_holdOn HoldSet only by an API client. No Care screen sets it
entered_in_errorEntered in Errorcancel. An update cannot move a request into it
endedEndedSet only by an API client. No Care screen sets it
completedCompletedcomplete, or an update. The frontend's "Save & Complete" uses an update
revokedRevokedcancel. An update cannot move a request into it

Only the service request API changes a request's status.

spec.py derives two groupings from these:

  • SERVICE_REQUEST_COMPLETED_CHOICES = completed, revoked, ended, entered_in_error. A new charge item cannot link to a request in one of these statuses.
  • SERVICE_REQUEST_CANCELLED_CHOICES = revoked, entered_in_error. Update, complete and cancel refuse a request in one of these statuses.

ended is in the first group only, so update, complete and cancel still accept an ended request. See Status rules.

There is no unknown status. The frontend's status list has an extra unknown value that the backend does not have.

Intent values​

ServiceRequestIntentChoices

ValueLabelNotes
proposalProposalDefault when apply_activity_definition gets no intent
planPlan
directiveDirective
orderOrderThe Service Request form always sends it

Priority values​

ServiceRequestPriorityChoices

ValueLabelNotes
routineRoutineDefault when apply_activity_definition gets no priority. The Service Request form starts on it; the user can pick another
urgentUrgent
asapASAP
statSTAT

Category values​

category reuses ActivityDefinitionCategoryOptions from care/emr/resources/activity_definition/spec.py.

ValueLabel
laboratoryLaboratory
imagingImaging
counsellingCounselling
surgical_procedureProcedure
educationEducation

An activity definition stores classification as a text field and category as a link to a ResourceCategory. apply_activity_definition copies the definition's category into the request's category, not its classification.

The Service Request form sends the definition's classification as category, and a category in the body replaces the copied value.

Bound value sets​

Each coded Coding field validates its code against a registered Care value set (ValueSetBoundCoding[...]).

FieldValue set slugComposition
codeactivity-definition-procedure-code"Activity Definition Procedure Code": SNOMED CT is-a 71388002. See activity_definition/valueset.py.
body_sitesystem-body-site-observation"Body Site": 40 listed SNOMED CT concepts (bones and joints of the foot, leg and pelvis) plus is-a 442083009. See observation/valueset.py.

Resource specs (API schema)​

Every spec subclasses EMRResource. serialize copies the model's non-foreign-key fields that the spec declares and does not exclude, then runs perform_extra_serialization; de_serialize sets the fields, then runs perform_extra_deserialization. See Base model. The base sets __model__ = ServiceRequest and __exclude__ = ["encounter", "healthcare_service", "locations"], so those three fields are handled only by the explicit per-spec hooks.

Spec classRoleAdds / overrides
BaseServiceRequestSpecsharedid, title, status, intent, priority, category, do_not_perform, note, code (required), body_site, occurance, patient_instruction
ServiceRequestWriteSpecwrite · sharedAdds healthcare_service: UUID4?, locations: list[UUID4], requester: UUID4?. Resolves healthcare_service and requester from external_id; stashes locations on obj._locations.
ServiceRequestCreateSpecwrite · createAdds required encounter: UUID4. Resolves the encounter and sets obj.patient = obj.encounter.patient server-side.
ServiceRequestUpdateSpecwrite · updateMakes title, status, intent, priority, category, code all optional for partial update.
ServiceRequestReadSpecread · listAdds created_date, modified_date, encounter (serialized with EncounterListSpec), tags (rendered), requester (cached UserSpec). Sets id = external_id.
ServiceRequestRetrieveSpecread · detailExtends Read with locations (FacilityLocationListSpec), healthcare_service (HealthcareServiceReadSpec), activity_definition (ActivityDefinitionReadSpec), specimens (SpecimenReadSpec), diagnostic_reports (DiagnosticReportListSpec), embedded encounter.patient (PatientRetrieveSpec), and audit created_by/updated_by.

Write-side behaviour (perform_extra_deserialization)​

  • healthcare_service, when provided, is looked up by external_id with HealthcareService.objects.get and assigned. An unknown ID does not give a 404, because the lookup does not use get_object_or_404.
  • requester, when provided, is looked up by external_id with get_object_or_404(User, ...).
  • locations: the list of UUIDs is kept on obj._locations, an empty list when the body leaves it out. The viewset then resolves each UUID to a location of the facility, adds the healthcare service's locations, and stores the integer IDs in locations.
  • On create only, encounter is required, fetched with get_object_or_404(Encounter, ...), and obj.patient is forced to encounter.patient. Clients cannot set patient directly.

Read-side behaviour (perform_extra_serialization)​

  • id is set to external_id; encounter is serialized with EncounterListSpec; tags come from SingleFacilityTagManager().render_tags(obj); requester, if set, is a cached UserSpec.
  • On retrieve only: queries FacilityLocation for obj.locations; serializes healthcare_service and activity_definition when present; fetches the related Specimen and DiagnosticReport rows that reference this request; embeds the patient (PatientRetrieveSpec, scoped to obj.facility) under encounter.patient; and attaches audit users.

Server-maintained behaviour​

On create and update, the viewset resolves each locations UUID to a location of the facility and adds the healthcare service's locations to the list.

apply_activity_definition takes an activity definition slug and an encounter, both in the facility, and runs these steps:

  1. Builds an unsaved request with status draft, intent proposal and priority routine.
  2. Copies the definition's title, code, body_site, locations and healthcare_service. It copies the definition's category field, a link to a ResourceCategory, into category; it does not read the definition's classification.
  3. Checks can_write_service_request on the built request, whose locations are still the definition's. The write permission therefore counts in the encounter's departments or in a department of one of the definition's locations.
  4. Applies the request body. Values in the body replace the built ones. locations is always the body's list: without locations in the body, the request keeps only the healthcare service's locations, not the definition's.
  5. Links the activity definition and saves the request through the update path. The location and healthcare service checks run; the requester membership check does not.
  6. Creates one charge item for each charge item definition of the activity definition. Each charge item has the service resource service_request and the requester as performer.

Steps 5 and 6 run in one transaction.

The plain create's encounter check does not run here, so apply_activity_definition does not look at the encounter's status.

The Care frontend's Service Request form always sends status active, intent order, the definition's classification as category, and the definition's locations in the body.

cancel sets the status sent in the body. For every charge item linked to the request, it removes the item from its invoice and sets it to aborted. The status and the charge items are saved in one transaction.

If a linked charge item is on a non-draft invoice, the whole cancel fails: "Cannot cancel charge item in a non-draft invoice".

complete sets the status to completed. The frontend's "Save & Complete" does not call complete: it sends an update with status completed and the completion note as note.

Methods & save behaviour​

  • ServiceRequest defines no save or delete override. The base model's delete() sets deleted instead of removing the row, and the default manager hides deleted rows. The API has no delete endpoint. See Base model.
  • The write specs check the enums, the required code, the bound value sets and the create-time encounter. The database columns are plain CharField/JSONField without choices.
  • The viewset adds the rules the specs do not cover: facility locations, the healthcare service's facility, requester membership on create, and the status rules. See API integration notes.
  • patient is never accepted from the client; it is derived from encounter.patient on create.
  • Related Specimen and DiagnosticReport records reference the request with their own service_request FK. The detail view (Retrieve) reads them back rather than storing them on the request.

API integration notes​

Things that trip up integrators:

  • Enum values are lower case with underscores (on_hold, entered_in_error, asap), and the field occurance keeps that spelling in model and spec.
  • code is required and body_site optional; both are single Coding objects validated against their bound value sets — not CodeableConcept.
  • category, status, intent, and priority are validated as enums by the spec even though the columns are free CharFields.
  • Write healthcare_service, requester, and locations as external_id/UUIDs and let the server resolve them. encounter (UUID) is required on create and determines the patient.
  • locations and tags are integer ID arrays. Send locations as location UUIDs in the write body, and change tags through set_tags / remove_tags.
  • An update replaces locations with the body's list. Send the current location IDs with every update, as the frontend's "Save & Complete" does.
  • The location list matches the requests whose locations array overlaps the location's ID.

Endpoints​

All paths are under /api/v1/facility/{facility}/.

PathMethodActionNotes
service_request/POSTcreatePlain create with ServiceRequestCreateSpec. Also applies a tags list from the body. Returns ServiceRequestRetrieveSpec. No Care screen calls it
service_request/GETlistNeeds the encounter or location query parameter. See List filters and ordering
service_request/{id}/GETretrieveReturns ServiceRequestRetrieveSpec
service_request/{id}/PATCH or PUTupdateUses ServiceRequestUpdateSpec; both methods run the same handler, and the Care frontend sends PATCH. Returns ServiceRequestRetrieveSpec. See Status rules
service_request/{id}/set_tags/, service_request/{id}/remove_tags/POSTtagsBody tags: a list of { tag, expiry_offset }, where tag is a tag config UUID. Need the write permission. No status check. Return the retrieve response
service_request/{id}/complete/POSTcompleteSets the status to completed. Answers 204 with no body
service_request/{id}/cancel/POSTcancelBody status: revoked or entered_in_error. Aborts the linked charge items. Answers 204 with no body
service_request/apply_activity_definition/POSTorder from an activity definitionBody: activity_definition (slug), encounter (UUID) and service_request (an object of ServiceRequestUpdateSpec fields, every field optional). Builds and saves a request and its charge items; see Server-maintained behaviour. Returns ServiceRequestRetrieveSpec. The Care frontend orders only through this action
service_request/{id}/create_specimen/POSTcreate a specimenBody: the specimen fields (BaseSpecimenSpec). Checked with can_write_specimen on the request. No status check. Returns the specimen (SpecimenReadSpec)
service_request/{id}/create_specimen_from_definition/POSTcreate a specimen from a specimen definitionBody: specimen_definition (UUID) and specimen (SpecimenUpdateSpec fields). Checked with can_write_specimen on the request. No status check. Returns the specimen (SpecimenReadSpec)

There is no delete endpoint.

List filters and ordering​

A list request must carry encounter or location. Without either, Care refuses with "Location or encounter is required".

With location, the list returns the requests whose locations include that location. With encounter, it returns that encounter's requests.

FilterMatches
statusStatus value, case-insensitive
categoryCategory value
titlePart of the title, case-insensitive
priorityPriority value
intentIntent value
do_not_performThe do-not-perform flag
encounterThe encounter
encounter_classThe encounter's class, case-insensitive
patientThe patient
requesterThe requester
patient_current_locationThe current location (UUID) of the request's encounter
activity_definitionActivity definition slug, case-insensitive
created_dateA range of creation dates
tags, tags_behaviorComma-separated tag UUIDs; tags_behavior any (default) matches any of them, all every one
orderingcreated_date or modified_date; -created_date lists the newest first

The Care frontend asks for 20 requests a page (limit) on the encounter's list and 14 on a location's list.

Status rules​

ActionRefused whenMessage
updateThe request is completed"Service request is completed"
updateThe request is revoked or entered_in_error"Cannot update a cancelled service request"
updateThe new status is revoked or entered_in_error"Use the cancel API to cancel the service request"
completeThe request is completed"Service request is completed"
completeThe request is revoked or entered_in_error"Service request is cancelled"
cancelThe request is completed"Service request is completed"
cancelThe request is revoked or entered_in_error"Service request is already in a cancelled state"
cancelThe body status is not revoked or entered_in_error"Invalid status"
cancelA linked charge item is on an invoice that is not a draft"Cannot cancel charge item in a non-draft invoice"
Linking a new charge itemThe request is completed, revoked, ended or entered_in_errorThe charge item API refuses the link
set_tags, remove_tagsNever: no status check—
create_specimen, create_specimen_from_definitionNever: no status check—

An update accepts every other status change.

The plain create and apply_activity_definition run no status check, so a new request can start in any status, completed, revoked and entered_in_error included.

Validation messages​

RuleMessage
Each locations UUID must be a location of the facility"Location with id ... not found"
healthcare_service must be in the request's facility"Healthcare Service must be from the same facility"
requester must be a member of the facility (plain create only)"requester must be a member of the facility"
A list needs location or encounter"Location or encounter is required"
No questionnaire may use the slug service_request"Slug cannot shadow internal question types"

Authorization​

A check passes when the user has, in one of the given departments, a role that carries the permission.

A permission on a request counts when held in the encounter's departments, or else in a department of one of the request's locations.

The encounter's departments are the departments it is linked to, their parents, the facility's root "Administration" department, and the departments of the encounter's current location.

A location's departments are its parent location's departments, the departments it is linked to and their parents, and the facility's root department.

OperationCheckPermission and where it counts
Plain createcan_write_service_request_in_encounter on the encounter"Can Write Service Request on Facility" in the encounter's departments. An encounter in Entered in Error is refused; a completed encounter is not. Refusal: "You do not have permission to create a service request for this encounter"
Retrievecan_read_service_request"Can Read Service Request" on the request. Refusal: "You do not have permission to read this service request"
Update, complete, cancel, set_tags, remove_tags, apply_activity_definitioncan_write_service_request"Can Write Service Request on Facility" on the request. Refusal: "You do not have permission to update this service request"
List by locationcan_list_location_service_request"Can Read Service Request" in the location's departments. Refusal: "You do not have permission to view service requests for this location"
List by encountercan_view_service_request_for_encounter"Can Read Service Request" in the encounter's departments. Refusal: "You do not have permission to view service requests for this encounter"
create_specimen, create_specimen_from_definitioncan_write_specimen on the request"Can Create Specimen on Facility" on the request. Refusal: "You do not have permission to create a specimen for this encounter"
Files with file type service_requestcan_read_service_request to read, can_write_service_request to writeAs retrieve and update

Default role lists from the permission definitions:

PermissionDefault roles
"Can Write Service Request on Facility"Facility Admin, Doctor, Nurse
"Can Read Service Request"Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist
"Can Create Specimen on Facility"Facility Admin, Doctor, Nurse

The permission definitions also name an Admin role (ADMIN_ROLE). Roles are matched by name, and the role-organization "Admin" is synced after it, so the only role named Admin in the database is for role organizations, which the facility screens do not offer. The lists above leave it out.

Notes​

  • The viewset registers the internal questionnaire type service_request (title "Service Request", subject patient). No questionnaire may use that slug.
  • The Care frontend's built-in Service Request form has the ID service_request and is filled for an encounter. It sends one apply_activity_definition request per card in one batch and submits no questionnaire response.
  • A batch holds at most 20 requests by default (MAX_REQUESTS_PER_BATCH_REQUEST). The form stops before sending when one save has more.
  • The Care frontend never edits a request's fields after ordering. Its only update is "Save & Complete".
  • The files API accepts files with file type service_request. No Care screen uploads one; uploads on the service request page attach to diagnostic reports.
  • Activity Definition — template a request is built from by apply_activity_definition; supplies the category enum and code value set
  • Encounter — required context on create; supplies the patient
  • Patient — subject, derived from the encounter
  • Specimen — specimens collected for a request
  • Diagnostic Report — reports produced for a request
  • Observation — shares the body-site value set; links to diagnostic reports, not to requests
  • Charge Item — created on ordering and aborted on cancel
  • Resource Category — what an activity definition's category links to
  • Healthcare Service — service fulfilling the request
  • Location — facility locations the request applies to
  • User — requester / audit users
  • File Upload — files with file type service_request
  • Questionnaire — service_request is a reserved internal type
  • Concept: Service Request