openapi: 3.0.3
info:
    title: ManaNotes External API
    version: 1.0.0
    description: |
        OAuth 2.0–protected REST API for third-party integrations with
        **ManaNotes**, clinic-management software for NZ ACC providers.

        It exposes appointment booking and patient management:

        - **Appointments** — list / create / read / update / delete, plus a
          dedicated status endpoint (check-in, no-show, cancel)
        - **Patients** — list / create / read / update / delete
        - **Attachments** — list, upload, download and delete the files on a
          patient's record (intake forms, consent PDFs, scans)
        - **Reference data** — practitioners, billable items, locations,
          working hours and availability (needed to book), the clinic
          profile and the patient-field catalogue

        ## Front-desk & forms apps

        A patient-forms or kiosk app (such as Finger-Ink) connects by creating
        a credential from its card in **Settings → Integrations**. It then
        reads the day's appointments and patients, files completed PDFs with
        `POST /patients/{id}/attachments`, and checks patients in with
        `PATCH /appointments/{id}/status` (`ARRIVED`). `GET /patient-fields`
        lists every patient field it can map a form question onto, and
        `GET /clinic` gives it the clinic's name and contact details to brand
        itself with.

        ## Authentication

        The API uses the **OAuth 2.0 client-credentials (machine-to-machine)**
        grant. Generate a `client_id` and `client_secret` from **Settings →
        Integrations → API access** in the ManaNotes app, exchange them at the
        token endpoint below, then call the API with `Authorization: Bearer
        <token>`.

        ```bash
        curl --request POST \
          --url https://api.mananotes.co.nz/api/v1/oauth/token \
          --header 'content-type: application/x-www-form-urlencoded' \
          --data grant_type=client_credentials \
          --data client_id=YOUR_CLIENT_ID \
          --data client_secret=YOUR_CLIENT_SECRET
        ```

        Each client is bound to a single **clinic** and granted a set of
        **scopes**. Requests only ever see that clinic's data.

        ## Scopes

        | Scope                  | Grants                                  |
        | ---------------------- | --------------------------------------- |
        | `appointments:read`    | List/read appointments, practitioners, billable items, locations, working hours, availability & the clinic profile |
        | `appointments:write`   | Create/update/delete appointments and change their status |
        | `patients:read`        | List/read patients & the patient-field catalogue |
        | `patients:write`       | Create/update/delete patients           |
        | `attachments:read`     | List/read a patient's files and download their bytes |
        | `attachments:write`    | Upload and delete files                 |

        ## Conventions

        - All times are **UTC ISO 8601** strings (e.g. `2026-01-20T21:30:00Z`).
          Clinic-local time is `Pacific/Auckland`. Send times with `Z` or an
          offset; in a query string, encode `+` as `%2B`.
        - Dates of birth and injury dates are calendar days sent as ISO 8601:
          send UTC midnight of the day (e.g. `1991-04-22T00:00:00Z`). They are
          stored as that `Pacific/Auckland` calendar day, so read them back by
          their date part rather than converting to your local zone.
        - Successful responses wrap the payload in a `data` field.
        - Deletes are **soft deletes** (the record is flagged, not destroyed),
          matching the practitioner app.
        - Unknown request-body fields are rejected with `400`.

        ## Locations (multi-site clinics)

        Clinics may operate several physical sites. `GET /locations` lists
        them; exactly one is the clinic's **default**. Records created before
        a clinic adopted locations carry no `LocationId` — they belong to the
        default site, and filtering by the default site's id includes them.
        Single-site integrations can ignore locations entirely: omitting the
        optional `locationId` / `locationIds` / `LocationId` /
        `HomeLocationId` parameters keeps clinic-wide behaviour everywhere.

        List filters that take several sites (`locationIds`) accept the
        parameter repeated (`?locationIds=a&locationIds=b`) or
        comma-separated (`?locationIds=a,b`). An empty value is the same as
        omitting it.

    contact:
        name: ManaNotes
        url: https://www.mananotes.co.nz

servers:
    - url: https://{host}/api/v1
      description: ManaNotes backend (set host per environment)
      variables:
          host:
              default: api.mananotes.co.nz
              description: >-
                  Backend host. Replace with your environment's API host
                  (e.g. the Cloud Run service domain).

security:
    - OAuth2: []

tags:
    - name: Appointments
    - name: Patients
    - name: Attachments
    - name: Reference
    - name: Meta

paths:
    /health:
        get:
            tags: [Meta]
            summary: Health check
            description: Unauthenticated liveness probe.
            security: []
            responses:
                '200':
                    description: Service is up
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    status: { type: string, example: ok }
                                    apiVersion: { type: string, example: 1.0.0 }

    /me:
        get:
            tags: [Meta]
            summary: Identify the calling client
            description: >-
                Returns the authenticated client's identity, clinic and granted
                scopes. Useful to verify credentials.
            responses:
                '200':
                    description: Client info
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data: { $ref: '#/components/schemas/Me' }
                '401': { $ref: '#/components/responses/Unauthorized' }

    /patients:
        get:
            tags: [Patients]
            summary: List patients
            description: >-
                Without `search`, lists the clinic's patients alphabetically.
                With `search`, performs the same case-insensitive lookup as
                the in-app patient search: matches on first / preferred /
                middle / last name (multi-word terms like "Li Wei Yu" are
                matched across the name fields), email, phone numbers, NHI,
                and date of birth (e.g. `01/02/1990`). Search results are
                ordered best match first — a patient whose full name, then
                first (or preferred) name, then last name exactly equals the
                term ranks above patients the term merely prefixes or appears
                inside.
            security: [{ OAuth2: [patients:read] }]
            parameters:
                - $ref: '#/components/parameters/Limit'
                - $ref: '#/components/parameters/Offset'
                - $ref: '#/components/parameters/Search'
                - name: locationIds
                  in: query
                  required: false
                  style: form
                  explode: true
                  schema:
                      type: array
                      items: { type: string }
                  description: >-
                      Restrict to patients whose home location (site) is one
                      of these — see `GET /locations`. Passing the default
                      location's id also matches patients with no home
                      location. Also narrows `search` results. Omitted = all
                      sites.
            responses:
                '200':
                    description: A page of patients
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/PatientList'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '429': { $ref: '#/components/responses/RateLimited' }
        post:
            tags: [Patients]
            summary: Create a patient
            security: [{ OAuth2: [patients:write] }]
            requestBody:
                required: true
                content:
                    application/json:
                        schema:
                            $ref: '#/components/schemas/PatientCreate'
            responses:
                '201':
                    description: Patient created
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/PatientResponse'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '409': { $ref: '#/components/responses/Conflict' }

    /patients/{id}:
        parameters:
            - $ref: '#/components/parameters/Id'
        get:
            tags: [Patients]
            summary: Get a patient
            security: [{ OAuth2: [patients:read] }]
            responses:
                '200':
                    description: The patient
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/PatientResponse'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }
        patch:
            tags: [Patients]
            summary: Update a patient
            security: [{ OAuth2: [patients:write] }]
            requestBody:
                required: true
                content:
                    application/json:
                        schema:
                            $ref: '#/components/schemas/PatientUpdate'
            responses:
                '200':
                    description: Updated patient
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/PatientResponse'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }
        delete:
            tags: [Patients]
            summary: Delete a patient (soft)
            security: [{ OAuth2: [patients:write] }]
            responses:
                '200':
                    description: Deleted patient
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: object
                                        properties:
                                            id: { type: string }
                                            IsDeleted: { type: boolean }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }
                '409': { $ref: '#/components/responses/Conflict' }

    /patients/{id}/attachments:
        parameters:
            - $ref: '#/components/parameters/Id'
        get:
            tags: [Attachments]
            summary: List a patient's files
            description: >-
                Metadata for the files on the patient's record and under any
                of their injuries (what the patient page's Files tab shows),
                newest first. Never the bytes — fetch those per file with
                `GET /attachments/{id}/content`.
            security: [{ OAuth2: [attachments:read] }]
            responses:
                '200':
                    description: The patient's files
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/Attachment'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }
        post:
            tags: [Attachments]
            summary: Upload a file to a patient
            description: >-
                Attaches a file to the patient's record — or, with `injuryId`,
                under one of the patient's injuries (ACC claims). The bytes
                travel base64-encoded in the JSON body, so no multipart client
                is needed. The decoded file may be at most **10MB** and must be
                one of the allowed MIME types (PDF, JPEG, PNG, GIF, Word,
                Excel or plain text); anything else is rejected with `400`
                (`File size exceeds maximum limit of 10MB` for an oversize
                file). The upload shows in the patient's **Files** tab in the
                app and is logged on the patient's activity timeline, exactly
                as an in-app upload.
            security: [{ OAuth2: [attachments:write] }]
            requestBody:
                required: true
                content:
                    application/json:
                        schema:
                            $ref: '#/components/schemas/AttachmentCreate'
            responses:
                '201':
                    description: File uploaded
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/AttachmentResponse'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /attachments/{id}:
        parameters:
            - $ref: '#/components/parameters/Id'
        get:
            tags: [Attachments]
            summary: Get a file's metadata
            security: [{ OAuth2: [attachments:read] }]
            responses:
                '200':
                    description: The file's metadata
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/AttachmentResponse'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }
        delete:
            tags: [Attachments]
            summary: Delete a file (soft)
            description: >-
                Soft-deletes the file: it is hidden from the patient record in
                the app, but the bytes are kept.
            security: [{ OAuth2: [attachments:write] }]
            responses:
                '200':
                    description: Deleted file
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: object
                                        properties:
                                            id: { type: string }
                                            isDeleted: { type: boolean, example: true }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /attachments/{id}/content:
        parameters:
            - $ref: '#/components/parameters/Id'
        get:
            tags: [Attachments]
            summary: Download a file's bytes
            description: >-
                The raw file, not JSON. `Content-Type` is the stored
                `mimeType`, `Content-Length` is the file size, and
                `Content-Disposition: attachment; filename="..."` carries the
                file name. Each download is recorded on the attachment's
                access log, like an in-app open.
            security: [{ OAuth2: [attachments:read] }]
            responses:
                '200':
                    description: The file bytes
                    headers:
                        Content-Type:
                            schema: { type: string, example: application/pdf }
                            description: The file's stored MIME type.
                        Content-Length:
                            schema: { type: integer }
                            description: File size in bytes.
                        Content-Disposition:
                            schema:
                                type: string
                                example: attachment; filename="intake-form.pdf"
                    content:
                        application/octet-stream:
                            schema: { type: string, format: binary }
                        application/pdf:
                            schema: { type: string, format: binary }
                        image/jpeg:
                            schema: { type: string, format: binary }
                        image/png:
                            schema: { type: string, format: binary }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /appointments:
        get:
            tags: [Appointments]
            summary: List appointments in a date range
            description: >-
                Returns appointments whose start and end fall within
                `[from, to]`. Both are required ISO 8601 values: with `Z` or an
                offset they are that instant; without one they are clinic-local
                (`Pacific/Auckland`) time; a bare `yyyy-MM-dd` covers that whole
                clinic day (`from` from its start, `to` to its end).
            security: [{ OAuth2: [appointments:read] }]
            parameters:
                - name: from
                  in: query
                  required: true
                  schema: { type: string }
                  example: '2026-01-01'
                - name: to
                  in: query
                  required: true
                  schema: { type: string }
                  example: '2026-01-31'
                - name: locationIds
                  in: query
                  required: false
                  style: form
                  explode: true
                  schema:
                      type: array
                      items: { type: string }
                  description: >-
                      Restrict to these clinic locations (sites) — see `GET
                      /locations`. Passing the default location's id also
                      matches legacy appointments that predate multi-location.
                      Omitted = all sites.
                - name: locationId
                  in: query
                  required: false
                  schema: { type: string }
                  description: >-
                      Restrict to one clinic location (site). Shorthand for a
                      one-item `locationIds`; when both are sent, the union is
                      used. Omitted = all sites.
            responses:
                '200':
                    description: Matching appointments
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/Appointment'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
        post:
            tags: [Appointments]
            summary: Create an appointment
            description: >-
                `BillableItemId` is required (see `GET /billable-items`). Link an
                existing patient with `PatientId`, or create one inline via
                `Patient`. Optionally attach/lodge an injury via `InjuryId` or
                `Injury`. Multi-site clinics can pick the site with
                `LocationId` (see `GET /locations`). A booking that overlaps an
                existing active appointment for the practitioner is rejected
                with `409` — cancelled and no-show appointments free their slot
                and do not count as conflicts.
            security: [{ OAuth2: [appointments:write] }]
            requestBody:
                required: true
                content:
                    application/json:
                        schema:
                            $ref: '#/components/schemas/AppointmentCreate'
            responses:
                '201':
                    description: Appointment created
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/AppointmentResponse'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '409': { $ref: '#/components/responses/Conflict' }

    /appointments/{id}:
        parameters:
            - $ref: '#/components/parameters/Id'
        get:
            tags: [Appointments]
            summary: Get an appointment
            security: [{ OAuth2: [appointments:read] }]
            responses:
                '200':
                    description: The appointment
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/AppointmentResponse'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }
        patch:
            tags: [Appointments]
            summary: Update an appointment
            description: >-
                Reschedule, change status/notes, relink patient/injury, etc.
                Rescheduling into a time that overlaps an existing active
                appointment for the practitioner is rejected with `409` —
                cancelled and no-show appointments free their slot and do not
                count as conflicts.
            security: [{ OAuth2: [appointments:write] }]
            requestBody:
                required: true
                content:
                    application/json:
                        schema:
                            $ref: '#/components/schemas/AppointmentUpdate'
            responses:
                '200':
                    description: Updated appointment
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/AppointmentResponse'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }
                '409': { $ref: '#/components/responses/Conflict' }
        delete:
            tags: [Appointments]
            summary: Delete an appointment (soft)
            security: [{ OAuth2: [appointments:write] }]
            parameters:
                - name: deleteAssociatedTreatment
                  in: query
                  required: false
                  schema: { type: boolean, default: false }
                  description: Also soft-delete the linked treatment (if any).
            responses:
                '200':
                    description: Deleted appointment
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: object
                                        properties:
                                            id: { type: string }
                                            IsDeleted: { type: boolean }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /appointments/{id}/status:
        parameters:
            - $ref: '#/components/parameters/Id'
        patch:
            tags: [Appointments]
            summary: Update an appointment's status
            description: >-
                Moves the appointment through the front-desk lifecycle:
                `PENDING` (tentative) → `NEW` (booked) → `ARRIVED` (checked in)
                → `WITH_PRACTITIONER` (in the room) → `COMPLETED` (visit
                over), or `NO_SHOW` / `CANCELLED`. The typical use is a kiosk check-in setting
                `ARRIVED`. Setting `CANCELLED` stops the appointment's pending
                reminders and fires its "after appointment cancelled"
                workflows exactly as a cancel in the app; reverting out of
                `CANCELLED` re-arms them. Returns the full appointment, the
                same shape as `GET /appointments/{id}`.
            security: [{ OAuth2: [appointments:write] }]
            requestBody:
                required: true
                content:
                    application/json:
                        schema:
                            $ref: '#/components/schemas/AppointmentStatusUpdate'
            responses:
                '200':
                    description: Updated appointment
                    content:
                        application/json:
                            schema:
                                $ref: '#/components/schemas/AppointmentResponse'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /clinic:
        get:
            tags: [Reference]
            summary: Get the clinic profile
            description: >-
                The clinic's profile — name, legal name, contact details,
                website and social links, whether online booking is on, and
                its locations (sites, the same shape as `GET /locations`).
                What a forms or kiosk app brands itself with. The clinic logo
                is deliberately not included. Returns `404` for a solo
                practitioner with no clinic.
            security: [{ OAuth2: [appointments:read] }]
            responses:
                '200':
                    description: The clinic
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data: { $ref: '#/components/schemas/Clinic' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /patient-fields:
        get:
            tags: [Reference]
            summary: List the patient record fields
            description: >-
                The catalogue of every patient record field an integrator can
                read and write — its name, type, human label, group and
                whether it is required on create — so a forms app can let the
                clinic map its own questions onto the patient record without
                hard-coding field names. ManaNotes has no clinic-defined custom
                patient fields: this is the complete, fixed set, and
                `ExtraInformation` is the free-text catch-all for anything
                without a structured home. Only `FirstName` and `LastName` are
                required.
            security: [{ OAuth2: [patients:read] }]
            responses:
                '200':
                    description: The patient-field catalogue
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/PatientField'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }

    /practitioners:
        get:
            tags: [Reference]
            summary: List clinic practitioners
            security: [{ OAuth2: [appointments:read] }]
            responses:
                '200':
                    description: Practitioners in the client's clinic
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/Practitioner'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }

    /practitioners/{id}/working-hours:
        parameters:
            - $ref: '#/components/parameters/Id'
        get:
            tags: [Reference]
            summary: List a practitioner's working hours & breaks
            description: >-
                A practitioner's weekly working hours plus break times — the
                clinic configuration that shapes availability. There is no
                separate "blocked time" resource; blocked time is modelled as an
                appointment. Times are clinic-local (`Pacific/Auckland`) in
                `HH:mm`, and `Day` is a weekday enum. Multi-site clinics keep a
                separate weekly pattern per site — each row's `LocationId` says
                which site it applies to (null = the clinic's default site).
            security: [{ OAuth2: [appointments:read] }]
            responses:
                '200':
                    description: The practitioner's weekly working hours
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/WorkingHour'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /practitioners/{id}/availability:
        parameters:
            - $ref: '#/components/parameters/Id'
        get:
            tags: [Reference]
            summary: Get a practitioner's open appointment slots
            description: >-
                Computes open appointment slots for a service across a date
                range, honouring working hours, breaks, booking lead time and
                existing active appointments (cancelled and no-show
                appointments free their slot). Read it before
                `POST /appointments` to pick a free slot — the create and
                reschedule endpoints also reject overlapping bookings with
                `409`. Dates are `yyyy-MM-dd`; slots are returned in
                clinic-local time (`Pacific/Auckland`). Unlike the public
                booking portal, this trusted channel does **not** require
                online booking to be enabled.
            security: [{ OAuth2: [appointments:read] }]
            parameters:
                - name: billableItemId
                  in: query
                  required: true
                  schema: { type: string }
                  description: >-
                      The service to compute slots for; its duration sizes each
                      slot. See `GET /billable-items`.
                - name: from
                  in: query
                  required: true
                  schema: { type: string, format: date }
                  example: '2026-07-06'
                  description: First day of the range (clinic-local calendar date).
                - name: to
                  in: query
                  required: true
                  schema: { type: string, format: date }
                  example: '2026-07-12'
                  description: >-
                      Last day of the range, inclusive (clinic-local calendar
                      date). If the practitioner doesn't take same-day
                      bookings, today in `Pacific/Auckland` is never included.
                - name: locationId
                  in: query
                  required: false
                  schema: { type: string }
                  description: >-
                      Compute slots inside one site's working hours — see `GET
                      /locations`. Existing appointments block slots regardless
                      of site (a practitioner is one person). Omitted = every
                      site the practitioner works at.
            responses:
                '200':
                    description: Open slots across the range
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/TimeSlot'
                '400': { $ref: '#/components/responses/BadRequest' }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }
                '404': { $ref: '#/components/responses/NotFound' }

    /locations:
        get:
            tags: [Reference]
            summary: List clinic locations (sites)
            description: >-
                The clinic's physical sites, default first. `LocationId` fields
                elsewhere refer to these ids. Deactivated sites (`Active:
                false`) stay listed because historical appointments still
                reference them, but they cannot take new bookings. Returns an
                empty list for solo practitioners with no clinic and for
                clinics not yet migrated to locations — treat that as a single
                implicit location.
            security: [{ OAuth2: [appointments:read] }]
            responses:
                '200':
                    description: The clinic's locations
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/Location'
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }

    /billable-items:
        get:
            tags: [Reference]
            summary: List billable items (bookable services/products)
            security: [{ OAuth2: [appointments:read] }]
            parameters:
                - $ref: '#/components/parameters/Limit'
                - $ref: '#/components/parameters/Offset'
                - $ref: '#/components/parameters/Search'
            responses:
                '200':
                    description: Billable items
                    content:
                        application/json:
                            schema:
                                type: object
                                properties:
                                    data:
                                        type: array
                                        items:
                                            $ref: '#/components/schemas/BillableItem'
                                    totalCount: { type: integer }
                '401': { $ref: '#/components/responses/Unauthorized' }
                '403': { $ref: '#/components/responses/Forbidden' }

components:
    securitySchemes:
        OAuth2:
            type: oauth2
            description: Self-hosted OAuth 2.0 client-credentials (M2M) grant.
            flows:
                clientCredentials:
                    tokenUrl: https://api.mananotes.co.nz/api/v1/oauth/token
                    scopes:
                        appointments:read: Read appointments, reference data and the clinic profile
                        appointments:write: Create/update/delete appointments and change their status
                        patients:read: Read patients and the patient-field catalogue
                        patients:write: Create/update/delete patients
                        attachments:read: List/read a patient's files and download their bytes
                        attachments:write: Upload and delete files

    parameters:
        Id:
            name: id
            in: path
            required: true
            schema: { type: string }
            description: Resource id (Mongo ObjectId).
        Limit:
            name: limit
            in: query
            required: false
            schema: { type: integer, minimum: 1, maximum: 200 }
        Offset:
            name: offset
            in: query
            required: false
            schema: { type: integer, minimum: 0 }
        Search:
            name: search
            in: query
            required: false
            schema: { type: string }
            description: >-
                Case-insensitive search term. See the endpoint description
                for the fields it matches.

    responses:
        BadRequest:
            description: Invalid request (validation failed)
            content:
                application/json:
                    schema: { $ref: '#/components/schemas/Error' }
        Unauthorized:
            description: Missing/invalid token or unknown/deactivated client
            content:
                application/json:
                    schema: { $ref: '#/components/schemas/Error' }
        Forbidden:
            description: The client lacks the required scope
            content:
                application/json:
                    schema: { $ref: '#/components/schemas/Error' }
        NotFound:
            description: Resource not found (or outside the client's clinic)
            content:
                application/json:
                    schema: { $ref: '#/components/schemas/Error' }
        Conflict:
            description: Conflict (e.g. duplicate patient)
            content:
                application/json:
                    schema: { $ref: '#/components/schemas/Error' }
        RateLimited:
            description: Too many requests
            content:
                application/json:
                    schema: { $ref: '#/components/schemas/Error' }

    schemas:
        Error:
            type: object
            properties:
                error:
                    type: object
                    properties:
                        code: { type: string, example: BAD_REQUEST }
                        message: { type: string }

        Me:
            type: object
            properties:
                clientId: { type: string }
                name: { type: string }
                clinicId: { type: string, nullable: true }
                practitionerId: { type: string }
                scopes:
                    type: array
                    items: { type: string }
                active: { type: boolean }

        Address:
            type: object
            additionalProperties: false
            properties:
                Line1: { type: string }
                Line2: { type: string }
                Suburb: { type: string }
                City: { type: string }
                PostCode: { type: string }
                Country: { type: string }
                Latitude: { type: number }
                Longitude: { type: number }

        Employer:
            type: object
            additionalProperties: false
            properties:
                EmployerName: { type: string }
                Address: { $ref: '#/components/schemas/Address' }

        EmergencyContact:
            type: object
            additionalProperties: false
            description: An additional emergency contact.
            properties:
                Name: { type: string }
                Relationship: { type: string }
                PhoneNumber: { type: string }
                CountryCode: { type: string }
                Notes: { type: string }

        PhoneNumber:
            type: object
            additionalProperties: false
            description: An additional phone number on the patient record.
            properties:
                Number: { type: string }
                CountryCode: { type: string }
                Type:
                    type: string
                    description: Free-text label, e.g. Mobile, Home or Work.
                IsPreferred: { type: boolean }

        PatientWritable:
            type: object
            additionalProperties: false
            description: Writable patient fields. Unknown fields are rejected.
            properties:
                FirstName: { type: string }
                LastName: { type: string }
                PreferredFirstName: { type: string }
                Pronouns: { type: string }
                Email: { type: string, format: email }
                Mobile: { type: string }
                NHI: { type: string, description: NZ National Health Index }
                Gender: { type: string }
                Title: { type: string }
                UTCDateOfBirth:
                    type: string
                    format: date-time
                    description: Calendar day — send UTC midnight, e.g. `1991-04-22T00:00:00Z`.
                UTCDateOfFirstVisit: { type: string, format: date-time }
                DeletedOnUTCDateTime: { type: string, format: date-time }
                Address: { $ref: '#/components/schemas/Address' }
                Address1: { type: string }
                Employer: { $ref: '#/components/schemas/Employer' }
                EthnicityCode: { type: string }
                EthnicityDescription: { type: string }
                OccupationCode: { type: string }
                OccupationDescription: { type: string }
                EmploymentStatusCode: { type: string }
                EmploymentStatusDescription: { type: string }
                OtherEmployment: { type: string }
                InPaidEmployment: { type: boolean }
                WorkTypeCode: { type: string }
                WorkTypeDescription: { type: string }
                NextOfKin: { type: string }
                NextOfKinPhone: { type: string }
                EmergencyContactName: { type: string }
                EmergencyContactRelationship: { type: string }
                EmergencyContactCountryCode: { type: string }
                EmergencyContactPhoneNumber: { type: string }
                EmergencyContacts:
                    type: array
                    description: Additional emergency contacts.
                    items: { $ref: '#/components/schemas/EmergencyContact' }
                HomePhone: { type: string }
                WorkPhone: { type: string }
                PhoneNumbers:
                    type: array
                    description: Additional phone numbers.
                    items: { $ref: '#/components/schemas/PhoneNumber' }
                PatientSmsConsent:
                    type: boolean
                    description: False stops reminder SMS to this patient.
                GP: { type: string }
                ReferredBy: { type: string }
                ReferenceId: { type: string }
                MedicalHistory: { type: string }
                SurgicalHistory: { type: string }
                FamilyHistory: { type: string }
                SocialHistory: { type: string }
                GynaecologicalHistory: { type: string }
                Investigations: { type: string }
                RecreationalDrugs: { type: string }
                ExtraInformation:
                    type: string
                    description: >-
                        Free-text notes shown on the patient record — alerts,
                        preferences, anything without a structured field.
                IsSmoking: { type: boolean }
                IsVegan: { type: boolean }
                IsVegetarian: { type: boolean }
                Alcohol: { type: boolean }
                IsDeleted: { type: boolean }
                HomeLocationId:
                    type: string
                    description: >-
                        The patient's home clinic location (site) — see `GET
                        /locations`. Must be one of the clinic's locations.
                        Omitted on create: the practitioner's home location,
                        else the clinic's default. Omitted on update: left
                        unchanged.

        PatientCreate:
            allOf:
                - $ref: '#/components/schemas/PatientWritable'
                - type: object
                  required: [FirstName, LastName]

        PatientUpdate:
            $ref: '#/components/schemas/PatientWritable'

        Patient:
            type: object
            description: A patient record (read shape).
            properties:
                id: { type: string }
                PractitionerId: { type: string }
                FirstName: { type: string }
                LastName: { type: string }
                PreferredFirstName: { type: string, nullable: true }
                Pronouns: { type: string, nullable: true }
                Email: { type: string, nullable: true }
                Mobile: { type: string, nullable: true }
                NHI: { type: string, nullable: true }
                Gender: { type: string, nullable: true }
                Title: { type: string, nullable: true }
                UTCDateOfBirth:
                    type: string
                    format: date-time
                    nullable: true
                    description: Calendar day, as UTC midnight of the day.
                HomeLocationId:
                    type: string
                    nullable: true
                    description: >-
                        The patient's home site; null on patients that predate
                        multi-location — treat as the clinic's default
                        location.
                Address: { $ref: '#/components/schemas/Address' }
                Employer: { $ref: '#/components/schemas/Employer' }
                EmploymentStatusDescription: { type: string, nullable: true }
                OtherEmployment: { type: string, nullable: true }
                WorkTypeDescription: { type: string, nullable: true }
                EmergencyContactName: { type: string, nullable: true }
                EmergencyContactRelationship: { type: string, nullable: true }
                EmergencyContactCountryCode: { type: string, nullable: true }
                EmergencyContactPhoneNumber: { type: string, nullable: true }
                EmergencyContacts:
                    type: array
                    items: { $ref: '#/components/schemas/EmergencyContact' }
                PhoneNumbers:
                    type: array
                    items: { $ref: '#/components/schemas/PhoneNumber' }
                PatientSmsConsent: { type: boolean, nullable: true }
                GynaecologicalHistory: { type: string, nullable: true }
                ExtraInformation: { type: string, nullable: true }
                IsDeleted: { type: boolean, nullable: true }
                createdAt: { type: string, format: date-time }
                updatedAt: { type: string, format: date-time }

        PatientResponse:
            type: object
            properties:
                data: { $ref: '#/components/schemas/Patient' }

        PatientList:
            type: object
            properties:
                data:
                    type: array
                    items: { $ref: '#/components/schemas/Patient' }
                totalCount: { type: integer }
                limit: { type: integer, nullable: true }
                offset: { type: integer, nullable: true }

        ReadCode:
            type: object
            additionalProperties: false
            required: [ReadCode, Side]
            properties:
                ReadCode: { type: string, description: ACC diagnosis Read code }
                Side: { type: string, example: Left }

        AppointmentInjury:
            type: object
            additionalProperties: false
            description: Inline injury to lodge with a new appointment.
            required: [ACCNumber, InjuryUTCDate, ReadCodes]
            properties:
                ACCNumber: { type: string, description: ACC45 claim number }
                InjuryUTCDate:
                    type: string
                    format: date-time
                    description: Calendar day of the accident — send UTC midnight, e.g. `2026-06-18T00:00:00Z`.
                ReadCodes:
                    type: array
                    items: { $ref: '#/components/schemas/ReadCode' }
                PatientId: { type: string }
                ACCNumberUsedByAcupuncture: { type: boolean }
                CauseOfAccident: { type: string }
                CoverStatus: { type: string }
                InjuryCausedByAccident: { type: string }
                MedicationAndOrSupplements: { type: string }
                PreviousIllnesses: { type: string }
                PreviousSurgeryOrFractures: { type: string }

        AppointmentType:
            type: string
            deprecated: true
            description: >-
                Deprecated. Appointment.Type is retired: it is no longer
                written, is null on every new appointment, and only legacy
                rows still carry a value. Use BillableItemId (the service
                booked, ACC-claimable or not) and InjuryId (the ACC claim
                being treated) to describe an appointment.
            enum:
                - ACC_INITIAL
                - ACC_FOLLOWUP
                - ALL_APPOINTMENTS
                - OTHER
                - SELF_FUND_FOLLOWUP
                - SELF_FUND_INITIAL

        AppointmentCreate:
            type: object
            additionalProperties: false
            required: [BillableItemId, UTCStartTime, UTCEndTime]
            properties:
                BillableItemId: { type: string }
                UTCStartTime: { type: string, format: date-time }
                UTCEndTime: { type: string, format: date-time }
                Type:
                    allOf: [{ $ref: '#/components/schemas/AppointmentType' }]
                    deprecated: true
                    description: >-
                        Deprecated and ignored. Still accepted so existing
                        integrations keep working, but never stored — pass
                        BillableItemId and InjuryId instead.
                Notes: { type: string }
                PatientId: { type: string, description: Link an existing patient }
                InjuryId: { type: string }
                PractitionerId: { type: string }
                RoomId: { type: string }
                LocationId:
                    type: string
                    description: >-
                        Clinic location (site) to book at — see `GET
                        /locations`. Must be one of the clinic's active
                        locations. Omitted: the appointment practitioner's home
                        location, else the clinic's default.
                TreatmentId: { type: string }
                RecurrenceRule:
                    type: string
                    description: RRULE, e.g. FREQ=WEEKLY;INTERVAL=1;BYDAY=TU
                WorkflowIds:
                    type: array
                    items: { type: string }
                Patient: { $ref: '#/components/schemas/PatientCreate' }
                Injury: { $ref: '#/components/schemas/AppointmentInjury' }

        AppointmentUpdate:
            type: object
            additionalProperties: false
            properties:
                BillableItemId: { type: string }
                UTCStartTime: { type: string, format: date-time }
                UTCEndTime: { type: string, format: date-time }
                Type:
                    allOf: [{ $ref: '#/components/schemas/AppointmentType' }]
                    deprecated: true
                    description: >-
                        Deprecated and ignored. Still accepted so existing
                        integrations keep working, but never stored — pass
                        BillableItemId and InjuryId instead.
                Notes: { type: string }
                PatientId: { type: string }
                InjuryId: { type: string }
                PractitionerId: { type: string }
                RoomId: { type: string }
                LocationId:
                    type: string
                    description: >-
                        Move the appointment to this clinic location (site) —
                        see `GET /locations`. Must be an active location,
                        unless it is the appointment's current one.
                TreatmentId: { type: string }
                WorkflowIds:
                    type: array
                    items: { type: string }
                UpdateAssociatedTreatment:
                    type: boolean
                    description: Propagate time changes to the linked treatment.

        Appointment:
            type: object
            properties:
                id: { type: string }
                PractitionerId: { type: string }
                PatientId: { type: string, nullable: true }
                PatientName: { type: string, nullable: true }
                InjuryId: { type: string, nullable: true }
                BillableItemId: { type: string, nullable: true }
                RoomId: { type: string, nullable: true }
                LocationId:
                    type: string
                    nullable: true
                    description: >-
                        The site this appointment is at; null on rows that
                        predate multi-location — treat as the clinic's default
                        location.
                TreatmentId: { type: string, nullable: true }
                Status:
                    type: string
                    enum:
                        [
                            NEW,
                            ARRIVED,
                            WITH_PRACTITIONER,
                            COMPLETED,
                            NO_SHOW,
                            CANCELLED,
                            PENDING,
                        ]
                    description: >-
                        ARRIVED is the patient checked in; WITH_PRACTITIONER
                        is the patient in the room being treated; COMPLETED is
                        the visit over. ARRIVED, WITH_PRACTITIONER and
                        COMPLETED all count as attended.
                Type:
                    allOf: [{ $ref: '#/components/schemas/AppointmentType' }]
                    nullable: true
                    deprecated: true
                    description: >-
                        Deprecated. Null for every appointment created since
                        the field was retired; legacy rows keep their old
                        value. Read BillableItemId and InjuryId instead.
                UTCStartTime: { type: string, format: date-time }
                UTCEndTime: { type: string, format: date-time }
                Notes: { type: string, nullable: true }
                RecurrenceRule: { type: string, nullable: true }
                RecurrenceSeriesId: { type: string, nullable: true }
                ACCInvoiceStatus: { type: string, nullable: true }
                WorkflowIds:
                    type: array
                    items: { type: string }
                createdAt: { type: string, format: date-time }
                updatedAt: { type: string, format: date-time }

        AppointmentResponse:
            type: object
            properties:
                data: { $ref: '#/components/schemas/Appointment' }

        AppointmentStatusUpdate:
            type: object
            additionalProperties: false
            required: [Status]
            properties:
                Status:
                    type: string
                    enum:
                        [
                            PENDING,
                            NEW,
                            ARRIVED,
                            WITH_PRACTITIONER,
                            COMPLETED,
                            NO_SHOW,
                            CANCELLED,
                        ]
                    description: >-
                        New status. PENDING (tentative) → NEW (booked) →
                        ARRIVED (checked in) → WITH_PRACTITIONER (in the
                        room) → COMPLETED (visit over), or NO_SHOW /
                        CANCELLED.

        AttachmentCreate:
            type: object
            additionalProperties: false
            description: >-
                A file to attach to a patient. Unknown fields are rejected.
            required: [fileName, mimeType, fileData]
            properties:
                fileName:
                    type: string
                    maxLength: 255
                    example: intake-form.pdf
                    description: File name including its extension.
                mimeType:
                    type: string
                    description: >-
                        MIME type of the file. Allowed: PDF, JPEG, PNG, GIF,
                        Word, Excel and plain text.
                    enum:
                        - application/pdf
                        - image/jpeg
                        - image/jpg
                        - image/png
                        - image/gif
                        - application/msword
                        - application/vnd.openxmlformats-officedocument.wordprocessingml.document
                        - text/plain
                        - application/vnd.ms-excel
                        - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                fileData:
                    type: string
                    format: byte
                    description: >-
                        The file bytes, base64-encoded — no `data:` URL prefix,
                        no whitespace. The decoded size may be at most 10MB.
                description:
                    type: string
                    description: Optional caption shown with the file.
                injuryId:
                    type: string
                    description: >-
                        File it under one of the patient's injuries (ACC
                        claims) instead of the patient record itself.

        Attachment:
            type: object
            description: A file on a patient record (metadata only).
            properties:
                id: { type: string }
                fileName: { type: string, example: intake-form.pdf }
                fileSize:
                    type: integer
                    description: Size in bytes.
                fileType:
                    type: string
                    example: pdf
                    description: File extension, lower-case, no dot.
                mimeType: { type: string, example: application/pdf }
                description: { type: string, nullable: true }
                uploadedAt: { type: string, format: date-time }
                patientId:
                    type: string
                    nullable: true
                    description: The patient the file is on, when filed on the patient record.
                injuryId:
                    type: string
                    nullable: true
                    description: The injury the file is under, when filed under an injury.
                PractitionerId: { type: string }
                createdAt: { type: string, format: date-time }
                updatedAt: { type: string, format: date-time }

        AttachmentResponse:
            type: object
            properties:
                data: { $ref: '#/components/schemas/Attachment' }

        Clinic:
            type: object
            description: >-
                The clinic's profile. The logo is deliberately not included.
            properties:
                id: { type: string }
                Name: { type: string, example: City Physio }
                LegalName: { type: string, nullable: true }
                Code: { type: string, nullable: true }
                Description: { type: string, nullable: true }
                ContactName: { type: string, nullable: true }
                ContactNumber: { type: string, nullable: true }
                ContactEmail: { type: string, nullable: true }
                Website: { type: string, nullable: true }
                Facebook: { type: string, nullable: true }
                Instagram: { type: string, nullable: true }
                OnlineBookingEnabled: { type: boolean, nullable: true }
                Locations:
                    type: array
                    description: The clinic's sites — the same shape as `GET /locations`.
                    items: { $ref: '#/components/schemas/Location' }

        PatientFieldProperty:
            type: object
            properties:
                name: { type: string }
                type: { $ref: '#/components/schemas/PatientFieldType' }
                label: { type: string }

        PatientFieldType:
            type: string
            enum: [string, boolean, date-time, email, object, array]

        PatientField:
            type: object
            description: >-
                One field of the patient record, from the fixed catalogue
                returned by `GET /patient-fields`.
            properties:
                name:
                    type: string
                    example: PreferredFirstName
                    description: The field name as used in patient bodies and responses.
                type: { $ref: '#/components/schemas/PatientFieldType' }
                label: { type: string, example: Preferred name }
                group:
                    type: string
                    enum:
                        - identity
                        - contact
                        - address
                        - emergency
                        - employment
                        - history
                        - lifestyle
                        - admin
                required:
                    type: boolean
                    description: Required when creating a patient (only FirstName and LastName).
                description:
                    type: string
                    description: What the value means / how the app uses it.
                properties:
                    type: array
                    description: Shape of an object / array-of-object field.
                    items: { $ref: '#/components/schemas/PatientFieldProperty' }

        Practitioner:
            type: object
            properties:
                id: { type: string }
                email: { type: string }
                PreferredName: { type: string, nullable: true }
                ProviderFirstname: { type: string, nullable: true }
                ProviderLastname: { type: string, nullable: true }
                ServiceCode: { type: string, nullable: true }
                ClinicId: { type: string, nullable: true }
                HomeLocationId:
                    type: string
                    nullable: true
                    description: >-
                        The practitioner's home site — where their bookings
                        land when `LocationId` is omitted.
                LocationIds:
                    type: array
                    items: { type: string }
                    description: >-
                        The sites this practitioner works at. Empty = the
                        clinic's default location only.
                Active: { type: boolean, nullable: true }

        BillableItem:
            type: object
            properties:
                id: { type: string }
                Code: { type: string }
                Name: { type: string }
                Description: { type: string }
                UnitPrice: { type: number }
                Duration: { type: integer, nullable: true }
                Type: { type: string, enum: [Service, Product] }
                Active: { type: boolean, nullable: true }
                IsACCClaimable: { type: boolean, nullable: true }

        Location:
            type: object
            description: >-
                A clinic location (physical site). Exactly one per clinic is
                the default; records written before the clinic adopted
                multi-location carry no `LocationId` and belong to the default
                site.
            properties:
                id: { type: string }
                Name: { type: string, example: City Branch }
                IsDefault:
                    type: boolean
                    description: >-
                        The clinic's default site — also owns legacy records
                        with no location stamp.
                Active:
                    type: boolean
                    description: >-
                        Deactivated sites are historical — they cannot take new
                        appointments.
                OnlineBookingEnabled:
                    type: boolean
                    description: >-
                        Whether the public booking portal offers this site.
                ContactNumber: { type: string, nullable: true }
                ContactEmail: { type: string, nullable: true }
                ClinicAddress: { $ref: '#/components/schemas/Address' }

        WeekDay:
            type: string
            enum:
                - MONDAY
                - TUESDAY
                - WEDNESDAY
                - THURSDAY
                - FRIDAY
                - SATURDAY
                - SUNDAY

        TimeSlot:
            type: object
            description: >-
                A single open appointment slot, in clinic-local time
                (`Pacific/Auckland`).
            properties:
                Date: { type: string, format: date, example: '2026-07-06' }
                StartTime:
                    type: string
                    example: '09:00'
                    description: Clinic-local start time (`HH:mm`).
                EndTime:
                    type: string
                    example: '09:30'
                    description: Clinic-local end time (`HH:mm`).

        BreakTime:
            type: object
            description: A recurring weekly break inside a working day.
            properties:
                id: { type: string }
                Name: { type: string, example: Lunch }
                LocationId:
                    type: string
                    nullable: true
                    description: >-
                        The site this break applies to; null = the clinic's
                        default location.
                Day: { $ref: '#/components/schemas/WeekDay' }
                StartTime:
                    type: string
                    example: '12:00'
                    description: Clinic-local start time (`HH:mm`).
                EndTime:
                    type: string
                    example: '13:00'
                    description: Clinic-local end time (`HH:mm`).

        WorkingHour:
            type: object
            description: >-
                A practitioner's working hours for one weekday at one site,
                with its breaks.
            properties:
                id: { type: string }
                PractitionerId: { type: string }
                LocationId:
                    type: string
                    nullable: true
                    description: >-
                        The site this weekly slice applies to; null = the
                        clinic's default location.
                Day: { $ref: '#/components/schemas/WeekDay' }
                StartTime:
                    type: string
                    example: '09:00'
                    description: Clinic-local start time (`HH:mm`).
                EndTime:
                    type: string
                    example: '17:00'
                    description: Clinic-local end time (`HH:mm`).
                BreakTimes:
                    type: array
                    items: { $ref: '#/components/schemas/BreakTime' }
