# Medication administration

Technical reference for the `MedicationAdministration` module in Care EMR. For what a medication administration is in the product, see the [Medication administration](https://docs.ohc.network/concepts/medications/medication-administration.md) concept.

A medication administration records one administration event under a [medication request](https://docs.ohc.network/references/medications/medication-request.md): its status, its start time and the dosage given.

**Source:**

* Model: [`care/emr/models/medication_administration.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/medication_administration.py)
* Spec: [`care/emr/resources/medication/administration/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/medication/administration/spec.py)
* Viewset: [`care/emr/api/viewsets/medication_administration.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/medication_administration.py)
* Value sets: [`care/emr/resources/medication/valueset/`](https://github.com/ohcnetwork/care/tree/develop/care/emr/resources/medication/valueset)

The Django model stores `medication`, `status_reason`, `performer` and `dosage` as JSON columns. The Pydantic resource specs define their shape, the enums, the validation and the read and write schemas. This page covers both layers.

## Models

| Model | Purpose |
| - | - |
| `MedicationAdministration` | One administration event under a medication request |

`MedicationAdministration` extends [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md). It supplies `external_id`, `created_date`, `modified_date`, the soft-delete flag `deleted`, `created_by`, `updated_by`, `history` and `meta`.

## `MedicationAdministration` fields

In the tables below, the model type is the Django column and the spec type is what the API reads and writes. "Fixed" means that the update spec does not accept the field after create.

### Status & classification

| Field | Model type | Spec type | Required (API) | Notes |
| - | - | - | - | - |
| `status` | `CharField(100)` | `MedicationAdministrationStatus` | Yes | Can change after create, with no transition rule. See [status values](#medicationadministrationstatus-values) |
| `status_reason` | `JSONField`, nullable | `ValueSetBoundCoding[system-medication] \| None` | No | Bound to the Medication value set, not to a not-given reason set. Fixed |
| `category` | `CharField(100)`, nullable | `MedicationAdministrationCategory \| None` | No | Fixed. See [category values](#medicationadministrationcategory-values) |

### Medication & product

| Field | Model type | Spec type | Required (API) | Notes |
| - | - | - | - | - |
| `medication` | `JSONField`, default `{}` | `ValueSetBoundCoding[system-medication] \| None` | No | Cannot be sent with `administered_product`. Fixed |
| `administered_product` | `FK → ProductKnowledge`, `CASCADE`, nullable | `UUID4 \| None` (write), product knowledge read (read) | No | A catalogue product, in place of a coded medication. Fixed |
| `dosage` | `JSONField`, nullable | `Dosage \| None` | No | See [`Dosage`](#dosage-nested-spec). Fixed |

### Subject & context

| Field | Model type | Spec type | Required (API) | Notes |
| - | - | - | - | - |
| `patient` | `FK → Patient`, `CASCADE` | Not accepted | Server-set | Copied from the encounter on create |
| `encounter` | `FK → Encounter`, `CASCADE`, nullable | `UUID4` | Yes (create) | Must exist ("Encounter not found"). Dropped from an update body. Read returns the encounter id |
| `request` | `FK → MedicationRequest`, `CASCADE`, nullable | `UUID4` | Yes (create) | Must exist ("Medication Request not found"). Existence is the only check: Care does not check that the request belongs to the same encounter or patient. Read returns the request id. Fixed |

### Timing & attribution

| Field | Model type | Spec type | Required (API) | Notes |
| - | - | - | - | - |
| `authored_on` | `DateTimeField`, nullable | `datetime \| None` | No | Fixed |
| `occurrence_period_start` | `DateTimeField`, default `datetime.now` | `datetime` | Yes | The API sets no default, so the model default is not used by API creates. Fixed |
| `occurrence_period_end` | `DateTimeField`, nullable | `datetime \| None` | No | Can change after create |
| `recorded` | `DateTimeField`, nullable | `datetime \| None` | No | Fixed |
| `performer` | `JSONField`, default `[]` | `list[MedicationAdministrationPerformer] \| None` | No | See [`MedicationAdministrationPerformer`](#medicationadministrationperformer-nested-spec). Fixed |
| `note` | `TextField`, nullable | `str \| None` | No | Can change after create. Sending `null` does not clear it |

## Enum values

Enum values use underscores (`not_done`, `in_progress`, `entered_in_error`). They are the exact strings that the API accepts and returns.

### `MedicationAdministrationStatus` values

| Value |
| - |
| `completed` |
| `not_done` |
| `entered_in_error` |
| `stopped` |
| `in_progress` |
| `on_hold` |
| `unknown` |
| `cancelled` |

### `MedicationAdministrationCategory` values

| Value |
| - |
| `inpatient` |
| `outpatient` |
| `community` |
| `discharge` |

### `MedicationAdministrationPerformerFunction` values

| Value |
| - |
| `performer` |
| `verifier` |
| `witness` |

## Nested specs (JSON-field shapes)

### `Dosage` (nested spec)

The shape of the `dosage` column. Every field is optional.

| Field | Type | Notes |
| - | - | - |
| `text` | `str \| None` | Free-text dosage instructions |
| `site` | `Coding \| None` | Bound to the Body Site value set |
| `route` | `Coding \| None` | Bound to the Route value set |
| `method` | `Coding \| None` | Bound to the Administration Method value set |
| `dose` | `Quantity \| None` | The amount administered |
| `rate` | `Quantity \| None` | The speed of administration |

```
Quantity {

  value: Decimal | None                # up to 6 decimal places

  unit: Coding | None

  code: Coding | None

  meta: dict | None

}                                      # unknown keys are refused



Coding {

  system: str | None

  version: str | None

  code: str                            # required

  display: str | None

}                                      # unknown keys are refused
```

### `MedicationAdministrationPerformer` (nested spec)

The shape of each entry of the `performer` list.

| Field | Type | Notes |
| - | - | - |
| `actor` | `UUID4` | Required. The user must exist ("User not found") |
| `function` | `MedicationAdministrationPerformerFunction \| None` | Declared with no default value. See [performer function values](#medicationadministrationperformerfunction-values) |

The user who saves the record is stored in `created_by` and `updated_by`. `performer` holds only what the client sends.

## Bound value sets

Coded fields bind to Care value sets through `ValueSetBoundCoding[<slug>]`. Every write checks the `code` against the value set and refuses a code outside it.

| Field | Value set slug | SNOMED CT scope |
| - | - | - |
| `medication`, `status_reason` | `system-medication` | `<< 763158003` Medicinal product |
| `dosage.site` | `system-body-site` | is-a `91723000` |
| `dosage.route` | `system-route` | is-a `284009009` |
| `dosage.method` | `system-administration-method` | is-a `736665006` |

The administration spec imports only these four value sets. The directory also defines Medication Not Given Reason (`system-medication-not-given`), which no medication spec binds.

Care checks codes against the copy of each value set in the database. A deployment can change that copy after it is loaded, so the codes allowed at a deployment can differ from the scope above.

## Related models

```
administered_product → FK ProductKnowledge (CASCADE, nullable)

patient              → FK Patient (CASCADE)

encounter            → FK Encounter (CASCADE, nullable; required by the API)

request              → FK MedicationRequest (CASCADE, nullable; required by the API)
```

These links are `CASCADE`. The rule acts only when a row is removed from the database. The API delete and the model `delete()` are soft and do not trigger it, so deleting a medication request through the API keeps its administrations.

## Resource specs (API schema)

Resource specs never copy foreign keys automatically. The shared spec also lists `patient`, `encounter`, `request` and `administered_product` in `__exclude__`; the update spec lists `patient`, `encounter` and `request`.

| Spec class | Role | Notes |
| - | - | - |
| `BaseMedicationAdministrationSpec` | shared | `id`, `status`, `status_reason`, `category`, `medication`, `authored_on`, `occurrence_period_start`, `occurrence_period_end`, `recorded`, `encounter`, `request`, `performer`, `dosage`, `note` |
| `MedicationAdministrationSpec` | write · create | Adds `administered_product`. Holds the validators |
| `MedicationAdministrationUpdateSpec` | write · update | Only `status` (required), `note` and `occurrence_period_end` |
| `MedicationAdministrationReadSpec` | read · list and detail | Adds `created_by`, `updated_by`, `created_date`, `modified_date`. Returns `encounter` and `request` as ids and expands `administered_product` |
| `Dosage` | nested | The shape of `dosage` |
| `MedicationAdministrationPerformer` | nested | One entry of `performer` |

### Validation rules

* The `encounter` must exist ("Encounter not found").
* The `request` must exist ("Medication Request not found"). That is the only check on it.
* `medication` and `administered_product` cannot both be set ("Medication and administered product cannot be set at the same time").
* Each `performer.actor` must be an existing user ("User not found").
* Coded fields are checked against their value sets.
* Required on create: `status`, `occurrence_period_start`, `encounter` and `request`.
* The API sets no rule on status changes. Any status can follow any status, including a change back from `entered_in_error`.

### Server-maintained behaviour

* On create only, Care resolves the encounter, copies `patient` from it, links the request by its id, and resolves `administered_product` when it is sent.
* Every create and update also writes a questionnaire response with structured type `medication_administration` and submit type `CREATE` or `UPDATE`.

## Methods & save behaviour

* The model defines no `save()` or `delete()` override.
* Fields left at their spec default are not written (`exclude_defaults=True`). So an update cannot clear a field by sending its default, for example `"note": null`.
* An update body loses `id`, `external_id`, `patient` and `encounter` before validation.
* Delete is soft: Care sets `deleted` and keeps the row. The default manager hides deleted rows.
* Recording an administration does not change stock or billing, even with `administered_product`.

## API integration notes

### Endpoints

All paths are under `/api/v1/`.

| Method | Path | Action |
| - | - | - |
| `GET` | `patient/{patient_id}/medication/administration/` | List |
| `POST` | `patient/{patient_id}/medication/administration/` | Create |
| `GET` | `patient/{patient_id}/medication/administration/{id}/` | Retrieve |
| `PUT`, `PATCH` | `patient/{patient_id}/medication/administration/{id}/` | Update. Both use `MedicationAdministrationUpdateSpec` |
| `DELETE` | `patient/{patient_id}/medication/administration/{id}/` | Soft delete |
| `POST` | `patient/{patient_id}/medication/administration/upsert/` | Batch create or update, see [Upsert](#upsert) |

### Authorization

"Clinical write" below means "Update Encounter related clinical data" held in one of the encounter's departments or its current location's departments. The encounter status must not be Completed, Cancelled, Entered in Error or Discontinued.

| Action | Requirement |
| - | - |
| List | "Can view clinical data about patients" on the patient in the URL. Failing that, with `?encounter=`: "Can Read encounter related clinical data" on that encounter. Else 403 "Permission denied to user". The `encounter` filter then limits the results to that encounter |
| Retrieve | The read check of the list runs first |
| Create, upsert items without `id` | Clinical write on the encounter in the body. Else 403 "You do not have permission to update encounter" |
| Update, delete | The read check of the list runs first. Then clinical write on the administration's encounter |

An encounter's departments are the departments it is linked to, their parent departments, and the facility's Administration department.

"Can view clinical data about patients" counts the user's roles on the patient. These come from the departments of the patient's open encounters (and of their current locations), the patient's organizations, and a direct patient link. Closed encounters do not count.

Default role lists from the permission definitions:

| Permission | Default roles |
| - | - |
| "Update Encounter related clinical data" | Doctor, Nurse, Facility Admin |
| "Can Read encounter related clinical data" | Doctor, Nurse, Facility Admin |
| "Can view clinical data about patients" | Staff, Doctor, Nurse, Facility Admin |

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 screen that links users to departments does not offer. The lists above leave it out.

The Pharmacist role holds none of these by default.

A permission refusal is HTTP 403 with the message in `detail`. A validation error is HTTP 400 with an `errors` list. A missing record is HTTP 404 with type `object_not_found`.

### Filters and ordering

| Parameter | Meaning |
| - | - |
| `encounter` | Encounter id |
| `request` | Medication request id |
| `occurrence_period_start` | Range of start times |
| `occurrence_period_end` | Range of end times |
| `status` | Comma-separated statuses |
| `ordering` | `created_date` or `modified_date`. Without it, newest record first |

Lists are paginated with `limit` and `offset` (default 14, at most 200) and return `count` and `results`.

### Upsert

`POST .../upsert/` takes `{"datapoints": [...]}`. An item with `id` is an update and an item without one is a create; each runs the normal checks.

* More than `MAX_DATAPOINTS_PER_UPSERT` items (100 by default, set per deployment by environment variable) fails with "Too many datapoints provided". An empty list fails with "No datapoints provided".
* The upsert is all or nothing. If any item fails, every item is rolled back and the response is HTTP 400 with one result per item.

### Notes

* The Care frontend calls only the list and the upsert for administrations. No screen deletes an administration.
* The "Administer Medicines" panel saves all ticked medicines in one upsert, so one failing item stops all of them.
* The Care frontend never sends `performer` or `status_reason`.
* Send coded fields as `Coding` objects with a `code` from the bound value set. Free strings and codes outside the set are refused.
* Send `encounter` and `request` as ids. Care copies `patient` from the encounter.
* No deployment setting is specific to this resource.

## Related

* Concept: [Medication administration](https://docs.ohc.network/concepts/medications/medication-administration.md)
* Reference: [Medication request](https://docs.ohc.network/references/medications/medication-request.md)
* Reference: [Medication dispense](https://docs.ohc.network/references/medications/medication-dispense.md)
* Reference: [Medication statement](https://docs.ohc.network/references/medications/medication-statement.md)
* Reference: [Product Knowledge](https://docs.ohc.network/references/definitions/product-knowledge.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [Patient](https://docs.ohc.network/references/clinical/patient.md)
* Reference: [User](https://docs.ohc.network/references/access-governance/user.md)
* Reference: [Base model](https://docs.ohc.network/references/foundation/base-model.md)
* FHIR: [MedicationAdministration](https://hl7.org/fhir/medicationadministration.html)
* Source: [medication\_administration.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/medication_administration.py) · [administration/spec.py](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/medication/administration/spec.py) · [medication value sets](https://github.com/ohcnetwork/care/tree/develop/care/emr/resources/medication/valueset)
