# Care team

Technical reference for the encounter care team in Care EMR. See the [care team concept](https://docs.ohc.network/concepts/clinical/care-team.md) for the plain-language view.

**Source:**

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

The care team has no model of its own. It is stored on the `Encounter` model as a `JSONField`, and its real shape lives in the Pydantic specs. The write path is a dedicated action on the encounter viewset, not the encounter create or update schema.

## Models

| Model | Purpose |
| - | - |
| `Encounter` | Owns the care team through the `care_team` and `care_team_users` fields |

`Encounter` extends [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md).

## `Encounter` care team fields

| Field | Type | Notes |
| - | - | - |
| `care_team` | `JSONField` | Default `{}`. After a save through the care team endpoint, a list of `{ "user_id": int, "role": Coding }` entries in team order. In the `__exclude__` list of the encounter specs, so the encounter create and update schemas cannot write it |
| `care_team_users` | `ArrayField(IntegerField)` | Default `[]`. Cache of the internal user ids in `care_team`, rebuilt on every save while `care_team` is a list. Platform-maintained |

The stored `user_id` is the internal integer id of `User`. The API takes the user's `external_id` (UUID) on write, and returns it as the member's `id` on read.

### Stored shape

Keys of `role` that are left at their default (`None`) are not stored.

```
care_team: [

  {

    "user_id": int,                                       # internal User id

    "role": Coding { system?, version?, code, display? }  # defaults left out

  }

]
```

## Related models

The care team links each entry to a `User` by internal id, in JSON, with no foreign key. Three other models store lists with the same `user_id` and `role` keys.

```
Encounter.care_team[].user_id  ──> User.id   (internal id, no foreign key)

Schedule.care_team             list of { user_id, role }   default care team of a schedule

ReferralAvailability.care_team list of { user_id, role }   care team of a referral destination

Referral.assignees             list of { user_id, role }   copied from ReferralAvailability.care_team
```

A schedule's care team reaches an encounter through the frontend. When the frontend creates an encounter from an appointment on that schedule, the create form then sends the schedule's members to `set_care_team_members`.

A referral destination's care team is copied to each new referral's `assignees`. It does not change the encounter's care team.

## Resource specs (API schema)

| Spec | Role |
| - | - |
| `EncounterCareTeamMemberSpec` | write · one member, defined in `care_team.py`: `user_id: UUID4`, `role: ValueSetBoundCoding[system-practitioner-role-code]` |
| `EncounterCareTeamMemberWriteSpec` | write · the full replacement list: `members: list[EncounterCareTeamMemberSpec]` |
| `EncounterListSpec` | read · list. Serializes `care_team` as `[{ "member": UserSpec, "role": Coding }]` |
| `EncounterRetrieveSpec` | read · detail. Same `care_team` serialization as the list spec |

On read, each member is expanded from the cached `UserSpec` for the stored `user_id`. The list order of `care_team` is preserved, and the frontend shows the first entry as the primary member.

### `PRACTITIONER_ROLE_VALUESET`

`role` is bound to the system value set "Practitioner Role", slug `system-practitioner-role-code`. It composes two SNOMED CT `is-a` filters:

| Concept | Name |
| - | - |
| `223366009` | Healthcare professional |
| `224930009` | Services |

The code holds only the concept ids. The names are the SNOMED CT International Edition names, as returned by Care's default terminology server.

Validation runs when the body is parsed. It takes the first value set with the slug (`ValuesetDatabaseModel.objects.filter(slug=slug).first()`) and looks the code up in it.

A code that is not in that value set fails with "Code does not exist in the valueset". If no value set has the slug, validation fails with "Valueset does not exist in care, Resync valuesets".

The lookup filters on the slug only. A slug can exist more than once: instance-wide, and again per facility, per department or per user.

The role picker in the frontend asks for the slug with the facility. The backend then returns the user's saved preference for that slug in that facility, if one exists. Otherwise it returns a facility value set or the instance-wide one.

### Other specs that use `EncounterCareTeamMemberSpec`

| Spec | Field | Holds |
| - | - | - |
| `ScheduleWriteSpec` (base of `ScheduleCreateSpec` and `ScheduleUpdateSpec`) | `care_team` | The default care team of a schedule |
| `ReferralAvailabilityCreateSpec`, `ReferralAvailabilityUpdateSpec` | `care_team` | The care team of a referral destination |
| `ReferralUpdateSpec` · `ReferralAssigneesWriteSpec` | `assignees` · `members` | The assignees of a referral |

These paths accept only active users, and refuse other users with "Care team user not found or inactive". Schedule members must also belong to the schedule's facility ("Care team members must belong to the schedule facility").

The encounter endpoint makes neither check. It accepts any existing user id.

## Methods & save behaviour

* `Encounter.save()` calls `sync_care_team_users_cache()` on every save. It rebuilds `care_team_users` from the `user_id` of each entry, and uses `-1` for an entry without one.
* `sync_care_team_users_cache()` rebuilds the cache only when `care_team` is a list. The model default is a dict, so an encounter with no saved care team keeps an empty cache.
* `set_care_team_members` sets `updated_by` to the signed-in user, and saves with `update_fields=["care_team", "care_team_users", "updated_by", "modified_date"]`.

## API integration notes

### Endpoint

* Write endpoint: `POST /api/v1/encounter/{external_id}/set_care_team_members/`, a detail action on `EncounterViewSet`. The body is `EncounterCareTeamMemberWriteSpec`.
* The response is HTTP 200 with an empty body `{}`. Only the API schema declares `EncounterRetrieveSpec` as the response. Read the encounter again to get the new team.
* The write is a full replacement. Send the complete member list on every call.
* To remove a member, send the list without that member. To change the primary member, send the list with that member first. An empty list clears the team.
* The endpoint has no version or concurrency check. Each call replaces what is stored, including changes that another client saved after you read the encounter.

### Order of checks and errors

Before step 1, the default permission class `IsAuthenticated` refuses a request with no signed-in user. The encounter viewset adds no other permission class.

The endpoint runs these checks in order and stops at the first failure. Steps 4 to 6 run once for each member, in list order.

| Step | Check | On failure |
| - | - | - |
| 1 | The body parses as `EncounterCareTeamMemberWriteSpec`: `members` is present, each `user_id` is a UUID4, each `role` is a `Coding` (extra keys refused) whose code is in the value set | 400 with `{"errors": [...]}`, for example "Code does not exist in the valueset" |
| 2 | The encounter exists. The lookup by `external_id` applies no access filter for this action | 404 |
| 3 | `authorize_update` → `can_update_encounter_obj` for the signed-in user | 403 "You do not have permission to update encounter" |
| 4 | The member's `user_id` matches a `User` by `external_id` | 404 |
| 5 | The member's user is not already in this body | 400, from `ValidationError({"user": "repeats are not allowed"})` |
| 6 | `can_view_encounter_obj` for the signed-in user (`request.user`), not for the member | 403 "Treating doctor does not have permission on encounter" |
| 7 | Save | 200 with `{}` |

### Authorization

* `authorize_update` calls `can_update_encounter_obj` on the `EncounterAccess` handler. It returns `False` when the encounter status is in `COMPLETED_CHOICES`: `completed`, `cancelled`, `entered_in_error` or `discontinued`.
* Otherwise `can_update_encounter_obj` requires `can_write_encounter`, shown as "Update Encounter non clinical".
* Inside the member loop, the endpoint calls `can_view_encounter_obj` with `request.user`, once for each member. The arguments do not depend on the member, so the check fails on the first member or not at all. This handler requires `can_read_encounter`, shown as "Can Read encounter", with no status condition.
* Both handlers check the permission in the encounter's departments, their parent departments, the facility's root department (Administration) and the current location's departments.
* By default, the Doctor, Nurse and Facility Admin roles hold "Update Encounter non clinical" and "Can Read encounter".
* The permission definitions also list `ADMIN_ROLE`. After the role sync, the only role named "Admin" has the role-organization context alone, so it cannot be given in a facility.
* The members themselves are not checked. A user who holds no role at all is accepted, and the backend tests cover this case.
* An empty `members` list skips the member loop, so only `can_update_encounter_obj` applies.
* Reading the team needs read access to the encounter. `authorize_retrieve` passes with "Can list patients" through a role on the patient (`can_view_patient_obj`) or with "Can Read encounter" (`can_view_encounter_obj`). Otherwise it gives 403 "You do not have permission to view this patient".
* Being on the care team gives no access. No authorization handler reads `care_team` or `care_team_users`. Roles on an encounter come only from the user's roles in the encounter's departments and its location's departments.

### Filtering and reports

* The encounter list accepts `care_team_user=<username>`. It resolves the username to a user id and returns the encounters whose `care_team_users` contains that id. An unknown username gives 404.
* Report templates read the care team as `encounter.care_team`, shown as "Care Team". Each entry has `user` ("User", a user context) and `role` ("Role", the role's `display`, or an empty string).

## Related

* Concept: [Care team](https://docs.ohc.network/concepts/clinical/care-team.md)
* Flow: [Add care team members](https://docs.ohc.network/flows/clinical/care-team/add-care-team-members.md)
* Flow: [View the care team](https://docs.ohc.network/flows/clinical/care-team/view-the-care-team.md)
* Flow: [Modify the care team](https://docs.ohc.network/flows/clinical/care-team/modify-the-care-team.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [User](https://docs.ohc.network/references/access-governance/user.md)
* Concept: [Schedule & Availability](https://docs.ohc.network/concepts/scheduling/schedule.md)
* Concept: [Report Template](https://docs.ohc.network/concepts/platform/report-template.md)
