# Location

`FacilityLocation` is a node in a facility's building/ward/room/bed tree — where resources sit and where care happens. You work with it when you place an encounter somewhere, scope organization access to part of a facility, or model a site's physical layout.

**Source:**

* Model: [`care/emr/models/location.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/location.py)
* Resource spec: [`care/emr/resources/location/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/location/spec.py)
* Viewset: [`care/emr/api/viewsets/location.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/location.py)
* Base resource: [`care/emr/resources/base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py)
* Coding type: [`care/emr/resources/common/coding.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/common/coding.py)

Nodes nest: a node may have a parent, and a `kind` node may have children, so one tree can run from a campus down to a single bed. The create API limits the depth to `LOCATION_MAX_DEPTH` (default 10). Encounters and organizations attach to nodes. Access granted at a node cascades to its descendants through cached organization IDs, so access checks do not walk the tree on each request. The model maps to the [FHIR Location](https://build.fhir.org/location.html) resource.

The Django model is only the storage layer. `location_type`, `metadata`, `cached_parent_json`, and `tags_data` are opaque `JSONField`s. The Pydantic resource specs (`care/emr/resources/location/spec.py`) give `location_type` its shape, and also define every enum and the read/write schema split. The server alone writes the other three JSON fields. See [Resource specs (API schema)](#resource-specs-api-schema).

## Models

| Model | Purpose |
| - | - |
| `FacilityLocation` | A node in a facility's location tree (building, ward, room, bed, …) |
| `FacilityLocationOrganization` | Grants a `FacilityOrganization` access to a location |
| `FacilityLocationEncounter` | Records how/when an encounter occupied a location (e.g. a bed) |

All three extend [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md), which supplies `external_id`, audit fields, and soft-delete semantics.

## `FacilityLocation` fields

### Descriptive

| Field | Type | Spec values / shape | Notes |
| - | - | - | - |
| `name` | `CharField(255)` | `str`, required | Not unique. The model has a sibling-uniqueness helper, but the API does not call it (see [`validate_uniqueness()`](#validate_uniqueness)) |
| `description` | `CharField(255)` | `str`, required | Free-text |
| `status` | `CharField(255)` | `StatusChoices` enum | One of [`StatusChoices`](#statuschoices-values) |
| `operational_status` | `CharField(255)` | `FacilityLocationOperationalStatusChoices` enum | FHIR operational status code; one of [`FacilityLocationOperationalStatusChoices`](#facilitylocationoperationalstatuschoices-values) |
| `system_availability_status` | `CharField(255)` | `str` (read-only) | Server-maintained, derived from encounter association. Resolves to one of [`LocationAvailabilityStatusChoices`](#locationavailabilitystatuschoices-values) (`available` / `reserved`) |
| `mode` | `CharField(255)` | `FacilityLocationModeChoices` enum | `kind` (a type, e.g. a building/ward) or `instance` (a single location, e.g. Bed 1). Set on create, then frozen. See [`FacilityLocationModeChoices`](#facilitylocationmodechoices-values) |
| `location_type` | `JSONField` (`default=dict`, nullable) | `Coding \| None` (default `None`) | A single FHIR [`Coding`](#coding-shape), not a `CodeableConcept`. Unbound — any coding is accepted |
| `form` | `CharField(255)` | `FacilityLocationFormChoices` enum | FHIR physical form; one of [`FacilityLocationFormChoices`](#facilitylocationformchoices-values) |
| `inventory_usage` | `CharField(255)` (`default="none"`) | `InventoryUsage` enum, default `none` | How the location takes part in inventory; one of [`InventoryUsage`](#inventoryusage-values). The backend only stores it. care\_fe shows inventory screens for any value other than `none`, and store screens for `store`. `perform_extra_deserialization` writes it whenever the request has the key, so an explicit `none` resets it |

### Hierarchy & tree caches

These fields denormalize the tree so descendants are queryable without recursive joins. `save()` and the cascade own them; never set them from a client.

| Field | Type | Notes |
| - | - | - |
| `parent` | `FK → FacilityLocation` | `SET_NULL`, nullable. Immediate parent. Accepted on write as a UUID (`parent`); on read it's dropped in favour of the serialized parent JSON |
| `root_location` | `FK → self` | `CASCADE`, `related_name="root"`, nullable. Top of this node's tree. Excluded from specs |
| `has_children` | `BooleanField` | `default=False`. `True` when the node has a non-deleted child. Recomputed by `sync_children_flags()` on every save of the node or of a child. Read-only in list/retrieve specs |
| `has_sub_locations` | `BooleanField` | `default=False`. `True` when the node has a non-deleted child in `kind` mode. Recomputed by `sync_children_flags()`. Read-only; filterable |
| `has_beds` | `BooleanField` | `default=False`. `True` when the node has a non-deleted child in `instance` mode. Recomputed by `sync_children_flags()`. Read-only; filterable |
| `level_cache` | `IntegerField` | `default=0`. Depth in the tree (`parent.level_cache + 1`) |
| `parent_cache` | `ArrayField[int]` | Ordered ancestor IDs (`parent.parent_cache + [parent.id]`) |
| `cached_parent_json` | `JSONField` (`default=dict`) | Serialized parent chain (`FacilityLocationListSpec`) plus a `cache_expiry` ISO timestamp. Rebuilt lazily by `get_parent_json()`, cleared on every update and by the cascade. `cache_expiry_days = 15` |
| `sort_index` | `IntegerField` | `default=0`. In specs `int \| None`, default `0`, constrained `0 ≤ sort_index ≤ 10000` (`MIN_SORT_INDEX`/`MAX_SORT_INDEX`). On any save, a value of `0` or `null` becomes `max(sibling sort_index) + 1` |

### Access & encounter

| Field | Type | Notes |
| - | - | - |
| `facility` | `FK → facility.Facility` | `PROTECT`. Owning facility. Excluded from specs — resolved from route/context |
| `facility_organization_cache` | `ArrayField[int]` | `default=list`. Org IDs that can reach this location; rebuilt by `sync_organization_cache()` |
| `current_encounter` | `FK → Encounter` | `SET_NULL`, nullable, `default=None`. Populated from `FacilityLocationEncounter`. Excluded from the base spec; surfaced as serialized JSON in list/retrieve specs |
| `metadata` | `JSONField` | `default=dict`. Open bag for deployment-specific data. Not in any spec, so the API neither reads nor writes it |

### Tags

| Field | Type | Notes |
| - | - | - |
| `tags` | `ArrayField[int]` | `default=list`. [Tag config](https://docs.ohc.network/references/platform/tag-config.md) IDs applied to the location. Rendered as tag objects in `FacilityLocationListSpec` through `SingleFacilityTagManager().render_tags()` |
| `tags_data` | `JSONField` | `default=dict`. Per-tag metadata keyed by tag ID string: `{ "<tag_id>": { "expiry": "<datetime>" } }`. The tag manager writes an entry when it sets a tag that has an expiry, and removes it when the tag is unset. On read, each rendered tag gets `expiry`, plus `expired: true` after that time. Not on any spec |

## Enum values

Every enum is a `str` `Enum` in `care/emr/resources/location/spec.py`. Values below are character-for-character from source.

### `StatusChoices` values

| Value | Meaning |
| - | - |
| `active` | Location is active |
| `inactive` | Location is inactive |
| `unknown` | Status unknown |

### `FacilityLocationOperationalStatusChoices` values

FHIR HL7 v2 bed/location operational status codes.

| Code | Meaning |
| - | - |
| `C` | Closed |
| `H` | Housekeeping |
| `O` | Occupied |
| `U` | Unoccupied |
| `K` | Contaminated |
| `I` | Isolated |

### `FacilityLocationModeChoices` values

| Value | Meaning |
| - | - |
| `instance` | A single, concrete location (e.g. Bed 1). Instances cannot have children |
| `kind` | A class/type of location (e.g. a ward or building) |

### `FacilityLocationFormChoices` values

FHIR `location-physical-type` codes.

| Code | Meaning |
| - | - |
| `si` | Site |
| `bu` | Building |
| `wi` | Wing |
| `wa` | Ward |
| `lvl` | Level |
| `co` | Corridor |
| `ro` | Room |
| `bd` | Bed |
| `ve` | Vehicle |
| `ho` | House |
| `ca` | Cabinet |
| `rd` | Road |
| `area` | Area |
| `jdn` | Jurisdiction |
| `vi` | Virtual |

### `InventoryUsage` values

Used by `inventory_usage`. Default `none`.

| Value |
| - |
| `store` |
| `supplier` |
| `consumption` |
| `adjustment` |
| `none` |

### `LocationEncounterAvailabilityStatusChoices` values

Used by `FacilityLocationEncounter.status` — how an encounter occupies a location.

| Value | Meaning |
| - | - |
| `planned` | Occupancy planned |
| `active` | Currently occupied |
| `reserved` | Reserved |
| `completed` | Occupancy ended |

### `LocationAvailabilityStatusChoices` values

The server-derived values that `system_availability_status` resolves to.

| Value | Meaning |
| - | - |
| `available` | Not actively tied to an encounter |
| `reserved` | Tied to an encounter |

### `Coding` shape

`location_type` is a single `Coding` object (`extra="forbid"`):

```
Coding {

  system:  str | None = None

  version: str | None = None

  code:    str            # required

  display: str | None = None

}
```

## Related models

### `FacilityLocationOrganization`

Links an organization to a location. Users under that organization inherit access to the location and its encounters through whatever role they hold on the organization.

```
location     → FK FacilityLocation (CASCADE)

organization → FK FacilityOrganization (CASCADE)
```

Saving one of these rows calls `location.save()` (rebuilding `facility_organization_cache`), then `location.cascade_changes()`, which re-saves every descendant in the same request.

The location create body carries `organizations` (`FacilityLocationWriteSpec`), but the viewset only authorizes those UUIDs and creates no rows. The `organizations_add` and `organizations_remove` actions link and unlink organizations (see [API integration notes](#api-integration-notes)).

### `FacilityLocationEncounter`

A bed assignment, in effect: it records how an encounter occupied a location over a time window.

| Field | Type | Spec | Notes |
| - | - | - | - |
| `status` | `CharField(25)` | `LocationEncounterAvailabilityStatusChoices` | One of `planned` / `active` / `reserved` / `completed` |
| `location` | `FK → FacilityLocation` | excluded / nested | `CASCADE`. Surfaced as JSON in `...ListSpecWithLocation` |
| `encounter` | `FK → Encounter` | UUID on write, JSON on read | `CASCADE`. Validated to exist on create |
| `start_datetime` | `DateTimeField` | `datetime` (required) | Occupancy start |
| `end_datetime` | `DateTimeField` (nullable) | `datetime \| None` | Occupancy end; open-ended when null |

`FacilityLocation.current_encounter` is populated from these rows. After each create, update, or delete of a row, the viewset re-derives the location state (`reset_encounter_location_association`) under a lock on the location:

* If the location has an `active` row, `current_encounter` is that encounter, `system_availability_status` is `reserved`, and the encounter's `current_location` is this location.
* If not, `current_encounter` is `null` and `system_availability_status` is `available`.
* Any other encounter whose `current_location` is this location loses it.

The viewset (`_validate_data`) enforces these rules:

* A `kind` location cannot take encounters (`Cannot assign encounters to location kind`).
* `end_datetime` must not be before `start_datetime`. A `completed` row requires `end_datetime`. For an `active` row, the checks ignore `end_datetime`.
* A row must not conflict with another `active` or `planned` row on the same location (`Conflict in schedule`).
* A location has at most one `active` row, and an encounter has at most one `active` location.
* A `completed` row cannot change status.
* Retrieve, update, and delete reject a row that belongs to a different location than the one in the URL.

When an encounter reaches a completed status, `close_related_location_from_encounter` clears `current_encounter` on its locations and sets them `available`. Open rows for the encounter become `completed` with `end_datetime` set to now. A location left `O` (occupied) with no current encounter becomes `U` (unoccupied).

## Methods & save behaviour

### `save()` side effects

`save()` runs inside `transaction.atomic()`:

1. A save with an empty `update_fields` list returns without a write.
2. When `parent` is set, the parent row is locked (`select_for_update`).
3. On insert with a `parent`, `level_cache`, `root_location`, and `parent_cache` are derived from the parent.
4. On update, `cached_parent_json` is cleared so it rebuilds lazily. If `update_fields` is given, `cached_parent_json` is added to it.
5. On any save, a `sort_index` of `0` or `null` becomes `max(sibling sort_index) + 1`.
6. After `super().save()`, `sync_organization_cache()` persists `facility_organization_cache` through a second `save(update_fields=[...])`, so each write touches the row twice.
7. `sync_children_flags()` then recomputes the child flags of this node and of its parent.

### Caches & cascade

* `sync_organization_cache()` — unions the parent's org cache, the org chains of every linked `FacilityLocationOrganization`, and the facility's `default_internal_organization_id`, then writes `facility_organization_cache`.
* `get_parent_json()` — returns the cached parent chain, refreshing `cached_parent_json` (via `FacilityLocationListSpec.serialize(parent)`) once it expires (`cache_expiry_days = 15`).
* `sync_children_flags(sync_parent=True)` — reads the modes of the node's non-deleted children. It sets `has_children` (any child), `has_sub_locations` (a `kind` child), and `has_beds` (an `instance` child) with a queryset `update()`, then repeats once for the parent.
* `cascade_changes()` / `handle_cascade(base_location)` — `handle_cascade` has the Celery `@app.task` decorator, but `cascade_changes()` calls it directly, so it runs synchronously in the same request. It walks every descendant and calls `save(update_fields=["cached_parent_json"])`. Each save clears the node's parent JSON and re-runs `sync_organization_cache()`, so descendants pick up the new organization IDs. It runs when a `FacilityLocationOrganization` row is saved and after `organizations_remove`.

### `validate_uniqueness()`

Classmethod that checks `name` uniqueness among siblings at the same `level_cache` within the same `root_location` — or among root-level locations when there's no root. For a new instance with a `parent`, `level_cache` and `root_location` are computed from that parent before the check runs. It returns `True` when a duplicate exists.

note

No code calls `FacilityLocation.validate_uniqueness()`. The location viewset does not check names, so two sibling locations can have the same `name`. The organization viewsets call their own `validate_uniqueness()`.

## Resource specs (API schema)

The Pydantic specs in `care/emr/resources/location/spec.py` define the request/response shapes. All extend `EMRResource`, which provides `serialize`/`de_serialize` plus the `perform_extra_serialization`/`perform_extra_deserialization` hooks (see [base model](https://docs.ohc.network/references/foundation/base-model.md) and [`base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py)).

### Location specs

| Spec class | Role | Exposes / notes |
| - | - | - |
| `FacilityLocationBaseSpec` | shared base | `__model__ = FacilityLocation`; `id: UUID4 \| None`. `__exclude__ = [parent, facility, organizations, root_location, current_encounter]` |
| `FacilityLocationSpec` | shared fields | `status`, `operational_status`, `name`, `description`, `location_type` (`Coding \| None`), `form`, `inventory_usage` (`InventoryUsage`, default `none`), `sort_index` (`0..10000`, default `0`). `perform_extra_deserialization` writes `inventory_usage` whenever the request has the key |
| `FacilityLocationWriteSpec` | write · create | Adds `parent: UUID4 \| None`, `organizations: list[UUID4]` (required; authorized, not linked), `mode: FacilityLocationModeChoices`. Validator: a set `parent` must exist ("Parent not found") and must not be `mode = instance` ("Instances cannot have children"). `perform_extra_deserialization` resolves the `parent` UUID to an FK |
| `FacilityLocationUpdateSpec` | write · update | Same fields as `FacilityLocationSpec` (an empty subclass), so it has no `parent`/`organizations`/`mode` — hierarchy and mode are fixed after creation |
| `FacilityLocationMinimalListSpec` | read · nested (encounter `current_location`) | Extends `FacilityLocationSpec`; adds `parent: dict`, `mode: str`, `has_children: bool`, `has_sub_locations: bool`, `has_beds: bool`, `system_availability_status: str`. `perform_extra_serialization` sets `id = external_id` and `parent = obj.get_parent_json()` |
| `FacilityLocationListSpec` | read · list | Extends minimal; adds `current_encounter: dict \| None`, serialized via `EncounterListSpec` when present, and `tags: list[dict]` (default `[]`), rendered via `SingleFacilityTagManager().render_tags(obj)` |
| `FacilityLocationRetrieveSpec` | read · detail | Extends list; adds `created_by`/`updated_by` (via `serialize_audit_users`) |

### Encounter-association specs

| Spec class | Role | Exposes / notes |
| - | - | - |
| `FacilityLocationEncounterBaseSpec` | shared base | `__model__ = FacilityLocationEncounter`; `id: UUID4 \| None`. `__exclude__ = [encounter, location]` |
| `FacilityLocationEncounterCreateSpec` | write · create | `status` (`LocationEncounterAvailabilityStatusChoices`), `encounter: UUID4`, `start_datetime`, `end_datetime: datetime \| None`. Validator: encounter must exist. `perform_extra_deserialization` resolves the `encounter` UUID to an FK |
| `FacilityLocationEncounterUpdateSpec` | write · update | `status`, `start_datetime`, `end_datetime` (no default, so the key is required; `null` allowed). Encounter is not re-assignable |
| `FacilityLocationEncounterListSpec` | read · base | `encounter: UUID4`, `start_datetime`, `end_datetime`, `status: str`; `id = external_id`. Base of `...ListSpecWithLocation`; no endpoint uses it directly |
| `FacilityLocationEncounterListSpecWithLocation` | read · nested (encounter `location_history`) | Extends list; adds `location: dict` (serialized via `FacilityLocationListSpec`) |
| `FacilityLocationEncounterReadSpec` | read · list & detail (`association` endpoint) | `encounter: dict` (serialized via `EncounterRetrieveSpec`), `start_datetime`, `end_datetime`, `status`, `created_by`/`updated_by` |

### Server-maintained behaviour

* These are platform-maintained — don't write them from a client: `system_availability_status`, `has_children`, `has_sub_locations`, `has_beds`, `level_cache`, `parent_cache`, `cached_parent_json`, `facility_organization_cache`, `current_encounter`, `tags_data`, and `sort_index` (when left unset).
* On read, `parent` comes back as the serialized parent chain (`get_parent_json()`), never the raw FK.
* Access granted through `organizations_add` (a new `FacilityLocationOrganization` row) reaches the location and its descendants in the same request, because `cascade_changes()` runs synchronously.
* `location_type` takes a free `Coding` (no value-set slug), so it adds coded data without a schema migration. `metadata` is not exposed through the API.

## API integration notes

* The model follows the FHIR `Location` resource, but the payload uses the Django field names on this page (for example, `form` and `location_type`).
* `mode` separates `kind` (a location type) from `instance` (a concrete location such as a bed). Beds are `FacilityLocation` instances, not a separate model, and `instance` locations cannot have children.
* `parent`, `organizations`, and `mode` are settable only at creation (`FacilityLocationWriteSpec`). Updates go through `FacilityLocationUpdateSpec`, which omits all three.
* For fields you can't write, see [Server-maintained behaviour](#server-maintained-behaviour).
* Create checks: the parent must be in the same facility (`Parent Incompatible with Location`), must not be an `instance`, and must have `level_cache` below `LOCATION_MAX_DEPTH` (default 10). A facility holds at most `MAX_LOCATION_IN_FACILITY` (default 1000) non-deleted locations.
* Delete is a soft delete. It fails with `Location has active children` while the location has non-deleted children.
* Organizations: `GET .../organizations/` lists the linked organizations. `POST .../organizations_add/` and `POST .../organizations_remove/` take `{ organization: uuid }`. Both need `can_update_facility_location_obj` on the location and `can_manage_facility_organization_obj` on an organization of the same facility. Remove hard-deletes the link row, then re-saves the location and runs `cascade_changes()`.
* Tags: the viewset uses `EMRTagMixin` with `resource_type = location`. The create body can carry `tags: [{ tag, expiry_offset? }]`, and `POST .../set_tags/` and `POST .../remove_tags/` change them later. A tag must have `resource` `location` and belong to this facility or to the instance. `?tags=<uuid>,<uuid>` with `tags_behavior=any` (default) or `all` filters the list. See [Tag config](https://docs.ohc.network/references/platform/tag-config.md).
* List filters: `parent` (UUID; an empty `?parent=` returns top-level locations), `name` (contains), `mode`, `form`, `operational_status`, `status` (case-insensitive exact), `available` (no current encounter), `has_beds`, `has_sub_locations`, and `mine` (locations linked to the user's organizations). Ordering: `sort_index`.
* Encounter occupancy lives at the nested `.../location/<location_id>/association/` endpoint (`FacilityLocationEncounter`). The `POST .../associate_encounter/` action on the location is an unfinished stub: it runs permission checks and returns no response.
* A location can be the subject of a form. A questionnaire with `subject_type` `location` takes submissions at `POST /api/v1/questionnaire/<questionnaire_id>/submit_resource/`, with the location `external_id` in `resource_id`. Care stores them as `FacilityResourceQuestionnaireResponse` rows, listed at `GET /api/v1/resource_responses/?subject_type=location&subject_id=<location_id>`. Submit needs `can_submit_questionnaire`, and read needs `can_view_resource_responses`, in an organization in the location's `facility_organization_cache`.

## Related

* Reference: [Facility](https://docs.ohc.network/references/facility.md)
* Reference: [Organization](https://docs.ohc.network/references/access-governance/organization.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [Tag config](https://docs.ohc.network/references/platform/tag-config.md)
* Reference: [Device](https://docs.ohc.network/references/facility/device.md)
* Reference: [Base model](https://docs.ohc.network/references/foundation/base-model.md)
* Concept: [Location](https://docs.ohc.network/concepts/facility/location.md)
* Source: [location.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/location.py)
* Source: [location/spec.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/location/spec.py)
