Skip to main content
Version: 3.1

Medication dispense

Technical reference for the MedicationDispense module in Care EMR. For what a medication dispense is in the product, see the Medication dispense concept.

A medication dispense records a quantity of one inventory item given out for a patient in an encounter. An inventory item is the stock of one product at one location. Saving a dispense reduces that stock, and it can create a charge item.

Source:

The Django model stores dosage_instruction and substitution as JSON columns. The Pydantic resource specs define their shape, the enums, the validation and the read and write schemas. Enum values use underscores, such as in_progress.

Models​

ModelPurpose
MedicationDispenseOne dispense: a quantity of one inventory item for a patient in an encounter
DispenseOrderGroups dispenses for one patient at one location. See the Dispense order reference

Both extend EMRBaseModel. It supplies external_id, created_date, modified_date, the soft-delete flag deleted, created_by, updated_by, history and meta.

MedicationDispense 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​

FieldModel typeSpec typeRequired (API)Notes
statusCharField(100)MedicationDispenseStatusYesA dispense in a cancelling status accepts no more updates. See status values
not_performed_reasonCharField(100), nullableMedicationDispenseNotPerformedReason | NoneNoCan change after create
categoryCharField(100), nullableMedicationDispenseCategory | NoneNoCan change after create

Timing & instructions​

FieldModel typeSpec typeRequired (API)Notes
when_preparedDateTimeField, nullabledatetime | NoneNoCan change after create
when_handed_overDateTimeField, nullabledatetime | NoneNoCan change after create
noteTextField, nullablestr | NoneNoCan change after create
dosage_instructionJSONField, default [], nullablelist[DosageInstruction], default []NoThe DosageInstruction of medication requests. Can change after create
substitutionJSONField, default {}, nullableMedicationDispenseSubstitution | NoneNoAll three keys are required when sent. Can change after create

Quantities​

FieldModel typeSpec typeRequired (API)Notes
quantityDecimalField(20, 6)Decimal, whole number of at least 1YesChecked against the inventory item's stock on create. Fixed
days_supplyDecimalField(20, 6), nullableDecimal | None, whole numberNoAccepted on create, but no read returns it. Fixed

Relationships​

FieldModel typeSpec typeNotes
encounterFK → Encounter, CASCADEUUID4, requiredpatient is copied from it. Fixed
patientFK → Patient, CASCADENot acceptedServer-set from the encounter
locationFK → FacilityLocation, CASCADEUUID4, requiredThe dispensing location. Must be in the encounter's facility, or Care answers 404. The write permission is checked here. Fixed
itemFK → InventoryItem, CASCADEUUID4, requiredMust be at a location of the encounter's facility, or Care answers 404. Fixed
authorizing_requestFK → MedicationRequest, SET_NULL, nullableUUID4 | NoneMust be on the same encounter, or Care answers 404. Its status is not checked. Fixed. Care clears it on some cancellations, see Methods & save behaviour
charge_itemFK → ChargeItem, CASCADE, nullableRead onlyCreated by Care when the product has a charge item definition
orderFK → DispenseOrder, CASCADE, nullableUUID4 | NoneAn existing order. Can change after create. See Dispense order

Two more write fields are not columns. fully_dispensed lives only for the save, and create_dispense_order creates or finds an order inline.

Enum values​

MedicationDispenseStatus values​

Value
preparation
in_progress
cancelled
on_hold
completed
entered_in_error
stopped
declined

MEDICATION_DISPENSE_CANCELLED_STATUSES lists cancelled, entered_in_error, stopped and declined. A dispense in one of these is final, and its quantity no longer counts against stock.

Among the other statuses there is no transition rule. A completed dispense can go back to in_progress.

MedicationDispenseNotPerformedReason values​

Value
outofstock
washout
surg
sintol
sddi
sdupther
saig
preg

The backend holds only these codes, with no labels. The field is a plain enum, not a bound Coding, and no code relates it to the system-medication-not-given value set.

MedicationDispenseCategory values​

Value
inpatient
outpatient
community
discharge

SubstitutionType values​

Used in substitution.substitution_type. Codes only.

Value
E
EC
BC
G
TE
TB
TG
F
N

SubstitutionReason values​

Used in substitution.reason. Codes only.

Value
CT
FP
OS
RR

JSON field shapes​

MedicationDispenseSubstitution shape​

substitution = {
was_substituted: bool # required
substitution_type: SubstitutionType # required
reason: SubstitutionReason # required
}

DosageInstruction shape​

dosage_instruction reuses the DosageInstruction spec of medication requests. Its fields, sub-types and bound value sets are on the Medication request reference.

DispenseOrder​

A dispense order groups dispenses for one patient at one location. Its fields, statuses, rules and API are on the Dispense order reference.

MedicationDispense.order → FK DispenseOrder (CASCADE, nullable)

Charge item​

When the dispensed product has a charge item definition, Care applies it and links the result in charge_item.

  • The charge item is for the patient and the encounter, for the dispensed quantity.
  • Its status is billable, on the patient's default account at the facility. Care creates that account when the patient has no active, open account there.
  • It records that it comes from this dispense (service_resource medication_dispense, with the dispense id).
  • When the medication request has a requester, the requester is the charge item's performer.
  • Care checks no billing permission for this.

Resource specs (API schema)​

Resource specs never copy foreign keys automatically. The shared dispense spec also lists patient, encounter, authorizing_request, item and location in __exclude__, and the hooks set them.

Spec classRoleNotes
BaseMedicationDispenseSpecsharedstatus, not_performed_reason, category, when_prepared, when_handed_over, note, dosage_instruction, substitution
MedicationDispenseWriteSpecwrite · createAdds encounter, location, item (required), authorizing_request, quantity (required), days_supply, fully_dispensed, order and create_dispense_order
MedicationDispenseUpdateSpecwrite · updateThe shared fields plus fully_dispensed and order
MedicationDispenseReadSpecread · listExpands item, charge_item, location, authorizing_request and order. Adds quantity, created_date and modified_date. No created_by, updated_by or days_supply
MedicationDispenseRetrieveSpecread · detailAdds encounter
MedicationDispenseSubstitutionnestedThe shape of substitution
CreateDispenseOrderwrite · nestedInline order creation, see below

CreateDispenseOrder​

CreateDispenseOrder {
name: str | None
note: str | None
alternate_identifier: str # required
status: draft | in_progress # default draft
}
  • Care looks for an order with the same alternate_identifier, patient and location. A match joins the dispense to it.
  • A match that is not draft or in_progress fails with "Prescription is not active".
  • With no match, Care creates an order for the patient at the dispensing location, in the encounter's facility. It takes the given status, name and note, and records the user as its creator.
  • An order cannot be created as completed this way.
  • Sending both order and create_dispense_order fails with "Cannot have both dispense order and create_dispense_order".

Methods & save behaviour​

The model defines no save() or delete() override. The behaviour below lives in the specs and the viewset.

On create​

  • Care locks the order first and refuses an abandoned or entered_in_error order ("Dispense order is abandoned or entered in error"). An order id that does not exist fails before this, with HTTP 404.
  • Care then locks the inventory item. If another request holds it, Care answers HTTP 423 "The resource you are trying to access is locked".
  • A quantity above the item's current stock fails with "Inventory item does not have enough stock". Care checks the quantity only. It does not refuse an expired or inactive lot.
  • When the product has a charge item definition, Care creates the charge item, see Charge item.
  • Care recalculates the item's stock. Dispenses in any status except the cancelling ones count against it.
  • With an authorizing_request, fully_dispensed: true sets its dispense_status to complete and false sets partial. Without the flag, the request stays as it is.
  • A dispense created directly in a cancelling status still needs enough stock and still gets a charge item, but it does not reduce stock.
  • Care does not check the encounter's status, so a dispense can be recorded on a closed encounter.

On update​

  • A dispense in a cancelling status refuses any update ("No updates allowed on cancelled medication dispense").
  • Care locks the old and the new order. Neither can be abandoned or entered_in_error. If another request moved the dispense to another order meanwhile, Care answers HTTP 423.
  • A change into a cancelling status on a dispense with a charge item cancels that charge item. Care takes it off its draft invoice, recalculates the invoice totals and sets the charge item to aborted.
  • If the charge item is on an invoice that is not a draft, the update fails with "Cannot cancel charge item in a non-draft invoice".
  • In the same case, Care sets the request's dispense_status to incomplete and clears authorizing_request. Only a dispense with a charge item gets this reset.
  • Care then recalculates the item's stock and applies fully_dispensed to the request again.

Order cancellation​

Moving a dispense order to abandoned or entered_in_error cancels its dispenses, their charge items and their request links. See the Dispense order reference.

API integration notes​

Endpoints​

All paths are under /api/v1/. Dispenses are not nested under a patient or a facility.

MethodPathAction
GETmedication/dispense/List. Needs location or encounter
POSTmedication/dispense/Create
GETmedication/dispense/{id}/Retrieve
PUT, PATCHmedication/dispense/{id}/Update. Both use MedicationDispenseUpdateSpec
POSTmedication/dispense/upsert/Batch create or update
GETmedication/dispense/summary/Number of dispenses per encounter. Needs location or encounter

There is no delete.

Authorization​

ActionRequirement
Create, upsert items without id"Write Medication Dispense" in the dispensing location's departments. No encounter permission is needed. Else 403 "You do not have permission to write medication dispenses"
Update"Write Medication Dispense" for the dispense's own location
Retrieve"Medication Dispense Read" for its location, or "Medication Dispense Read" on its encounter. Else 403 "You do not have permission to read medication dispense"
List or summary with ?location="Medication Dispense Read" for that location. include_children=true adds the locations under it
List or summary with ?encounter="Medication Dispense Read" on that encounter. Returns only that encounter's dispenses
List or summary with neitherHTTP 400 "Location or encounter is required"

A location's departments are its parent location's departments, the departments it is linked to and their parents, and the facility's Administration department. An encounter-level check uses the encounter's departments and its current location's.

Listing the lots and stock of a location needs "Can Read Inventory Item" in that location's departments.

Default role lists from the permission definitions:

PermissionDefault roles
"Medication Dispense Read"Facility Admin, Staff, Doctor, Nurse, Pharmacist
"Write Medication Dispense"Facility Admin, Staff, Doctor, Nurse, Pharmacist
"Can Read Inventory Item"Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist

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.

A permission refusal is HTTP 403 with the message in detail. A business-rule refusal is HTTP 400 with errors: [{type: "validation_error", msg}]. A missing record is HTTP 404 with type object_not_found.

Filters and ordering​

ParameterMeaning
locationDispensing location. Also selects the location read check
include_childrenWith location, also dispenses at the locations under it
encounterEncounter id. Also selects the encounter read check
status, exclude_statusComma-separated statuses to keep or to leave out
categoryCategory
patientPatient id
itemInventory item id
authorizing_requestMedication request id
authorizing_prescriptionPrescription of the medication request
orderDispense order id
orderingcreated_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 medication/dispense/upsert/ takes {"datapoints": [...]}, at most 100 by default. An item with id is an update and an item without one is a create. All items run in one transaction: if any fails, nothing is saved and the response is HTTP 400.

Medication returns​

A medication return is not a change to the dispense. Care 3.1 records it as a delivery order with a patient, at facility/{facility_id}/order/delivery/. See the Medication return and Supply delivery concepts.

  • A returned item names a product and a quantity. Nothing links it to the dispense it reverses.
  • A returned item that is completed adds its quantity to stock at the return's destination.
  • Completing the return creates a refund invoice on the patient's default account.
  • Returns use "Can Read Medication Returns" and "Can Write Medication Returns" at the destination, new in 3.1. By default, Facility Admin is the only role given in a facility that holds the write permission.
  • A return list needs patient_return=true and a destination.

Notes​

  • Send item as an inventory item id. There is one inventory item per product per location.
  • quantity and days_supply take whole numbers on write, though the columns store six decimal places.
  • charge_item is server-managed: Care creates it on create and cancels it with the dispense or its order.
  • fully_dispensed sets the request's dispense_status. Care does not check the request's status before a dispense.
  • The Care frontend's encounter Dispense drawer creates the order inline with its dispenses, then sends a separate update that sets the order to completed.