Skip to main content
Version: 3.1

Action

Technical reference for configurable actions in Care EMR: the Action model (an action configuration), the action JSON that questionnaires also store, and the evaluator that runs it. An action is a condition and a list of instructions. When the condition is true, Care runs the instructions in order, for example to show a message or to tag a patient.

Two places store actions:

  • An action configuration (Action row) holds actions for a context. Care runs the configurations for APPOINTMENT when staff book an appointment from a slot.
  • A questionnaire holds actions in its actions field. Care runs them when a user submits the questionnaire through its submit action. See Questionnaire.

Both use the same action JSON and the same evaluator.

Source:

Models​

ModelPurpose
ActionA named action configuration: a list of actions for one context, for the instance or for one facility

It extends EMRBaseModel, which gives external_id, the audit fields, soft delete through deleted, history and meta.

Action fields​

FieldTypeSpec typeNotes
nameCharField(255)str, max 254Required on create. Optional on update
descriptionTextFieldstrOptional in the spec, not nullable in the model
action_contextCharField(255)ActionContextOptionsRequired on create. Write once: the update spec has no action_context
actionsJSONFieldlist[dict]Required on create. Optional on update. Each item is an action (see Action JSON). The spec does not validate the items. Care validates them when it runs them
performableBooleanField, default TrueboolRequired on create. Write once. true lets a client run the configuration on demand through execute_action
facilityFK → Facility, CASCADE, nullableUUID4 or nullCreate only. null is an instance configuration. The API refuses a create with a facility (see API integration notes). Read back as a FacilityReadSpec object
organization_cacheArrayField[int], default []—Not in any spec. No code writes it at ddfd840
internal_organization_cacheArrayField[int], default []—Not in any spec. No code writes it at ddfd840

ActionContextOptions values​

ValueWhere Care runs it
APPOINTMENTcreate_appointment on a slot, and execute_action on an appointment
PATIENTAccepted by the spec. No viewset runs PATIENT configurations at ddfd840

Action JSON​

Each item of Action.actions and of Questionnaire.actions has this shape (care/action_evaluator/base.py):

Action {
condition: str # an expression. An empty string never runs
instructions: list[Instruction] # default []
}

Instruction {
slug: str # a registered instruction. Slugs that start with "i_" are reserved
params: dict # the instruction's inputs
context: str # the context path the instruction acts on, e.g. "self", "patient", "encounter"
}

Conditions and variables​

  • Care evaluates condition with the evalidate safe-expression library: its base model plus f-strings and multiplication. A true result runs the instructions.
  • A variable is a dotted path that the context registry resolves from the record, for example patient.age from an appointment or encounter.priority from an encounter questionnaire response.
  • Questionnaire answers are variables with the q_ prefix. Care builds them from the submitted response. The i_ prefix is reserved.
  • A params value that is a string wrapped in {{ and }} is an expression. Care evaluates it and passes the result to the instruction.
  • A variable that no context resolves raises an error, and the request fails.

Contexts​

The context type depends on what runs the action. Fields resolve from that context, and some fields move to another context.

Context typeRuns forFields
AppointmentAction configurations (APPOINTMENT)patient → Patient
EncounterQuestionnaireQuestionnaire with any subject type except patientpatient → Patient, encounter → Encounter
PatientQuestionnaireQuestionnaire with subject type patientpatient → Patient
PatientReached through patientage, gender, name, phone_number, date_of_birth (ISO date or null), year_of_birth, blood_group, deceased (true when deceased_datetime is set)
EncounterReached through encounterstatus, encounter_class, priority

The Appointment context also registers a dynamic test field that returns test1234 for any name.

Instructions​

SlugInstruction typeActs onInputsOutput
show_messageNOTIFYEncounterQuestionnairemessage: str{ message }
set_encounter_priorityPERFORMEDEncounterpriority: an encounter priority value{ performed, priority, message }
tag_encounterPERFORMEDEncountertag: a tag configuration UUID for encounters{ performed, tag, message }
tag_patientPERFORMEDPatienttag: a tag configuration UUID for patients{ performed, tag, message }
loggingNOTIFYAppointmentmessage: strThe inputs. Writes them to the server log

InstructionType values: REDIRECT, PERFORMED, NOTIFY, TEXT, VALIDATE. The registered instructions use only NOTIFY and PERFORMED.

Instruction behaviour:

  • set_encounter_priority returns performed: false when the record has no encounter or the encounter already has that priority.
  • tag_encounter and tag_patient skip a tag that is already set. They return performed: false with the error message when the tag no longer exists, when there is nothing to tag, or when the user cannot apply the tag. A patient tag goes to the facility's tag set for a facility tag, or to the instance set for an instance tag.
  • Instructions run as the user who made the request.

Each instruction result has this shape:

{
slug: str
instruction_type: str
results: dict # the instruction's output
}

Authorization of action JSON​

When a client creates or updates a questionnaire with actions, Care calls each instruction's authorize(). An unknown slug fails. set_encounter_priority checks that priority is a valid value. The tag instructions check that the tag exists, that it is for the right resource, and that the user holds can_apply_tag_config for it.

The action configuration viewset does not call authorize() on create or update.

Resource specs (API schema)​

SpecRoleFields
BaseActionConfigurationSpecShared baseid, name (max 254), description, actions
ActionConfigurationWriteSpecwrite · createBase fields plus performable, action_context, facility
ActionConfigurationUpdateSpecwrite · updatename, description, actions, all optional. No performable, action_context or facility
ActionConfigurationReadSpecread · listBase fields plus performable, action_context, facility (a FacilityReadSpec object or null)
ActionConfigurationRetrieveSpecread · detailList fields plus created_date, modified_date, created_by, updated_by

Methods & save behaviour​

  • save() deletes the cached action lists for the row's context: the instance list, and the facility list when the row has a facility. Soft delete calls save(), so it also clears the cache.
  • get_actions_for_context(context, facility) returns the actions lists of the instance configurations for the context, then those of the facility. Each list is cached for 24 hours under action:cache:context:{context}:facility:{facility}.
  • These lists include configurations with performable = false. performable only controls execute_action.

Where actions run​

TriggerEndpointActionsResponse
Staff book an appointment from a slotPOST /api/v1/facility/{facility_external_id}/slots/{id}/create_appointment/Every APPOINTMENT configuration of the instance and of the slot's facilityThe booking, with _actions: one list of instruction results for each configuration
A client runs one configurationPOST /api/v1/facility/{facility_external_id}/appointments/{id}/execute_action/ with { "action": "<uuid>" }One APPOINTMENT configuration with performable = trueA list of instruction results
A user submits a questionnairePOST /api/v1/questionnaire/{id}/submit/The questionnaire's actionsThe response, with _actions: a list of instruction results
  • create_appointment books the appointment and runs the actions in one transaction. If an action raises an error, Care does not book the appointment.
  • execute_action needs update access to the appointment. It does not check the configuration's facility.
  • Bookings through the patient OTP slot endpoint, and reschedule, cancel and update on appointments, do not run actions. The questionnaire submit_resource action does not run actions.
  • care_fe offers actions only for patient and encounter questionnaires. The backend runs the actions of any questionnaire that has them, with the EncounterQuestionnaire context for every subject type except patient.

API integration notes​

  • Endpoint: /api/v1/action_configuration/. The viewset allows create, list, retrieve, update, delete (soft) and upsert.
  • Create, update and delete need a superuser. Care refuses a create with a facility, and an update or delete of a configuration that has a facility, for every user. So in 3.1 all configurations are instance configurations.
  • List and retrieve have no permission check beyond sign-in, and no filters.
  • GET /api/v1/action_configuration/contexts/ returns { "contexts": [...] }, the registered context types.
  • GET /api/v1/action_configuration/instructions/ returns { "instructions": [...] }. Each item has slug, input_schema and output_schema (JSON Schema), context and instruction_type. The tag inputs carry x-care-picker: tag_config and x-care-resource in their schema.
  • GET /api/v1/action_configuration/fields/ returns { "fields": [...] }. Each item has context_type, field, evaluation (static) and, for a field that moves to another context, target_context_type.
  • The three registry endpoints cache their output in the server process.