# 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](https://docs.ohc.network/references/definitions/questionnaire.md).

Both use the same action JSON and the same evaluator.

**Source:**

* Model: [`care/emr/models/action.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/action.py)
* Specs: [`care/emr/resources/action/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/action/spec.py)
* Viewsets: [`care/emr/api/viewsets/action.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/action.py) · [`action_base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/action_base.py)
* Evaluator: [`care/action_evaluator/`](https://github.com/ohcnetwork/care/tree/develop/care/action_evaluator)
* Registries: [`care/emr/registries/actions/`](https://github.com/ohcnetwork/care/tree/develop/care/emr/registries/actions)

## Models

| Model | Purpose |
| - | - |
| `Action` | A named action configuration: a list of actions for one context, for the instance or for one facility |

It extends [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md), which gives `external_id`, the audit fields, soft delete through `deleted`, `history` and `meta`.

## `Action` fields

| Field | Type | Spec type | Notes |
| - | - | - | - |
| `name` | `CharField(255)` | `str`, max 254 | Required on create. Optional on update |
| `description` | `TextField` | `str` | Optional in the spec, not nullable in the model |
| `action_context` | `CharField(255)` | `ActionContextOptions` | Required on create. Write once: the update spec has no `action_context` |
| `actions` | `JSONField` | `list[dict]` | Required on create. Optional on update. Each item is an action (see [Action JSON](#action-json)). The spec does not validate the items. Care validates them when it runs them |
| `performable` | `BooleanField`, default `True` | `bool` | Required on create. Write once. `true` lets a client run the configuration on demand through `execute_action` |
| `facility` | `FK → Facility`, `CASCADE`, nullable | `UUID4` or `null` | Create only. `null` is an instance configuration. The API refuses a create with a facility (see [API integration notes](#api-integration-notes)). Read back as a `FacilityReadSpec` object |
| `organization_cache` | `ArrayField[int]`, default `[]` | — | Not in any spec. No code writes it at ddfd840 |
| `internal_organization_cache` | `ArrayField[int]`, default `[]` | — | Not in any spec. No code writes it at ddfd840 |

### `ActionContextOptions` values

| Value | Where Care runs it |
| - | - |
| `APPOINTMENT` | `create_appointment` on a slot, and `execute_action` on an appointment |
| `PATIENT` | Accepted 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 type | Runs for | Fields |
| - | - | - |
| `Appointment` | Action configurations (`APPOINTMENT`) | `patient` → `Patient` |
| `EncounterQuestionnaire` | Questionnaire with any subject type except patient | `patient` → `Patient`, `encounter` → `Encounter` |
| `PatientQuestionnaire` | Questionnaire with subject type patient | `patient` → `Patient` |
| `Patient` | Reached through `patient` | `age`, `gender`, `name`, `phone_number`, `date_of_birth` (ISO date or `null`), `year_of_birth`, `blood_group`, `deceased` (`true` when `deceased_datetime` is set) |
| `Encounter` | Reached through `encounter` | `status`, `encounter_class`, `priority` |

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

### Instructions

| Slug | Instruction type | Acts on | Inputs | Output |
| - | - | - | - | - |
| `show_message` | `NOTIFY` | `EncounterQuestionnaire` | `message: str` | `{ message }` |
| `set_encounter_priority` | `PERFORMED` | `Encounter` | `priority`: an encounter priority value | `{ performed, priority, message }` |
| `tag_encounter` | `PERFORMED` | `Encounter` | `tag`: a tag configuration UUID for encounters | `{ performed, tag, message }` |
| `tag_patient` | `PERFORMED` | `Patient` | `tag`: a tag configuration UUID for patients | `{ performed, tag, message }` |
| `logging` | `NOTIFY` | `Appointment` | `message: str` | The 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)

| Spec | Role | Fields |
| - | - | - |
| `BaseActionConfigurationSpec` | Shared base | `id`, `name` (max 254), `description`, `actions` |
| `ActionConfigurationWriteSpec` | write · create | Base fields plus `performable`, `action_context`, `facility` |
| `ActionConfigurationUpdateSpec` | write · update | `name`, `description`, `actions`, all optional. No `performable`, `action_context` or `facility` |
| `ActionConfigurationReadSpec` | read · list | Base fields plus `performable`, `action_context`, `facility` (a `FacilityReadSpec` object or `null`) |
| `ActionConfigurationRetrieveSpec` | read · detail | List 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

| Trigger | Endpoint | Actions | Response |
| - | - | - | - |
| Staff book an appointment from a slot | `POST /api/v1/facility/{facility_external_id}/slots/{id}/create_appointment/` | Every `APPOINTMENT` configuration of the instance and of the slot's facility | The booking, with `_actions`: one list of instruction results for each configuration |
| A client runs one configuration | `POST /api/v1/facility/{facility_external_id}/appointments/{id}/execute_action/` with `{ "action": "<uuid>" }` | One `APPOINTMENT` configuration with `performable = true` | A list of instruction results |
| A user submits a questionnaire | `POST /api/v1/questionnaire/{id}/submit/` | The questionnaire's `actions` | The 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.

## Related

* Reference: [Questionnaire](https://docs.ohc.network/references/definitions/questionnaire.md)
* Reference: [Booking](https://docs.ohc.network/references/scheduling/booking.md)
* Reference: [Tag config](https://docs.ohc.network/references/platform/tag-config.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [Patient](https://docs.ohc.network/references/clinical/patient.md)
* Source (model): [action.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/action.py)
* Source (evaluator): [care/action\_evaluator on GitHub](https://github.com/ohcnetwork/care/tree/develop/care/action_evaluator)
