# Booking

A booking puts a patient into a concrete time slot generated from a [Schedule](https://docs.ohc.network/references/scheduling/schedule.md). `TokenSlot` is a bookable unit of availability; `TokenBooking` is a patient's appointment against that slot, carrying its status through the lifecycle. You touch both whenever an integration creates, cancels, reschedules, or reads an appointment.

**Source:**

* Model: [`care/emr/models/scheduling/booking.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/scheduling/booking.py)
* Resource spec: [`care/emr/resources/scheduling/slot/spec.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/scheduling/slot/spec.py)
* Viewset (side effects): [`care/emr/api/viewsets/scheduling/booking.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/scheduling/booking.py)
* Viewset (slots and booking creation): [`care/emr/api/viewsets/scheduling/availability.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/scheduling/availability.py)

These models live in two layers. The Django model is storage: `status` is an unconstrained `CharField` and several relations are opaque at the DB level. The Pydantic resource specs (`care/emr/resources/scheduling/slot/`) are the API layer — they pin `status` to a fixed enum, validate writes, and define the read schemas that embed slot, resource, facility, token, charge item, encounter, and patient sub-objects.

## Models

| Model | Purpose |
| - | - |
| `TokenSlot` | A concrete, bookable time window generated from a schedulable resource's availability |
| `TokenBooking` | A patient's appointment against a `TokenSlot`, with status, notes, and optional links to an encounter, token, and charge item |

Both extend [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md), the shared Care EMR base providing `external_id`, `created_date`/`modified_date`, soft-delete via `deleted`, `created_by`/`updated_by`, and `history`/`meta` JSON.

## `TokenBooking` fields

| Field | Type | Notes |
| - | - | - |
| `token_slot` | `FK → TokenSlot` (PROTECT) | The slot this appointment occupies; required. PROTECT prevents deleting a slot that has bookings |
| `patient` | `FK → emr.Patient` (CASCADE) | The booked patient; required |
| `booked_on` | `DateTimeField` | `auto_now_add` — stamped once at creation, never accepted from clients |
| `booked_by` | `FK → User` (CASCADE) | User who created the booking; nullable for self-service or system-created bookings |
| `status` | `CharField` (storage) → `BookingStatusChoices` (API) | Appointment lifecycle status. Unbounded on the model; the write spec restricts it to the [`BookingStatusChoices`](#bookingstatuschoices-values) enum |
| `note` | `TextField` | Free-text note; nullable in storage but required (`str`) on write |
| `tags` | `ArrayField[int]` | Tag IDs, default empty list. Managed via `SingleFacilityTagManager`; reads return rendered tag objects, not raw IDs |
| `tags_data` | `JSONField`, default `dict` | Per-tag expiry metadata, keyed by tag ID: `{"<tag id>": {"expiry": "<datetime>"}}`. `SingleFacilityTagManager` writes it when a tag gets an expiry. Not in any spec; `render_tags` adds `expiry` (and `expired: true` once past) to each rendered tag |
| `associated_encounter` | `FK → emr.Encounter` (PROTECT) | Encounter linked to the appointment; nullable, defaults to `None`. Encounter create sets it when the new encounter names this booking as its `appointment`, and rejects a booking that already has one. Surfaced only by `TokenBookingRetrieveSpec` |
| `token` | `FK → emr.Token` (PROTECT) | Queue token issued for this booking; nullable, defaults to `None`, `related_name="token_booking"`. Created by the `generate_token` action |
| `charge_item` | `FK → emr.ChargeItem` (CASCADE) | Billing charge item for the appointment; nullable. Auto-created on booking when the schedule has a `charge_item_definition` (see [Methods & save behaviour](#methods--save-behaviour)) |

### `BookingStatusChoices` values

`BookingStatusChoices` (`str, Enum`) is the full set of `status` values the write spec accepts:

| Value | Notes |
| - | - |
| `proposed` | |
| `pending` | |
| `booked` | Default applied server-side when a booking is created via `lock_create_appointment` |
| `arrived` | |
| `fulfilled` | Terminal; in `COMPLETED_STATUS_CHOICES` |
| `cancelled` | Set only via the `cancel` endpoint; in `CANCELLED_STATUS_CHOICES` + `COMPLETED_STATUS_CHOICES` |
| `noshow` | Terminal; in `COMPLETED_STATUS_CHOICES` |
| `entered_in_error` | Set only via the `cancel` endpoint; in `CANCELLED_STATUS_CHOICES` + `COMPLETED_STATUS_CHOICES` |
| `checked_in` | |
| `waitlist` | |
| `in_consultation` | Cannot be cancelled — the cancel handler rejects it |
| `rescheduled` | Set only via the `reschedule` endpoint; in `CANCELLED_STATUS_CHOICES` + `COMPLETED_STATUS_CHOICES` |

Two derived sets (from `slot/spec.py`) drive the lifecycle rules:

| Set | Values |
| - | - |
| `CANCELLED_STATUS_CHOICES` | `entered_in_error`, `cancelled`, `rescheduled` |
| `COMPLETED_STATUS_CHOICES` | `fulfilled`, `noshow`, `entered_in_error`, `cancelled`, `rescheduled` |

`TokenBookingWriteSpec.perform_extra_deserialization` rejects any write whose `status` is in `CANCELLED_STATUS_CHOICES` with `"Cannot cancel a booking. Use the cancel endpoint"`. Cancellation and rescheduling go through dedicated endpoints (see below), never a plain update.

## Related models

### `TokenSlot`

A bookable window derived from a resource's availability. Bookings reference it via PROTECT, so a slot with active bookings cannot be deleted. `TokenSlot` rows are created on demand: `SlotViewSet.get_slots_for_day` creates the missing slots for one day from the `appointment`-type availabilities, skips windows that overlap an availability exception or have already ended, and returns all slots for that day.

| Field | Type | Notes |
| - | - | - |
| `resource` | `FK → SchedulableResource` (CASCADE) | The schedulable resource — practitioner, location, or healthcare service — the slot belongs to; required |
| `availability` | `FK → Availability` (CASCADE) | The availability rule that generated this slot; nullable |
| `start_datetime` | `DateTimeField` | Slot start; required, tz-aware |
| `end_datetime` | `DateTimeField` | Slot end; required, tz-aware |
| `allocated` | `IntegerField` | Count of bookings currently allocated to the slot, used to enforce capacity. Defaults to `0`. Platform-maintained — never written by clients |

`SchedulableResource` and `Availability` live in the [Schedule](https://docs.ohc.network/references/scheduling/schedule.md) module. `SchedulableResource.resource_type` is one of `SchedulableResourceTypeOptions`: `practitioner`, `location`, `healthcare_service`.

## Resource specs (API schema)

Every spec extends `EMRResource` ([`base.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/base.py)): `serialize` (DB → pydantic, read) and `de_serialize` (pydantic → DB, write), with `perform_extra_serialization` / `perform_extra_deserialization` hooks.

| Spec class | Role | Exposes / behaviour |
| - | - | - |
| `TokenBookingBaseSpec` | shared | `__model__ = TokenBooking`, `__exclude__ = ["token_slot", "patient"]` |
| `TokenBookingWriteSpec` | write · update | Fields: `status: BookingStatusChoices`, `note: str` (both required). Rejects `status` in `CANCELLED_STATUS_CHOICES` (use the cancel/reschedule endpoints). The viewset sets it as both `pydantic_model` and `pydantic_update_model`, but `TokenBookingViewSet` has no create mixin, so only update uses it |
| `TokenBookingMinimumReadSpec` | read · embed | Lightweight read for when a booking is embedded in another resource, such as a token. Fields: `id`, `token_slot` (embedded `TokenSlotBaseSpec`), `booked_on`, `status: str`, `note`, `created_date`, `modified_date` |
| `TokenBookingBaseReadSpec` | read · shared | Adds `booked_by: UserSpec`, `resource_type`, `resource` (serialized resource), `facility`, `created_by`/`updated_by`, `token: TokenReadSpec`, `tags: list[dict]` (rendered), `charge_item: dict` |
| `TokenBookingReadSpec` | read · list/default | `TokenBookingBaseReadSpec` + `patient: PatientRetrieveSpec`. The viewset's `pydantic_read_model` for list responses |
| `TokenBookingOTPReadSpec` | read · OTP flow | `TokenBookingBaseReadSpec` + `patient: PatientOTPReadSpec` for the public/OTP booking flow |
| `TokenBookingRetrieveSpec` | read · detail | `TokenBookingReadSpec` + `associated_encounter: dict` (serialized `EncounterListSpec`). Also merges the schedule's `organizations`, `care_team`, and `encounter_type` into `token_slot.availability.schedule`. The viewset's `pydantic_retrieve_model` |
| `TokenSlotBaseSpec` | read · embed | `__model__ = TokenSlot`, `__exclude__ = ["resource", "availability"]`. Fields: `id`, `availability` (embedded as `{name, tokens_per_slot, id, schedule:{name,id}}`), `start_datetime`, `end_datetime`, `allocated`. The embedded `availability.id` carries the slot's own `external_id`, not the availability's |

### Read serialization details (`perform_extra_serialization`)

* `id` always comes from `obj.external_id` (UUID), not the integer PK.
* `token_slot` is embedded via `TokenSlotBaseSpec.serialize(...)`.
* `resource_type` comes from `token_slot.resource.resource_type`; `resource` is built by `serialize_resource()` — a `UserSpec` for `practitioner`, `HealthcareServiceReadSpec` for `healthcare_service`, `FacilityLocationListSpec` for `location`.
* `facility` is a cached `FacilityBareMinimumSpec`; `booked_by` / `created_by` / `updated_by` are cached `UserSpec`s.
* `tags` are rendered through `SingleFacilityTagManager().render_tags(obj)` as objects, not raw IDs.
* `token` (`TokenReadSpec`), `charge_item` (`ChargeItemReadSpec`), and `associated_encounter` (`EncounterListSpec`) appear only when present.
* `TokenBookingRetrieveSpec` extends `token_slot.availability.schedule` with `serialize_schedule_metadata()`: `organizations` (`FacilityOrganizationReadSpec` list), `care_team` (`[{member: UserSpec, role}]`), and `encounter_type`.

## Methods & save behaviour

`status` has no model-level `choices`; the lifecycle lives entirely in the spec/viewset layer (`TokenBookingViewSet`). The server-maintained behaviour:

* **Create endpoint (`SlotViewSet.create_appointment`)** — `POST facility/{facility_external_id}/slots/{slot_id}/create_appointment/` with `AppointmentBookingSpec { patient: UUID, note: str, tags: list[TagSetRequest] = [] }`, where `TagSetRequest` is `{ tag: UUID, expiry_offset? }`. Requires `can_create_booking` on the slot's resource. Rejects the request when the patient already has `settings.MAX_APPOINTMENTS_PER_PATIENT` (default `10`) or more upcoming bookings that are not in `COMPLETED_STATUS_CHOICES`, or when the patient does not exist. It then runs `lock_create_appointment`, applies `tags`, and runs the facility's actions for the `appointment` action context, all in one transaction. The response is `TokenBookingReadSpec` plus an `_actions` list with each action result.
* **Creation (`lock_create_appointment`)** — runs under a per-resource lock and a transaction. Rejects past slots (`end_datetime < now`) and full slots (`allocated >= availability.tokens_per_slot`), rejects a duplicate active booking for the same patient/slot (any status not in `COMPLETED_STATUS_CHOICES`), then increments `token_slot.allocated`, creates the booking with `status="booked"`, and — if the schedule has a `charge_item_definition` — auto-creates the linked `charge_item`.
* **Charge item selection** — `lock_create_appointment` finds the patient's latest booking on the same schedule that is not cancelled, starts at or before the new slot, and has a `paid` charge item from the schedule's `charge_item_definition`. If that charge item's `paid_on` is within `revisit_allowed_days` days of the new slot start, it applies `revisit_charge_item_definition` (no charge item when that field is `null`). Otherwise it applies `charge_item_definition`. The new charge item gets `service_resource = appointment`, `service_resource_id` = the booking's `external_id`, and `performer_actor` = the resource's user.
* **Cancel (`cancel` action)** — accepts `CancelBookingSpec { reason: cancelled | entered_in_error | rescheduled, note?: str }`. Rejects cancelling an `in_consultation` booking. Decrements `token_slot.allocated` (unless already cancelled), sets `status = reason`, optionally overwrites `note`, sets `updated_by`, and aborts any linked `charge_item` (`handle_charge_item_cancel` + status `aborted`).
* **Reschedule (`reschedule` action)** — accepts `RescheduleBookingSpec { new_slot: UUID, new_booking_note: str, previous_booking_note?: str, tags: list[TagSetRequest] = [] }`. Requires `can_write_booking` on the booking's resource and `can_reschedule_booking` on the facility. `new_slot` must belong to the URL facility. In one transaction, it cancels the existing booking with reason `rescheduled` (note: `previous_booking_note`, or the existing note), runs `lock_create_appointment` for the same patient on `new_slot`, and applies `tags` to the new booking. Rejects rescheduling to the same slot.
* **Generate token (`generate_token` action)** — accepts `TokenGenerationSpec { category: UUID, note?: str, queue?: UUID }`. Rejects if a token already exists. A given `queue` must match the slot's facility, resource, and date. Without one, it uses the system-generated `TokenQueue` for that date and resource, or creates one named `"System Generated"` (primary if no queue exists for that date). The `category` must belong to the facility and match the resource's `resource_type`. Under a queue lock it takes `Token.get_next_number(queue, category)`, creates a `Token` (`status="CREATED"`, linked to the booking and patient), and links it to `booking.token`.
* **`booked_on`** is `auto_now_add` — never set by clients.

## API integration notes

* `TokenSlot` and `TokenBooking` are exposed through Care's scheduling REST API and align with the FHIR `Slot` and `Appointment` resources; payload field names may differ from Django model names.
* Routes (nested under `facility/{facility_external_id}/`): `appointments/` (`TokenBookingViewSet`: list, retrieve, update, and the actions below) and `slots/` (`SlotViewSet`: retrieve, `get_slots_for_day`, `create_appointment`, `availability_stats`).
* Writes use `TokenBookingWriteSpec` (`status` constrained to `BookingStatusChoices`, `note` required). `cancelled` / `entered_in_error` / `rescheduled` cannot be set through a plain update — use the `cancel` / `reschedule` actions.
* List responses use `TokenBookingReadSpec`; detail responses use `TokenBookingRetrieveSpec`, which adds `associated_encounter`.
* `allocated` on `TokenSlot` is a capacity counter maintained by `lock_create_appointment` and cancel; do not write it directly.
* `tags` is stored as an array of integer tag IDs but returned as rendered tag objects on read.
* List requires a `resource_type` query param and authorization scoped to organizations or resource IDs. For `practitioner`, send `organization_ids` or `resource_ids`; only a superuser can omit both. Each organization must be in the facility, and the user needs `can_write_schedule` in that organization or a parent (`can_list_booking_organization`). For `location` and `healthcare_service`, `resource_ids` is required. Each resource needs `can_list_booking`.
* Update, `cancel`, `reschedule`, `generate_token`, `set_tags`, `remove_tags`, and `execute_action` require `can_write_booking` on the slot's resource. Retrieve requires `can_list_booking`.
* List filters: `status` (multi-select), `date` range on the slot start date, `slot`, `patient`, and facility tags (`SingleFacilityTagFilter`). Ordering: `created_date`, `token_slot__start_datetime`.
* Other `TokenBookingViewSet` actions: `available_users` (practitioner resources in the facility, optionally filtered by `organization_ids`), `set_tags` / `remove_tags` (`EMRTagMixin`, tag resource `token_booking`), and `execute_action` (runs one performable action of the `appointment` context; `PERFORM_INDEPENDENT_ACTIONS = True`).
* The OTP flow (`otp/slots`) books and cancels through the same handlers with `booked_by = None`, and returns `TokenBookingOTPReadSpec`.

## Related

* Reference: [Schedule](https://docs.ohc.network/references/scheduling/schedule.md)
* Reference: [Token](https://docs.ohc.network/references/scheduling/token.md)
* Reference: [Encounter](https://docs.ohc.network/references/clinical/encounter.md)
* Reference: [Patient](https://docs.ohc.network/references/clinical/patient.md)
* Reference: [Charge item](https://docs.ohc.network/references/billing/charge-item.md)
* Source: [booking.py (model)](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/scheduling/booking.py)
* Source: [slot/spec.py (resource spec)](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/scheduling/slot/spec.py)
* Source: [booking.py (viewset)](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/scheduling/booking.py)
