Skip to main content
Version: 3.1

Activity Definition

Technical reference for the ActivityDefinition module in Care EMR. For what an activity definition is, see the Activity Definition concept.

An ActivityDefinition is a facility-scoped template for a clinical activity. Applying it to an encounter creates a Service Request, and a charge item for each linked Charge Item Definition.

Source:

The Django model stores the data. Several fields are JSON fields or integer arrays whose real shape is defined by the Pydantic resource specs: the enums, the value set bindings, the validation and the read and write schemas. Read the two layers together.

Models​

ModelPurpose
ActivityDefinitionFacility-scoped template for a clinical activity, holding the defaults used to create the service request it produces

ActivityDefinition extends SlugBaseModel, which extends EMRBaseModel. From these it inherits external_id, created_date, modified_date, deleted (soft delete), created_by, updated_by, history and meta. See Base model.

ActivityDefinition fields​

Each field lists its storage type (Django model) and, where a spec constrains it, the API shape.

Identity & versioning​

FieldStorage typeAPI shape / notes
facilityFK → facility.Facility (PROTECT)Excluded from the specs. Set on create from the facility in the URL
slugCharField(255)Written as slug_value (SlugType, 5–50 characters). Stored as f-<facility external id>-<slug_value>. Unique in the facility, compared case-insensitively. Read back as slug plus a parsed slug_config. The API looks records up by slug
versionIntegerFieldDefault 1. Read-only (version: int | None on read). No code changes it
latestBooleanFieldDefault True. Not in any spec. No code changes it
derived_from_uriTextField, nullableOptional (str | None = None)

version and latest do not form a version chain. No code increments version or changes latest, and an update changes the record in place. Earlier states are not kept as separate records.

Descriptive metadata​

FieldStorage typeAPI shape / notes
titleCharField(1024)Required str
statusCharField(255)Required enum ActivityDefinitionStatusOptions
classificationCharField(100)Required enum ActivityDefinitionCategoryOptions. Labelled "Category" in the UI
kindCharField(100)Required enum ActivityDefinitionKindOptions (only service_request)
descriptionTextFieldOptional in the specs, default "". The UI form requires it
usageTextFieldOptional in the specs, default "". The UI form requires it

Coded clinical attributes (JSON)​

These are JSONFields. The spec binds each one to a value set with ValueSetBoundCoding[<slug>], which checks the submitted code against that value set. A code outside the value set fails with "Code does not exist in the valueset".

Each coding is Coding: code is required, system, version and display are optional, and extra keys are refused.

FieldStorage typeAPI shape / notes
codeJSONField, nullableRequired Coding bound to activity-definition-procedure-code
body_siteJSONField, nullableOptional Coding (default None) bound to system-body-site-observation
diagnostic_report_codesJSONField, nullablelist[Coding], default [], each bound to system-observation

Requirement & linkage arrays​

These fields store integer primary keys in ArrayField(IntegerField) with an empty-list default, not foreign keys. Writes reference the targets by slug or UUID, and the viewset converts them to ids on save. Retrieve expands them into objects and skips any id that no longer resolves.

FieldStorage typeWrite shapeRead (retrieve) shape
specimen_requirementsArrayField[int]list[ExtendedSlugType]list[dict], serialized Specimen Definitions
observation_result_requirementsArrayField[int]list[ExtendedSlugType]list[dict], serialized Observation Definitions
charge_item_definitionsArrayField[int]list[ExtendedSlugType]list[dict], serialized Charge Item Definitions
locationsArrayField[int]list[UUID4]list[dict], serialized Locations

Every linked specimen definition, observation definition, charge item definition and location must belong to the same facility. Otherwise the save fails with <Type> with slug <slug> not found or Location with id <id> not found. The status of a linked definition is not checked.

ExtendedSlugType is 7–89 characters and must start with f- or i-. SlugType is 5–50 characters.

Tags​

FieldStorage typeAPI shape / notes
tagsArrayField[int]Set with a tags list in the create body, or with set_tags and remove_tags. Read as rendered tag objects
tags_dataJSONFieldDefault {}. Holds an expiry per applied tag, keyed by tag id. A rendered tag with expiry data carries expiry, and expired: true once the expiry has passed. Not in any spec

Service relationships​

FieldStorage typeAPI shape / notes
healthcare_serviceFK → emr.HealthcareService (PROTECT), nullableWrite: UUID4 | None, a required key. Must be in the same facility ("Healthcare Service must be from the same facility"). Retrieve: serialized Healthcare Service
categoryFK → emr.ResourceCategory (PROTECT), nullableWrite: ExtendedSlugType | None, a required key. Must be a resource category of the same facility (404 otherwise). The backend does not check the category's resource type, or that it has no children. Read: serialized Resource Category. A category that a definition uses cannot be deleted

Enum values​

ActivityDefinitionStatusOptions (status)​

Value
draft
active
retired
unknown

ActivityDefinitionKindOptions (kind)​

ValueNotes
service_requestOnly kind. Applying the definition produces a Service Request

ActivityDefinitionCategoryOptions (classification)​

ValueUI label
laboratoryLaboratory
imagingImaging
counsellingCounselling
surgical_procedureProcedure
educationEducation

Bound value sets​

FieldValue set slugSource system / filter
codeactivity-definition-procedure-codeSNOMED CT, concept is-a 71388002
body_sitesystem-body-site-observationSNOMED CT: a list of body-site concepts, plus every concept under 442083009
diagnostic_report_codes[]system-observationLOINC (http://loinc.org)

The frontend body-site pickers search system-body-site (SNOMED CT, concept is-a 91723000). In a runtime check of 12 searches, all 238 codes that the picker offered were accepted by system-body-site-observation.

Resource specs (API schema)​

All specs extend EMRResource, with __model__ = ActivityDefinition and __exclude__ = ["facility"].

Spec classRoleNotes
BaseActivityDefinitionSpecshared baseid, title, derived_from_uri, status, description, usage, classification, kind, code, body_site, diagnostic_report_codes
ActivityDefinitionWriteSpecwrite · create and updateAdds locations, specimen_requirements, observation_result_requirements, healthcare_service, charge_item_definitions, category and slug_value. Every added key is required (no defaults); healthcare_service and category may be null
ActivityDefinitionReadSpecread · listBase fields plus version, tags, category (object), slug_config and slug
ActivityDefinitionRetrieveSpecread · detailExtends the read spec. Expands specimen_requirements, observation_result_requirements, locations, healthcare_service and charge_item_definitions into objects, and skips ids that no longer resolve

Methods & save behaviour​

  • Create. Sets facility from the URL and stores the prefixed slug. Converts the linked slugs and location ids to internal ids (same facility only), checks the healthcare service's facility, saves, and then applies a tags list from the request body.
  • Update. Runs the same conversions and checks, and changes the record in place.
  • Apply → Service Request (service_request.py). convert_ad_to_sr builds a service request with the definition's title, category, code, body_site, locations and healthcare_service, status draft, intent proposal and priority routine.
  • Category on apply. convert_ad_to_sr sets the service request's category from the definition's resource-category foreign key, but ServiceRequest.category holds a classification value. The service_request fields of the request body then replace the defaults. The frontend sends the definition's classification as category, with status active and intent order.
  • Charge items on apply. apply_ad_charge_definitions creates a charge item for every linked charge item definition, whatever its status, and links it to the service request. The performer is the requester when one is set. Each charge item starts billable.
  • Negative totals. A charge item with a negative total fails with "Total price is less than 0". This path does not allow negative charge items, so ordering a definition linked to a charge item definition with a negative base price fails, and nothing is saved.
  • No status check on apply. apply_activity_definition finds the definition by slug and facility and does not check its status. Only the frontend picker filters to active.

API integration notes​

Endpoints​

The base path is /api/v1/facility/{facility_id}/activity_definition/. Records are looked up by slug.

Method and pathActionNotes
GET /listFilters below
POST /createActivityDefinitionWriteSpec
GET /{slug}/retrieveActivityDefinitionRetrieveSpec
PUT /{slug}/updateActivityDefinitionWriteSpec
POST /{slug}/set_tags/, POST /{slug}/remove_tags/tagsUpdate check, plus "Can Apply Tag Config to Resources" for each tag. Each tag must be configured for activity definitions
POST /upsert/bulk create or updatedatapoints, 1 to 100 by default. A datapoint with id updates the record with that slug, one without creates a record. Any failure rolls back every change and returns 400 with one result per datapoint
GET /favorite_lists/, POST /{slug}/add_favorite/, POST /{slug}/remove_favorite/favoritesAt most 50 entries per list by default

There is no DELETE. To retire a definition, update it with status set to retired.

To apply a definition, call POST /api/v1/facility/{facility_id}/service_request/apply_activity_definition/ with activity_definition (slug), encounter (UUID, in the same facility) and service_request (ServiceRequestUpdateSpec). Care links the new service request to the definition, and saves it and its charge items in one transaction.

List filters​

ParameterBehaviour
statusExact match, case-insensitive
titleTrigram similarity
classificationClassification value
kindKind value
categorySlug of a resource category of the facility. Returns the definitions in that category
include_childrenWith category and true, returns only the definitions in the category's descendant categories, not those in the category itself (parent_cache holds only ancestors)
orderingcreated_date or modified_date

Authorization​

  • List, retrieve, and the record lookup for update, tags and favorites need can_read_activity_definition ("Can Read Activity Definition") in any organization of the facility.
  • Create and update need can_write_activity_definition ("Can Create Activity Definition on Facility") in the facility's root organization. Without it, the request fails with 403 "Access Denied to Activity Definition", also for a user who holds the permission in another organization of the facility.
  • By default, Facility Admin holds the write permission. Facility Admin, Administrator, Staff, Doctor, Nurse and Volunteer hold the read permission.
  • Applying a definition needs "Can Write Service Request on Facility" for the new service request, in an organization of the encounter, of its current location, or of the service request's locations.

Validation errors​

MessageCause
"Activity Definition with this slug already exists."Another definition in the facility has the slug (compared case-insensitively)
404 on categorycategory is not a resource category of the facility
Specimen Definition with slug <slug> not foundA linked specimen definition is not in the facility. Observation and charge item definitions give the same message with their type
Location with id <id> not foundA linked location is not in the facility
"Healthcare Service must be from the same facility"The healthcare service belongs to another facility
"Code does not exist in the valueset"A coded field holds a code outside its bound value set