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:
- Model:
care/emr/models/service_request.py - Resource spec:
care/emr/resources/service_request/spec.py - Viewset:
care/emr/api/viewsets/service_request.py - Building from an activity definition:
care/emr/resources/activity_definition/service_request.py - Authorization:
care/security/authorization/service_request.py· permissions:care/security/permissions/service_request.py
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
| Model | Purpose |
|---|---|
ServiceRequest | An 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
| Field | Model type | Spec type / shape | Notes |
|---|---|---|---|
title | CharField(1024) | str | Human-readable summary. Required on create, optional on update. |
category | CharField(255) | ActivityDefinitionCategoryOptions enum | Coded category. Required on create. See category values. apply_activity_definition fills it from the activity definition's category field unless the body sends one. |
status | CharField(255) | ServiceRequestStatusChoices enum | Lifecycle status. Required on create. See status values. |
intent | CharField(255) | ServiceRequestIntentChoices enum | Required on create. See intent values. |
priority | CharField(255) | ServiceRequestPriorityChoices enum | Required on create. See priority values. |
do_not_perform | BooleanField | bool | None | Do-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. |
code | JSONField (nullable) | Coding bound to activity-definition-procedure-code | The requested service/procedure. Required on create. A single Coding, not a CodeableConcept, validated against the bound value set. |
body_site | JSONField (nullable) | Coding bound to system-body-site-observation, optional | Coded 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
| Field | Model type | Spec type | Notes |
|---|---|---|---|
note | TextField (nullable) | str | None | Free-text note. The frontend's "Save & Complete" replaces it with the completion note. |
patient_instruction | TextField (nullable) | str | None | Free-text instructions for the patient. The service request page shows it as "Patient Instruction". |
occurance | DateTimeField (nullable) | datetime | None | Occurrence 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
| Field | Model type | Spec type | Notes |
|---|---|---|---|
facility | FK → facility.Facility | (not in any spec) | Owning facility. PROTECT. Set by the server to the facility in the URL. |
patient | FK → emr.Patient | (derived) | Subject of the request. CASCADE. Not accepted from clients — set server-side from encounter.patient on create. |
encounter | FK → 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_service | FK → emr.HealthcareService (nullable) | UUID4 | None | Healthcare 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_definition | FK → 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. |
requester | FK → 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. |
locations | ArrayField[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. |
tags | ArrayField[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_data | JSONField | — | 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.
| Value | Label | How it is set |
|---|---|---|
draft | Draft | Default when apply_activity_definition gets no status. No Care screen sets it |
active | Active | The Care frontend's Service Request form always sends it |
on_hold | On Hold | Set only by an API client. No Care screen sets it |
entered_in_error | Entered in Error | cancel. An update cannot move a request into it |
ended | Ended | Set only by an API client. No Care screen sets it |
completed | Completed | complete, or an update. The frontend's "Save & Complete" uses an update |
revoked | Revoked | cancel. 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,completeandcancelrefuse 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
| Value | Label | Notes |
|---|---|---|
proposal | Proposal | Default when apply_activity_definition gets no intent |
plan | Plan | |
directive | Directive | |
order | Order | The Service Request form always sends it |
Priority values
ServiceRequestPriorityChoices
| Value | Label | Notes |
|---|---|---|
routine | Routine | Default when apply_activity_definition gets no priority. The Service Request form starts on it; the user can pick another |
urgent | Urgent | |
asap | ASAP | |
stat | STAT |
Category values
category reuses ActivityDefinitionCategoryOptions from care/emr/resources/activity_definition/spec.py.
| Value | Label |
|---|---|
laboratory | Laboratory |
imaging | Imaging |
counselling | Counselling |
surgical_procedure | Procedure |
education | Education |
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[...]).
| Field | Value set slug | Composition |
|---|---|---|
code | activity-definition-procedure-code | "Activity Definition Procedure Code": SNOMED CT is-a 71388002. See activity_definition/valueset.py. |
body_site | system-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 class | Role | Adds / overrides |
|---|---|---|
BaseServiceRequestSpec | shared | id, title, status, intent, priority, category, do_not_perform, note, code (required), body_site, occurance, patient_instruction |
ServiceRequestWriteSpec | write · shared | Adds healthcare_service: UUID4?, locations: list[UUID4], requester: UUID4?. Resolves healthcare_service and requester from external_id; stashes locations on obj._locations. |
ServiceRequestCreateSpec | write · create | Adds required encounter: UUID4. Resolves the encounter and sets obj.patient = obj.encounter.patient server-side. |
ServiceRequestUpdateSpec | write · update | Makes title, status, intent, priority, category, code all optional for partial update. |
ServiceRequestReadSpec | read · list | Adds created_date, modified_date, encounter (serialized with EncounterListSpec), tags (rendered), requester (cached UserSpec). Sets id = external_id. |
ServiceRequestRetrieveSpec | read · detail | Extends 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 byexternal_idwithHealthcareService.objects.getand assigned. An unknown ID does not give a 404, because the lookup does not useget_object_or_404.requester, when provided, is looked up byexternal_idwithget_object_or_404(User, ...).locations: the list of UUIDs is kept onobj._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 inlocations.- On create only,
encounteris required, fetched withget_object_or_404(Encounter, ...), andobj.patientis forced toencounter.patient. Clients cannot setpatientdirectly.
Read-side behaviour (perform_extra_serialization)
idis set toexternal_id;encounteris serialized withEncounterListSpec;tagscome fromSingleFacilityTagManager().render_tags(obj);requester, if set, is a cachedUserSpec.- On retrieve only: queries
FacilityLocationforobj.locations; serializeshealthcare_serviceandactivity_definitionwhen present; fetches the relatedSpecimenandDiagnosticReportrows that reference this request; embeds the patient (PatientRetrieveSpec, scoped toobj.facility) underencounter.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:
- Builds an unsaved request with status
draft, intentproposaland priorityroutine. - Copies the definition's
title,code,body_site,locationsandhealthcare_service. It copies the definition'scategoryfield, a link to aResourceCategory, intocategory; it does not read the definition'sclassification. - Checks
can_write_service_requeston 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. - Applies the request body. Values in the body replace the built ones.
locationsis always the body's list: withoutlocationsin the body, the request keeps only the healthcare service's locations, not the definition's. - 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.
- Creates one charge item for each charge item definition of the activity definition. Each charge item has the service resource
service_requestand 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
ServiceRequestdefines nosaveordeleteoverride. The base model'sdelete()setsdeletedinstead 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-timeencounter. The database columns are plainCharField/JSONFieldwithout 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.
patientis never accepted from the client; it is derived fromencounter.patienton create.- Related
SpecimenandDiagnosticReportrecords reference the request with their ownservice_requestFK. 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 fieldoccurancekeeps that spelling in model and spec. codeis required andbody_siteoptional; both are singleCodingobjects validated against their bound value sets — notCodeableConcept.category,status,intent, andpriorityare validated as enums by the spec even though the columns are freeCharFields.- Write
healthcare_service,requester, andlocationsasexternal_id/UUIDs and let the server resolve them.encounter(UUID) is required on create and determines the patient. locationsandtagsare integer ID arrays. Sendlocationsas location UUIDs in the write body, and changetagsthroughset_tags/remove_tags.- An update replaces
locationswith 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
locationsarray overlaps the location's ID.
Endpoints
All paths are under /api/v1/facility/{facility}/.
| Path | Method | Action | Notes |
|---|---|---|---|
service_request/ | POST | create | Plain create with ServiceRequestCreateSpec. Also applies a tags list from the body. Returns ServiceRequestRetrieveSpec. No Care screen calls it |
service_request/ | GET | list | Needs the encounter or location query parameter. See List filters and ordering |
service_request/{id}/ | GET | retrieve | Returns ServiceRequestRetrieveSpec |
service_request/{id}/ | PATCH or PUT | update | Uses 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/ | POST | tags | Body 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/ | POST | complete | Sets the status to completed. Answers 204 with no body |
service_request/{id}/cancel/ | POST | cancel | Body status: revoked or entered_in_error. Aborts the linked charge items. Answers 204 with no body |
service_request/apply_activity_definition/ | POST | order from an activity definition | Body: 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/ | POST | create a specimen | Body: 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/ | POST | create a specimen from a specimen definition | Body: 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.
| Filter | Matches |
|---|---|
status | Status value, case-insensitive |
category | Category value |
title | Part of the title, case-insensitive |
priority | Priority value |
intent | Intent value |
do_not_perform | The do-not-perform flag |
encounter | The encounter |
encounter_class | The encounter's class, case-insensitive |
patient | The patient |
requester | The requester |
patient_current_location | The current location (UUID) of the request's encounter |
activity_definition | Activity definition slug, case-insensitive |
created_date | A range of creation dates |
tags, tags_behavior | Comma-separated tag UUIDs; tags_behavior any (default) matches any of them, all every one |
ordering | created_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
| Action | Refused when | Message |
|---|---|---|
| update | The request is completed | "Service request is completed" |
| update | The request is revoked or entered_in_error | "Cannot update a cancelled service request" |
| update | The new status is revoked or entered_in_error | "Use the cancel API to cancel the service request" |
complete | The request is completed | "Service request is completed" |
complete | The request is revoked or entered_in_error | "Service request is cancelled" |
cancel | The request is completed | "Service request is completed" |
cancel | The request is revoked or entered_in_error | "Service request is already in a cancelled state" |
cancel | The body status is not revoked or entered_in_error | "Invalid status" |
cancel | A 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 item | The request is completed, revoked, ended or entered_in_error | The charge item API refuses the link |
set_tags, remove_tags | Never: no status check | — |
create_specimen, create_specimen_from_definition | Never: 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
| Rule | Message |
|---|---|
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.
| Operation | Check | Permission and where it counts |
|---|---|---|
| Plain create | can_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" |
| Retrieve | can_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_definition | can_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 location | can_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 encounter | can_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_definition | can_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_request | can_read_service_request to read, can_write_service_request to write | As retrieve and update |
Default role lists from the permission definitions:
| Permission | Default 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_requestand is filled for an encounter. It sends oneapply_activity_definitionrequest 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.
Related models
- Activity Definition — template a request is built from by
apply_activity_definition; supplies thecategoryenum andcodevalue 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
categorylinks 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_requestis a reserved internal type - Concept: Service Request