# Activity Definition

Technical reference for the `ActivityDefinition` module in Care EMR. For what an activity definition is, see the [Activity Definition](https://docs.ohc.network/concepts/definitions/activity-definition.md) concept.

An `ActivityDefinition` is a facility-scoped template for a clinical activity. Applying it to an encounter creates a [Service Request](https://docs.ohc.network/references/clinical/service-request.md), and a charge item for each linked [Charge Item Definition](https://docs.ohc.network/references/definitions/charge-item-definition.md).

**Source:**

* Model: [`care/emr/models/activity_definition.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/activity_definition.py)
* Resource specs: [`spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/activity_definition/spec.py) · [`valueset.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/activity_definition/valueset.py) · [`service_request.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/activity_definition/service_request.py)
* Viewset: [`activity_definition.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/activity_definition.py)
* Authorization: [`activity_definition.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/activity_definition.py) · permissions [`activity_definition.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/activity_definition.py)

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

| Model | Purpose |
| - | - |
| `ActivityDefinition` | Facility-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](https://docs.ohc.network/references/foundation/base-model.md).

## `ActivityDefinition` fields

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

### Identity & versioning

| Field | Storage type | API shape / notes |
| - | - | - |
| `facility` | `FK → facility.Facility` (PROTECT) | Excluded from the specs. Set on create from the facility in the URL |
| `slug` | `CharField(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` |
| `version` | `IntegerField` | Default `1`. Read-only (`version: int \| None` on read). No code changes it |
| `latest` | `BooleanField` | Default `True`. Not in any spec. No code changes it |
| `derived_from_uri` | `TextField`, nullable | Optional (`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

| Field | Storage type | API shape / notes |
| - | - | - |
| `title` | `CharField(1024)` | Required `str` |
| `status` | `CharField(255)` | Required enum `ActivityDefinitionStatusOptions` |
| `classification` | `CharField(100)` | Required enum `ActivityDefinitionCategoryOptions`. Labelled "Category" in the UI |
| `kind` | `CharField(100)` | Required enum `ActivityDefinitionKindOptions` (only `service_request`) |
| `description` | `TextField` | Optional in the specs, default `""`. The UI form requires it |
| `usage` | `TextField` | Optional in the specs, default `""`. The UI form requires it |

### Coded clinical attributes (JSON)

These are `JSONField`s. 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.

| Field | Storage type | API shape / notes |
| - | - | - |
| `code` | `JSONField`, nullable | Required `Coding` bound to `activity-definition-procedure-code` |
| `body_site` | `JSONField`, nullable | Optional `Coding` (default `None`) bound to `system-body-site-observation` |
| `diagnostic_report_codes` | `JSONField`, nullable | `list[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.

| Field | Storage type | Write shape | Read (retrieve) shape |
| - | - | - | - |
| `specimen_requirements` | `ArrayField[int]` | `list[ExtendedSlugType]` | `list[dict]`, serialized [Specimen Definitions](https://docs.ohc.network/references/definitions/specimen-definition.md) |
| `observation_result_requirements` | `ArrayField[int]` | `list[ExtendedSlugType]` | `list[dict]`, serialized [Observation Definitions](https://docs.ohc.network/references/definitions/observation-definition.md) |
| `charge_item_definitions` | `ArrayField[int]` | `list[ExtendedSlugType]` | `list[dict]`, serialized [Charge Item Definitions](https://docs.ohc.network/references/definitions/charge-item-definition.md) |
| `locations` | `ArrayField[int]` | `list[UUID4]` | `list[dict]`, serialized [Locations](https://docs.ohc.network/references/facility/location.md) |

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

| Field | Storage type | API shape / notes |
| - | - | - |
| `tags` | `ArrayField[int]` | Set with a `tags` list in the create body, or with `set_tags` and `remove_tags`. Read as rendered tag objects |
| `tags_data` | `JSONField` | Default `{}`. 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

| Field | Storage type | API shape / notes |
| - | - | - |
| `healthcare_service` | `FK → emr.HealthcareService` (PROTECT), nullable | Write: `UUID4 \| None`, a required key. Must be in the same facility ("Healthcare Service must be from the same facility"). Retrieve: serialized [Healthcare Service](https://docs.ohc.network/references/facility/healthcare-service.md) |
| `category` | `FK → emr.ResourceCategory` (PROTECT), nullable | Write: `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](https://docs.ohc.network/references/platform/resource-category.md). A category that a definition uses cannot be deleted |

## Enum values

### `ActivityDefinitionStatusOptions` (`status`)

| Value |
| - |
| `draft` |
| `active` |
| `retired` |
| `unknown` |

### `ActivityDefinitionKindOptions` (`kind`)

| Value | Notes |
| - | - |
| `service_request` | Only kind. Applying the definition produces a [Service Request](https://docs.ohc.network/references/clinical/service-request.md) |

### `ActivityDefinitionCategoryOptions` (`classification`)

| Value | UI label |
| - | - |
| `laboratory` | Laboratory |
| `imaging` | Imaging |
| `counselling` | Counselling |
| `surgical_procedure` | Procedure |
| `education` | Education |

## Bound value sets

| Field | Value set slug | Source system / filter |
| - | - | - |
| `code` | `activity-definition-procedure-code` | SNOMED CT, `concept is-a 71388002` |
| `body_site` | `system-body-site-observation` | SNOMED CT: a list of body-site concepts, plus every concept under 442083009 |
| `diagnostic_report_codes[]` | `system-observation` | LOINC (`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 class | Role | Notes |
| - | - | - |
| `BaseActivityDefinitionSpec` | shared base | `id`, `title`, `derived_from_uri`, `status`, `description`, `usage`, `classification`, `kind`, `code`, `body_site`, `diagnostic_report_codes` |
| `ActivityDefinitionWriteSpec` | write · create and update | Adds `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` |
| `ActivityDefinitionReadSpec` | read · list | Base fields plus `version`, `tags`, `category` (object), `slug_config` and `slug` |
| `ActivityDefinitionRetrieveSpec` | read · detail | Extends 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`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/activity_definition/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 path | Action | Notes |
| - | - | - |
| `GET /` | list | Filters below |
| `POST /` | create | `ActivityDefinitionWriteSpec` |
| `GET /{slug}/` | retrieve | `ActivityDefinitionRetrieveSpec` |
| `PUT /{slug}/` | update | `ActivityDefinitionWriteSpec` |
| `POST /{slug}/set_tags/`, `POST /{slug}/remove_tags/` | tags | Update check, plus "Can Apply Tag Config to Resources" for each tag. Each tag must be configured for activity definitions |
| `POST /upsert/` | bulk create or update | `datapoints`, 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/` | favorites | At 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

| Parameter | Behaviour |
| - | - |
| `status` | Exact match, case-insensitive |
| `title` | Trigram similarity |
| `classification` | Classification value |
| `kind` | Kind value |
| `category` | Slug of a resource category of the facility. Returns the definitions in that category |
| `include_children` | With `category` and `true`, returns only the definitions in the category's descendant categories, not those in the category itself (`parent_cache` holds only ancestors) |
| `ordering` | `created_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

| Message | Cause |
| - | - |
| "Activity Definition with this slug already exists." | Another definition in the facility has the slug (compared case-insensitively) |
| 404 on `category` | `category` is not a resource category of the facility |
| `Specimen Definition with slug <slug> not found` | A 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 found` | A 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 |

## Related

* Concept: [Activity Definition](https://docs.ohc.network/concepts/definitions/activity-definition.md)
* Reference: [Service Request](https://docs.ohc.network/references/clinical/service-request.md)
* Reference: [Specimen Definition](https://docs.ohc.network/references/definitions/specimen-definition.md)
* Reference: [Observation Definition](https://docs.ohc.network/references/definitions/observation-definition.md)
* Reference: [Charge Item Definition](https://docs.ohc.network/references/definitions/charge-item-definition.md)
* Reference: [Healthcare Service](https://docs.ohc.network/references/facility/healthcare-service.md)
* Reference: [Location](https://docs.ohc.network/references/facility/location.md)
* Reference: [Resource Category](https://docs.ohc.network/references/platform/resource-category.md)
* Reference: [Tag Config](https://docs.ohc.network/references/platform/tag-config.md)
* Reference: [Favorites](https://docs.ohc.network/references/platform/favorites.md)
* Reference: [Base model](https://docs.ohc.network/references/foundation/base-model.md)
* Source: [`activity_definition.py` (model)](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/activity_definition.py)
* Source: [`spec.py` (resource specs)](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/activity_definition/spec.py)
* Source: [`valueset.py` (procedure-code value set)](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/activity_definition/valueset.py)
* Source: [`service_request.py` (apply logic)](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/activity_definition/service_request.py)
* Source: [`activity_definition.py` (viewset)](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/activity_definition.py)
