# Workspace

Technical reference for the `Workspace` module in Care EMR. A workspace is a saved layout of the encounter screen, and optionally of the patient's clinical history screen. The backend stores the layout as an opaque `template` and controls who can see and change each workspace. care\_fe defines and renders the layout.

A user picks the workspace that they use. Care stores that choice as a user default (`WorkSpaceUserDefault`).

**Source:**

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

## Models

| Model | Purpose |
| - | - |
| `Workspace` | A named layout with an owner scope (`auth_context`) and a status |
| `WorkspaceFacilityOrganization` | Shares a `facility` workspace with one facility organization (department) |
| `WorkspaceOrganization` | Shares an `instance` workspace with one organization |
| `WorkSpaceUserDefault` | One user's saved choice of a workspace, with an optional attribute |

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

## `Workspace` fields

| Field | Type | Spec type | Notes |
| - | - | - | - |
| `name` | `CharField(255)` | `str` | Required on create and update |
| `description` | `TextField`, default `""` | `str` | Required on create and update. An empty string is allowed |
| `template` | `JSONField`, default `{}` | `dict` | Required on create and update. The backend does not validate it. See [Template shape](#template-shape) |
| `status` | `CharField(255)` | `WorkspaceStatus` | Required on create and update |
| `auth_context` | `CharField(255)`, default `"instance"` | `WorkspaceAuthContext` | Required on create. Write once |
| `facility` | `FK → Facility`, `CASCADE`, nullable | `UUID4` or `null` | Create only. Required for `facility` and `user`. For `facility_organization`, Care copies it from the organization |
| `facility_organization` | `FK → FacilityOrganization`, `CASCADE`, nullable | `UUID4` or `null` | Create only. Required for `facility_organization` |
| `internal_organization_cache` | `ArrayField[int]`, default `[]` | — | Server-maintained. The facility organizations that the workspace reaches, with their parents |
| `organization_cache` | `ArrayField[int]`, default `[]` | — | Server-maintained. For `instance` workspaces, the shared organizations with their parents |

`WorkspaceCreateSpec` also requires `inherited: bool`. The model has no such field, so Care does not store it. care\_fe always sends `false`.

The read specs return `id`, `name`, `description`, `template` and `status`. They do not return `auth_context`, `facility` or `facility_organization`.

### `WorkspaceStatus` values

| Value | Meaning |
| - | - |
| `draft` | Not ready. care\_fe does not offer it on encounters |
| `active` | care\_fe offers it on encounters |
| `archived` | No longer offered |

### `WorkspaceAuthContext` values

| Value | Owner | Create needs |
| - | - | - |
| `instance` | The whole deployment | A superuser |
| `facility` | One facility | `can_write_workspace` in the facility's root organization |
| `facility_organization` | One facility organization (department) | `can_write_workspace` in that organization or an organization above it |
| `user` | The user who creates it, in one facility | `can_write_workspace` in any organization of the facility |

## Template shape

The backend stores `template` as any JSON object. care\_fe validates it before it saves (`src/types/workspace/encounterWorkspace.ts`):

```
template {

  schema_version: 1 | 2

  pages:          list[Page]   # encounter tabs, 1 to 50, unique keys

  history_pages:  list[Page]   # optional, schema_version 2 only. Clinical history tabs

}



Page = SystemPage | CustomPage



SystemPage {

  key:    str       # a built-in tab, e.g. "updates", "medicines", "immunizations"

  kind:   "system"

  hidden: bool      # optional

}



CustomPage {

  key:     str      # lowercase, not a reserved route key

  kind:    "custom"

  title:   str      # 1 to 120 characters

  icon:    str      # optional

  hidden:  bool     # optional

  columns: list[{ span: int (1-12), widgets: list[Widget] (max 50) }]   # 1 to 4 columns, spans total 12 or less

}



Widget {

  type:         str           # a built-in widget type, or "<plugin>.<widget>"

  title:        str           # optional

  config:       dict          # optional

  visible_when: { "encounter.status": list[str] }   # optional

}
```

care\_fe allows at most 200 widgets in one workspace. An API client can store a template that care\_fe cannot read.

## Related models

### `WorkspaceFacilityOrganization`

```
workspace    → FK Workspace (CASCADE)

organization → FK FacilityOrganization (CASCADE)
```

Written only by `set_facility_organizations`, for `facility` workspaces.

### `WorkspaceOrganization`

```
workspace    → FK Workspace (CASCADE)

organization → FK Organization (CASCADE)
```

Written only by `set_organizations`, for `instance` workspaces.

### `WorkSpaceUserDefault`

```
workspace → FK Workspace (CASCADE)

user      → FK users.User (CASCADE)

attribute → CharField(255), nullable

value     → CharField(255), nullable
```

A partial unique constraint covers (`workspace`, `user`, `attribute`, `value`) among rows that are not deleted, with `nulls_distinct=False`. care\_fe saves the attribute `scope` with the value `all` for the workspace that a user picks.

## Methods & save behaviour

* `Workspace.save()` clears the cached defaults of every user who has a default for that workspace.
* `sync_facility_org_cache()` sets `internal_organization_cache`. For `facility_organization`, it is the organization and its parents. For `facility`, it is each shared organization and its parents. Care calls it after create and after `set_facility_organizations`.
* `sync_organization_cache()` sets `organization_cache` for `instance` workspaces from the shared organizations and their parents. Care calls it after `set_organizations`.
* `WorkSpaceUserDefault.save()` and its `post_delete` signal clear that user's cached defaults (`workspace_user_default:{user_id}`).

## Resource specs (API schema)

| Spec | Role | Fields |
| - | - | - |
| `WorkspaceBaseSpec` | Shared base | `id`, `name`, `description`, `template`, `status` |
| `WorkspaceCreateSpec` | write · create | Base fields plus `auth_context`, `facility`, `facility_organization`, `inherited`. Checks that the facility and the organization exist, and that the scope has the object it needs |
| `WorkspaceUpdateSpec` | write · update | Base fields, all required |
| `WorkspaceMinimalReadSpec` | read · nested | Base fields. Used in `get_user_default_attributes` |
| `WorkspaceReadSpec` | read · list and detail | Base fields plus `created_by`, `updated_by` |

## Access rules

List and retrieve show only the workspaces that `get_filtered_workspaces` returns. A superuser sees all of them. Another user sees a workspace when one of these is true:

| Scope | Visible when |
| - | - |
| `instance` | The user holds `can_read_workspace` in an organization in `organization_cache`: a shared organization or an organization above one |
| `facility_organization` or `facility` | The user holds `can_read_workspace` in a facility organization in `internal_organization_cache` |
| `facility` | The user holds `can_write_workspace` in the facility's root organization, shared or not |
| `user` | The user created it |

Update and delete use the create rules for the workspace's scope, and the workspace must be visible to the user. A `user` workspace also needs the user to be its creator.

Default roles with `can_write_workspace`: Facility Admin. Default roles with `can_read_workspace`: Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist, and the Admin, Manager and Member roles of role organizations. See [Permission](https://docs.ohc.network/references/access-governance/permission.md).

## API integration notes

* Endpoint: `/api/v1/workspace/`. The viewset allows create, list, retrieve, update, delete (soft) and `upsert`.
* Filters: `name` (contains, case-insensitive), `status`, `auth_context`, `facility` (UUID). No ordering fields.
* `GET /{id}/get_facility_organizations/` and `POST /{id}/set_facility_organizations/` with `{ "facility_organizations": [uuid, ...] }`: `facility` workspaces only, and the caller needs update access. `set` replaces every link. Each organization must belong to the workspace's facility.
* `GET /{id}/get_organizations/` and `POST /{id}/set_organizations/` with `{ "organizations": [uuid, ...] }`: `instance` workspaces only, so only a superuser. `set` replaces every link. `get_organizations` serializes each organization with `FacilityOrganizationReadSpec`.
* `POST /{id}/set_default_attributes/` with `{ "attribute": str | null, "value": str }` saves the caller's default for that workspace. It replaces the caller's earlier row for the same workspace and attribute. Any user who can see the workspace can call it.
* `GET /get_user_default_attributes/` returns `{ "count", "results": [{ attribute, value, workspace }] }` for the caller. Care caches the result for each user and clears it when a default or a workspace changes. It does not leave out workspaces that are deleted, draft or archived, so the client checks them.

## Related

* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [Organization](https://docs.ohc.network/references/access-governance/organization.md)
* Reference: [Facility](https://docs.ohc.network/references/facility.md)
* Reference: [Permission](https://docs.ohc.network/references/access-governance/permission.md)
* Source (model): [workspace.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/workspace.py)
* Source (specs): [resources/workspace on GitHub](https://github.com/ohcnetwork/care/tree/develop/care/emr/resources/workspace)
