openapi: 3.0.3
info:
  title: Ruva POS API
  description: |
    The Ruva POS API connects your own systems — your accounts, a website, an app or a report of your own — to
    your own business on Ruva. It is the API Ruva's back office, kitchen display and your guests' phones use, so
    every call reads and writes your business's live data, and only yours.
    This reference covers what an integration needs — auth, the catalogue, orders, payments, stock, bookings
    and webhooks — grouped by area. A few back-office settings are not described here; if you need one you
    cannot find, ask Ruva support and we will tell you how to reach it.

    ## Auth
    All routes are namespaced under `/api/v1` and use JWT bearer authentication, except the routes explicitly
    marked **Public** below (health checks, digital receipts, customer self-order QR, and inbound webhooks).
    Obtain a token with `POST /api/v1/auth/login`, then send it as `Authorization: Bearer <accessToken>`.
    A token is checked against its session on every request: once the session is signed out, or the person is switched
    off or given another role, it answers 401 and a refresh gives a token for who they are now. When that check cannot
    be made the answer is `503` with `error:"auth_check_unavailable"` and a `Retry-After` header: the token is still
    good, so keep it and retry rather than refreshing.

    Endpoints marked **Manager-gated** additionally require the caller's JWT `role` claim to be one of
    `ADMIN`, `SUPER_ADMIN`, or `MANAGER` — otherwise the server returns `403 forbidden` with error code
    `manager_required`.

    ## Access
    API access comes with a Ruva subscription: you build against your own business, with keys made in Back Office -> Developer. There is no free sandbox.
    Try every endpoint interactively at [`/docs`](/docs) (Swagger UI), signed in as your own business.

    ## Rate limits
    Every bucket is someone's own (see the `x-rate-limit` vendor extension on each affected operation):
    `login` 10/min per client, `agentLogin` 10/min per client (a Ruva sales agent's own sign-in, not part of the API), `agentPage` 30/min per client (the agent sign-in page), `refresh` 30/min per client, `sync` 600/min per client, `health` 300/min per client (`/ready` and the status page), `pairing` 10/min per client,
    `passwordReset` 10/min per client, `optOut` 10/min per client (opening the stop link in a guest's message, a page rather than an API route), `optOutLink` 10/min per stop link (pressing it, also a mail provider's one-click call; spent only once the token verifies),
    `pairStart` 20/min per client, `pairPoll` 240/min per client, `pairClaim` 30/min per client, `pairToken` 90/min per pairing token (spent only once the pairing is found) and `pairClaimBusiness` 20/min per business (scan to pair),
    `signUp` 5/min per client (the public sign-up), `signUpOptions` 60/min per client (reading what sign-up offers, which spends nothing of `signUp`),
    `qr` 600/min per client, `qrFeedback` 30/min per client (a guest rating an order),
    `qrArrival` 6/min per order (a takeaway guest telling the pass they are here; spent only once the order's key has opened it),
    `qrCall` 60/hour per client and `qrCallOrder` 10/hour per order (a guest calling a waiter or asking for the bill; the order's spent only once its key has opened it),
    `qrEmailCode` 30/min per client (a guest confirming their email with a one-time code),
    `qrReceiptEmail` 10/hour per client (a guest asking for their receipt by email after ordering: a kiosk with no printer),
    `qrSample` 20/min per sample café visitor (every guest door naming the public sample café, keyed by client, on top of `qr`),
    `qrScan` 5/hour per client (the menu scans QR insights counts, for each venue a client scans at: past it the menu is still served and the scan is not counted),
    `qrTableCode` 5/min per address and venue (a guest's wrong table codes, for each venue an address orders at: past it the unpaid order is refused `429 table_code_paused` until the minute is up, and a paid order is still taken),
    `qrTableCodeTable` 10/min per table (wrong table codes from anywhere at one table, counted once across every server: past it that table's unpaid orders wait a minute, its paid orders do not),
    `webhook` 1000/min per client, `whatsapp` 6000/min per client (Meta's WhatsApp webhook alone: the number is shared, so it carries another application's traffic too),
    `whatsappOrderGuest` 10/hour per guest number and `whatsappOrderVenue` 120/hour per location (WhatsApp ordering: each answer is a metered message the venue pays for; past either nothing is placed or sent),
    `inboundMail` 600/min per client (the mail provider's received-message webhook: support mail),
    `booking` 60/min per client (shared with public click-and-collect),
    `bookingEnquiry` 5/hour per client (a large party's enquiry, besides `booking`; one client network also holds at most three unanswered at a location),
    `platformToken` 20/min per client, `platformApi` 600/min per API app, whichever address the app calls
    from, `ticketPrint` 60/min per signed-in device (a kitchen screen's reprints), `kioskFunnel` 6/min per signed-in device (a kiosk's counts of where its guests get to), `kioskOrder` 60/min per signed-in device (a paired kiosk's orders), `kioskLoyalty` 10/min per signed-in device and `kioskLoyaltyBusiness` 30/min per business (a regular's number typed at a kiosk),
    `socketTicket` 30/min per signed-in device (a browser's live-update socket tickets), `countedStock` 30/min per signed-in device (a till's read of the counted stock it shares offline), `billingWrite` 10/min per business
    (the owner's billing changes, each of which may ask PayFast or Yoco), `bookingPage` 10/min per business (a manager changing the booking page, whose addresses are kept for good), `checklistDigest` 5/hour per business (a manager's
    press of "send the checklist digest", which mails the business's own people), `trialMobileCode` 5/hour per business (WhatsApp codes
    the owner sends to confirm the mobile a free trial waits for), `billingLink` 10/min per client (a "Change how you pay"
    link's page posting its ticket), `secondFactor` 10/min per signed-in device (code attempts at the second factor), `pinSeat` 20/min per signed-in device (a person seated at a till's PIN pad, `POST /auth/pin`, on top of the manager-PIN lockout), `ledgrKey` 10/hour per client (an owner
    pasting a Ledgr key, which is checked with Ledgr there and then), `ownPin` 10/hour per person (a person setting
    their own PIN, on top of `login`), `staffPin` 30/hour per person (a manager setting a PIN for someone else: a create or invite
    with a PIN, or a reset), `ownPassword` 5/hour per person (a signed-in person changing their own password,
    on top of `login`), `ownName` 20/hour per person (a signed-in person changing their own name, on top of `login`), and `agentRequest` 5/hour per business (the owner asking the agent they forgot to name at sign-up, refused asks counted). "Per client" is the address the request reached our own proxy from; an `X-Forwarded-For` the caller
    writes does not change it. Exceeding a bucket returns `429 Too Many Requests` with a `Retry-After` header.

    ## Errors
    Failures use a uniform JSON body (see `ErrorBody`): `{ "error": "<code>", "message": "<detail>",
    "correlationId": "<id?>" }`. Business-rule failures typically return `409` with a specific `error` code
    (e.g. `voucher_expired`, `order_already_paid`); validation failures return `400` with `error:
    "validation_error"` or a specific code; missing/invalid JWTs return `401`; role failures return `403`.
    A body that cannot be read (not JSON, a field missing or of the wrong kind) returns `400` with `error: "bad_request"` and
    the same message whichever field it was, so check the body against the request's schema.
    A business whose plan is not paid (a free trial that ended unpaid, a cancelled plan past its last day, a failed
    debit past its grace) answers `402 plan_unpaid` on every signed-in route but sign-in, the licence read and redeem,
    billing, terms acceptance and `/data/*`; paying lifts it at once. A licence that cannot be read is `503`, never `402`.
  version: "1.0.0"
  contact:
    name: Ruva POS
servers:
  - url: /
    description: This server (the origin serving these docs)
  - url: https://www.ruvapos.com
    description: Hosted
security:
  - bearerAuth: []
tags:
  - name: System
    description: Health and readiness probes. Public, unauthenticated.
  - name: Auth
    description: Login, token refresh, and the current-user profile.
  - name: Devices
    description: The business's signed-in devices — pinned surface, prep station, remote sign-out (T-2.4).
  - name: Catalogue
    description: Categories, products, modifier groups, and tax rates. Reads need VIEW_CATALOGUE, which every role holds; mutations are manager-gated.
  - name: Staff
    description: Staff administration (PINs, roles, deactivation) and shift clock-in/clock-out. Administration routes are manager-gated.
  - name: Locations
    description: Locations / business profile (V16) — address, VAT number, receipt header/footer, and the branding logo. Mutations are manager-gated; logo bytes are public.
  - name: Floor & Tables
    description: Floor plan (tables, zones), seating, table transfer/merge, and reservations.
  - name: Orders
    description: Order lifecycle (create, add lines, checkout, fire to kitchen, split), plus voids/comps/discounts.
  - name: Kitchen
    description: Kitchen Display System (KDS) tickets — bump, rush, recall.
  - name: Tabs
    description: Bar tabs — open and settle.
  - name: Payments
    description: Payment initiation against SA payment providers (Yoco and PayFast; SnapScan is not offered right now) and cash capture.
  - name: Refunds
    description: Manager-approved refunds, returns by the line, and exchanges against a settled transaction.
  - name: Webhooks
    description: Public, HMAC-verified inbound webhooks from payment providers.
  - name: Sync
    description: Offline-first sync engine — push queued mutations, pull server changes since a cursor, and a WebSocket broadcast channel.
  - name: Training
    description: The training academy, with courses per role, a till's checks and the team's progress (T-15.5), and each release's notes (T-15.7).
  - name: Reports
    description: Dashboard, shift X/Z reports, VAT201, heatmap, server performance, and audit logs (discounts/voids/comps). Includes the Ruva-to-Ledgr journal bridge. A CSV or PDF download is refused `403 second_factor_required` to a session that has not typed its code where the business requires a second factor (T-37.4); the JSON is not.
  - name: Loyalty & Vouchers
    description: Discount vouchers (manual and birthday) and redemption.
  - name: Gift Cards
    description: Issue, look up, and redeem in-store gift card credit.
  - name: House Accounts
    description: B2B credit accounts (guesthouses, corporates) — charge and settle postings.
  - name: Inventory
    description: 86 list (out-of-stock flags), wastage logging, low-stock alerts, and manual stock adjustments.
  - name: Suppliers & Purchasing
    description: Suppliers and purchase orders, including goods receiving into stock.
  - name: Pricing
    description: Time-based pricing rules (happy hour, lunch specials, day-of-week promos).
  - name: Click & Collect
    description: >-
      Online ordering for in-store collection (V34). Stock is RESERVED, never depleted, so on-hand
      stays true and `available = on_hand - reserved`. Unpaid holds expire or a shop's availability
      drains away silently. The public endpoints need no JWT and are rate-limited.
  - name: Rota & Delivery
    description: >-
      Staff rota and third-party delivery ingestion (V32). A rota is a plan kept separate
      from attendance, costed at today's rate; delivery ingestion is idempotent per
      (platform, external id) and records gross, commission and payout separately.
  - name: Menus & Invoices
    description: >-
      Central menu publishing and customer invoices (V33). Menus are versioned so a publish
      is atomic; an issued invoice is immutable and corrected by credit note. A sale can only
      ever be invoiced once.
  - name: Saved Reports
    description: >-
      Saved report templates, scheduled email delivery, labour cost against sales, sales
      grouped by brand/supplier/category, and drilldown (V31). A template stores a date
      PRESET, never two dates, so a saved report follows the calendar instead of reporting
      the same month forever. Delivery is idempotent per period. Manager-gated except
      /reports/presets.
  - name: Commission
    description: >-
      Staff commission (V30). Schemes describe the arrangement; entries record what was
      earned, per line, with the rate frozen so a report can never disagree with a payslip.
      Accrual is not an endpoint — it happens inside settlement and reverses inside a refund.
      All routes are manager-gated, because commission is pay.
  - name: Marketing
    description: >-
      Customer segments, campaigns, lifecycle automations and consent (V29). Segments are
      rules evaluated on demand, never stored member lists. Every campaign recipient gets a
      row — suppressed ones carry the reason — so sent + failed + suppressed always accounts
      for the audience. Lifecycle messages send once per occurrence via a dedupe key. All
      writes are manager-gated.
  - name: Quotes & Special Orders
    description: >-
      Business promised but not yet rung up (V28). A quote is a priced offer that expires
      and may become a sale; a special order is goods brought in for one named customer,
      usually against a deposit. Quotes reserve no stock and hold no money; special-order
      deposits are captured payments on a real sale, so they count towards the shift that
      took them.
  - name: Waitlist
    description: Walk-in waitlist queue (F-09) — add, seat, remove.
  - name: Checklists
    description: Digital task checklists — manager-authored templates and per-day runs staff tick off. All routes require a JWT; template CRUD is manager-gated.
  - name: Customer QR
    description: Public self-order PWA endpoints served from a table QR code — no JWT required.
  - name: Booking
    description: Public guest online-booking API — a restaurant website takes reservations. No JWT; rate-limited (`booking` bucket).
  - name: Receipts
    description: Public, signed-link digital receipts (HTML).
paths:
  # ───────────────────────────── System ─────────────────────────────
  /health:
    get:
      tags: [System]
      summary: Liveness probe
      description: Public. Always returns `ok` if the process is up; does not check the database.
      security: []
      responses:
        "200":
          description: Server is alive.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HealthStatus" }
  /ready:
    get:
      tags: [System]
      summary: Readiness probe
      description: Public. Confirms the database is reachable with a trivial query.
      security: []
      responses:
        "200":
          description: Server and database are ready.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HealthStatus" }
        "503":
          description: Database unreachable.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HealthStatus" }

  # ───────────────────────────── Auth ─────────────────────────────
  /api/v1/auth/login:
    post:
      tags: [Auth]
      summary: Log in with email/password and receive a JWT pair
      description: |
        Public. Rate limit bucket `login`: 10 requests/min per client.
        Sign in with your own business's email, password and tenant id.
      x-rate-limit: "login: 10/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LoginRequest" }
      responses:
        "200":
          description: Authenticated.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoginResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          description: Invalid credentials (`error:"invalid_credentials"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: The email signs in to more than one business — choose one and retry (`error:"tenant_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TenantChoiceResponse" }
        "403":
          description: Account deactivated (`error:"account_inactive"`), or the location asked for registered devices only and this device is not one a manager registered (`error:"device_not_registered"`, T-22.3; no session is written), or the request names `surface:"admin"` and the role holds no back-office permission (`error:"back_office_not_for_role"`), or the email and password are a sign-up whose emailed link was never spent (`error:"account_not_confirmed"`; no account and no session exist yet, and a wrong password is the `401` above, word for word).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/refresh:
    post:
      tags: [Auth]
      summary: Exchange a refresh token for a new access/refresh token pair
      description: |
        Public. Rate limit bucket `refresh`: 30 requests/min per client. The token presented is spent: the new
        pair belongs to the same session (V82). Presenting the old token again within 60 seconds of its spend (an answer
        that never arrived, or a second tab racing the first) answers a fresh pair and revokes the one issued before;
        later, it answers 401 and ends the whole session — the pair issued for it included — since a spent token in a
        second pair of hands is a copy. A browser's session (a `device` with `platform: "web"`, or none) and any session that
        sent no `device` at sign-in lasts at most 90 days from sign-in however often it is refreshed; after that the answer
        is `error:"session_expired"` and the person signs in again. A till's (a registered Android, iOS or desktop device
        not signed out from Devices) and a paired screen's are held by the registration instead (D-92). A 429 or a 5xx says nothing about the token: keep it
        and try again.
      x-rate-limit: "refresh: 30/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RefreshRequest" }
      responses:
        "200":
          description: New token pair issued.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoginResponse" }
        "401":
          description: |
            Refresh token invalid, expired, or already consumed (`error:"invalid_refresh_token"`); a session past its
            longest life (`error:"session_expired"`); for a paired screen a manager signed out, `error:"device_signed_out"`
            with the sentence the screen shows; a token left unused past its window (30 days for a person, 90 for a paired
            screen; each refresh starts it again), `error:"session_unused"` with the sentence the sign-in shows.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: The account has been switched off since sign-in (`error:"account_inactive"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/pair:
    post:
      tags: [Auth]
      summary: Pair a kitchen screen or kiosk with its one-time code
      description: |
        Public. Rate limit bucket `pairing`: 10 requests/min per client. A manager adds a screen with
        `POST /devices` and is shown a code; the screen sends it here and receives its own sign-in, as
        `role: DEVICE`, set to the surface the manager chose (`pinnedSurface`). The pair refreshes through
        `POST /auth/refresh` like any device's, and a manager ends it with `POST /devices/{id}/sign-out` — from
        then on the screen's access token is refused at once and its refresh answers `device_signed_out`.

        A code works once, for ten minutes, and only for the latest code made for that screen. Letters are not
        case-sensitive, and spaces and the dash are ignored. A DEVICE sign-in holds only what the permission
        matrix gives a screen (the kitchen display's tickets and bumps, the kiosk's guest orders); its
        `GET /sync/pull` carries no staff, customers or reservations.
      x-rate-limit: "pairing: 10/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DevicePairRequest" }
      responses:
        "200":
          description: The screen's own token pair, with the device as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoginResponse" }
        "400":
          description: The code matches no screen waiting to be paired (`error:"pairing_code_unknown"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: The screen was signed out after the code was made (`error:"device_signed_out"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "410":
          description: The code has been used (`error:"pairing_code_used"`) or has run out (`error:"pairing_code_expired"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/pair/start:
    post:
      tags: [Auth]
      summary: An unpaired screen starts a pairing (scan to pair)
      description: |
        Public. Rate limit bucket `pairStart`: 20 requests/min per client. A kitchen screen or kiosk with no business yet
        asks for a pairing and shows `claimToken` as a QR (a link to the back office's confirm page) with `code` under it
        for a manager with no camera. `secret` is the screen's alone and is sent only to `POST /auth/pair/poll`. The answer
        names no business, location or person: nothing does yet. A pairing waits ten minutes for a phone.
      x-rate-limit: "pairStart: 20/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DevicePairStartRequest" }
      responses:
        "201":
          description: The three halves of a new pairing.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DevicePairStartDto" }
        "400":
          description: A surface that is not `kds` or `kiosk` (`error:"unknown_surface"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/pair/poll:
    post:
      tags: [Auth]
      summary: An unpaired screen asks whether a manager has added it
      description: |
        Public. Rate limit buckets `pairPoll`: 240 requests/min per client, and `pairToken`: 90 requests/min per pairing token.
        The per-pairing budget is spent only once `secret` has found a pairing: a secret that names none spends nothing but the
        per-client budget. Only `secret` finds a pairing: the QR's claim token, the short code or nothing find none. Poll every
        couple of seconds. Once a manager's phone has claimed the pairing, the answer is `202` `state:"claimed"` with the
        business and location the screen would join — never a credential: the screen asks "Join <business> — <location>?".
        Only a poll with `confirm: true` (Join) is answered with the screen's own DEVICE sign-in, the same body as
        `POST /auth/pair` and the same paired state, **once**: a second confirm is `410`. A poll with `reject: true` (Not mine)
        removes the screen the claim made from that business (audited `device.pair_rejected`) and answers `202`
        `state:"waiting"`; another phone may then claim it. Not mine removes nothing once the screen has joined, once a manager
        made it a new code on the Devices page (`410` `pairing_replaced`) or once the claim ran out (`410` `pairing_expired`).
      x-rate-limit: "pairPoll: 240/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DevicePairPollRequest" }
      responses:
        "200":
          description: The screen's own token pair, with the device as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoginResponse" }
        "202":
          description: Nobody has claimed this screen yet (`state:"waiting"`), or a phone has and the screen has not said Join (`state:"claimed"`, with `businessName` and `locationName`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DevicePairWaitingDto" }
        "400":
          description: Both `confirm` and `reject` (`error:"confirm_or_reject"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: No pairing holds that secret (`error:"pairing_unknown"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "410":
          description: The pairing ran out (`error:"pairing_expired"`), has already given its sign-in (`error:"pairing_used"`), or a manager made the screen a new code on the Devices page (`error:"pairing_replaced"`); start another.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/password/forgot:
    post:
      tags: [Auth]
      summary: Email a link to set a new password
      description: |
        Public. Rate limit bucket `passwordReset`: 10 requests/min per client. Emails a link to every account the
        address signs in to (one per business), unless that account has had three in the last hour. The answer is
        the same `202` and the same sentence whether or not the address has an account, and the email goes after
        the answer, so the response never tells anyone who is a customer. A newer link retires the older ones; a
        link works once, for thirty minutes, and opens `/reset-password`. A kitchen screen's or kiosk's own account
        is never sent one.
      x-rate-limit: "passwordReset: 10/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ForgotPasswordRequest" }
      responses:
        "202":
          description: Accepted. The same answer for any address.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PasswordResetAnswer" }
        "400":
          description: No address was given (`error:"missing_email"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/password/check:
    post:
      tags: [Auth]
      summary: Whether a reset link still works
      description: |
        Public. Rate limit bucket `passwordReset`. What the reset page asks before anything is typed. Changes nothing.
      x-rate-limit: "passwordReset: 10/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ResetLinkCheck" }
      responses:
        "200":
          description: The link works.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PasswordResetAnswer" }
        "410":
          description: The link ran out, was used, or was replaced by a newer one (`error:"reset_link_dead"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/password/reset:
    post:
      tags: [Auth]
      summary: Set a new password with a reset link
      description: |
        Public. Rate limit bucket `passwordReset`. Sets the password on the account the link was emailed for and
        spends the link. Every refresh token of the account is revoked, so every device signs in again. The new
        password must be at least ten characters and not the email address. A sign-in lock on the address (ten
        wrong passwords in fifteen minutes) is lifted, so the new password signs in at once.
      x-rate-limit: "passwordReset: 10/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ResetPasswordRequest" }
      responses:
        "200":
          description: The password is set and every session ended.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PasswordResetAnswer" }
        "400":
          description: The password is refused, with why (`error:"weak_password"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "410":
          description: The link ran out, was used, or was replaced by a newer one (`error:"reset_link_dead"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/pin:
    post:
      tags: [Auth]
      summary: Seat a person at a till's PIN pad
      description: |
        For a till that shows a PIN pad (a device a person signed in), called with the DEVICE's token after the till checked
        the PIN itself. The server checks the PIN again, behind the seat's own lockout (per person and per device), and answers a twelve-hour access
        token whose subject, role and permissions are the PERSON's, still held to the device's session: signing the device
        out, switching the person off or changing their role ends it at once. A wrong PIN, an unknown person and a person
        of a higher rank than the device's account are one answer (`error:"pin_seat_refused"`), and a PIN that is not four to
        eight digits is refused unchecked. A screen paired as itself is refused, and so is a seat. Rate limit bucket `pinSeat`:
        20 requests/min per signed-in device (`error:"rate_limited"`), beside the seat's own lockout (`error:"pin_seat_locked"`). The account that signed the device in is never seated at its own pad.
      x-rate-limit: "pinSeat: 20/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [staffId, pin]
              properties:
                staffId: { type: string }
                pin: { type: string, description: Four to eight digits. Never logged. }
      responses:
        "200":
          description: The person is seated; send their calls under `accessToken`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  accessToken: { type: string }
                  expiresInSeconds: { type: integer, format: int64 }
                  staffId: { type: string }
                  name: { type: string }
                  role: { type: string }
        "403":
          description: The PIN, the person or the rank was refused (`error:"pin_seat_refused"`), or the caller is a screen paired as itself.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Too many wrong PINs for this person or at this till (`error:"pin_seat_locked"`), or the `pinSeat` bucket; the till lets the person in to work offline only.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/auth/me:
    get:
      tags: [Auth]
      summary: Get the current authenticated user's profile
      responses:
        "200":
          description: Current user.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UserDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: User not found (`error:"user_not_found"`) — e.g. deleted after token issue.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/auth/2fa:
    get:
      tags: [Auth]
      summary: The caller's own two-factor standing
      description: |
        T-37.4. For the person signed in: whether the second factor applies to their role (it holds pay rates, refunds or
        exports), whether the business requires it, whether they have an authenticator, whether THIS session has proved it,
        and how many recovery codes are left. Never a secret or a code.
      responses:
        "200":
          description: The standing.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TwoFactorStatus" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/auth/2fa/enrol:
    post:
      tags: [Auth]
      summary: Start setting up an authenticator
      description: |
        T-37.4. Rate limit bucket `secondFactor`. Makes a new secret (kept sealed under the server's encryption key) and answers it
        once, with the `otpauth://` link an authenticator app reads. Only for a role the second factor applies to (otherwise
        `error:"second_factor_not_for_role"`); asking again before confirming replaces the secret; once confirmed it is
        `409 already_enrolled` — the owner resets a lost one. The account's password is asked again (`403 password_wrong`),
        so a session token alone cannot put a phone on the account; the request spends the sign-in's `login` bucket too.
      x-rate-limit: "secondFactor: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TwoFactorEnrolRequest" }
      responses:
        "200":
          description: The secret and its link, shown now and never again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TwoFactorEnrolment" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Not the account's password (`error:"password_wrong"`), or a role the factor is not for (`error:"second_factor_not_for_role"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Already set up (`error:"already_enrolled"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/2fa/confirm:
    post:
      tags: [Auth]
      summary: Confirm the authenticator with its first code
      description: |
        T-37.4. Rate limit bucket `secondFactor`. The first code from the new authenticator confirms it, marks THIS session as
        having proved the second factor, and answers ten recovery codes — shown once, each works once, stored only as a hash.
        A code is counted before it is judged; five wrong ones in fifteen minutes lock the person (`429 second_factor_locked`).
        The account's password is asked again (`403 password_wrong`; the `login` bucket too). Before anything is confirmed the
        person is emailed that an authenticator was set up, with a one-time "this wasn't me" link (`/second-factor/not-me`,
        seven days — a staff invite's life — once: it removes the authenticator, ends every session and retires the password,
        mailing a reset link); while that email cannot be sent nothing is confirmed (`503 second_factor_notice_unsent`), and a
        confirmation that loses a race with a fresh set-up (`409 nothing_to_confirm`) leaves no link standing. The owner is told too.
        Audited `security.second_factor_enrolled`.
      x-rate-limit: "secondFactor: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TwoFactorConfirmRequest" }
      responses:
        "200":
          description: Confirmed; the recovery codes, once.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TwoFactorRecoveryCodes" }
        "400":
          description: No code was sent (`error:"code_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The code is not right (`error:"invalid_code"`), or the password is not (`error:"password_wrong"`); never a 401, which would send a till to refresh its token.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Nothing to confirm (`error:"nothing_to_confirm"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "503":
          description: The person could not be emailed that an authenticator was set up, so nothing was confirmed (`error:"second_factor_notice_unsent"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/auth/2fa/verify:
    post:
      tags: [Auth]
      summary: Prove the second factor for this session
      description: |
        T-37.4. Rate limit bucket `secondFactor`. Send exactly one of `code` (the authenticator's) and `recoveryCode`. On success
        this session holds its second factor from now, through every rotation of its refresh token; another sign-in starts
        without it. A session a device registered at its sign-in (any till, the web `/app` in a browser included, and the back
        office inside it) holds it for five minutes only, because a till is shared (T-41.58); only a session with no device
        registered (an email sign-in with no device, a script) keeps it until it ends. `GET /auth/2fa` then answers
        `proven: false, provenOnce: true`: the sign-in is not owed again, and the back office asks for the code over the page
        when a door refuses. A code works once (its step only moves forward); a recovery code works once, and its person
        is emailed when one is spent. Wrong attempts are counted
        before they are judged and lock the person after five in fifteen minutes (`429 second_factor_locked`, with `Retry-After`).
        Until a session has proved it, a business that requires the factor answers `403 second_factor_required` at pay-rate,
        refund and export routes, where an API app or webhook endpoint is given more reach (a marketplace install included), where
        an accounting package is connected or a paused connection switched back on, and where a payment account is saved, with
        the remedy in the sentence.
      x-rate-limit: "secondFactor: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TwoFactorCode" }
      responses:
        "200":
          description: Proved for this session.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TwoFactorProof" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The code is wrong or already used (`error:"invalid_code"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: No authenticator yet (`error:"enrol_first"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/2fa/recovery-codes:
    post:
      tags: [Auth]
      summary: Make a new set of recovery codes
      description: |
        T-41.58. Rate limit bucket `secondFactor`, and `login` because the password is asked again. The account's password and
        the authenticator's current code (a recovery code does not make more) answer ten new recovery codes, shown once; the old
        ones stop working. The person is emailed. Audited `security.second_factor_codes_renewed`.
      x-rate-limit: "secondFactor: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TwoFactorRenewRequest" }
      responses:
        "200":
          description: The new recovery codes, once.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TwoFactorRecoveryCodes" }
        "400":
          description: No code was sent (`error:"code_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The code is not right (`error:"invalid_code"`), the password is not (`error:"password_wrong"`), or the role has no second factor (`error:"second_factor_not_for_role"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: No authenticator yet (`error:"enrol_first"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/2fa/till/forget:
    post:
      tags: [Auth]
      summary: A till drops the second-factor code typed at it
      description: |
        T-37.15. A code typed at a till serves the person who typed it only while they are at it. The till calls this when its
        PIN pad switches to someone else, when the person signs out and after a minute with no touch; it removes every proof held
        on THIS signed-in device's session, whoever typed it, and answers `204` whether or not any was held. Any signed-in person
        (a screen is refused). Not rate limited as a code attempt: it judges no code and spends no try. Each person dropped is
        audited `security.second_factor_till_forgotten` with the `reason` (`switch`, `sign_out`, `idle`; anything else `other`)
        and the `session`. The server also drops the other people's proofs on a session when a second person's code, or a
        request naming a second person, arrives (`person_changed`), where it can see the person change without being told.
        On a registered till it also ends the till account's own code typed in the back office inside it (lapsed: it proves
        nothing from now, while `provenOnce` stays true). With `staffId` the call drops that person's PIN-pad code (a PIN switch
        names who was at the till, so a call that arrives after the next person typed theirs leaves it; the account's own id
        lapses nobody else's PIN-pad code); the till account's own code is lapsed on every call whoever is named; without it, every code of the session. The server never relies on this call — a
        till code opens one act and is spent by it, and so is the account's own code on a registered till — and audits only what the call itself dropped, so two forgets at once write one row per code.
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TillCodeForgetRequest" }
      responses:
        "204":
          description: Dropped (or nothing was held).
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The caller is a screen.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/auth/2fa/till:
    post:
      tags: [Auth]
      summary: The second factor of the person at a till
      description: |
        T-37.11. Rate limit bucket `secondFactor`, spent by the till's session. A till is signed in by the business's account
        and its PIN pad switches who is using it; `staffId` is that person, and the code is judged against THEM — their
        authenticator or recovery codes, their lock (five wrong in fifteen minutes, `429 second_factor_locked`, shared with
        their own sign-ins). Only a session whose own account may refund calls it: any other is refused
        `403 second_factor_not_for_role` before a try is spent. On success that person holds a proof on THIS till's session for
        five minutes at most; the session itself is not marked. The proof is SINGLE-USE (T-37.15): a refund, return or lay-by
        cancellation sent with header `X-Ruva-Acting-Staff: <staffId>` spends it in the transaction that admits it, so one code
        opens one act (two sent at once: one admitted) and a second act asks again whatever the till does or fails to say; an
        act refused after it was admitted has spent it too. A return lookup is admitted by it and leaves it for the act. Each of
        those four is held to that person's proof — never to the account's — and refused
        `403 second_factor_required` with the till's own sentence when the person has not proved it, has no authenticator, or
        cannot do the act. The proof opens those four and nothing else: any other route naming them (an export, pay rates, a
        refund check, a room charge's reverse, release or postings) stays on the session's rule.
        With the header, the refund is recorded as that person's; a body `staffId` (or `byStaffId`) naming anyone else is
        `400 acting_staff_mismatch`. Never a screen's. Audited `security.second_factor_till_proof` (with the till's account,
        `grantedBy`, and `session`, the one till among every till the account signs in); a wrong or locked code is audited
        `security.second_factor_till_refused` under the till's account. A second person's code on the same session ends the
        first person's (`security.second_factor_till_forgotten`, reason `person_changed`): one person at a till at a time.
        A till whose own account cannot refund is told what helps (sign it in with a manager's account, or refund from the
        back office) rather than to ask a manager, whose code could change nothing there.
      x-rate-limit: "secondFactor: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TillSecondFactorRequest" }
      responses:
        "200":
          description: Proved for this person on this till until `expiresAt`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TillSecondFactorProof" }
        "400":
          description: No code was sent (`error:"code_required"`), or no person (`error:"staff_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The code is wrong or already used (`error:"invalid_code"`), the person's role is not one two-factor applies to, or the till's own account may not refund (`error:"second_factor_not_for_role"`), or the caller is a screen.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: No one with that id works here (`error:"person_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: The person has no authenticator yet; they set one up in the back office (`error:"enrol_first"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/settings/security:
    get:
      tags: [Settings]
      summary: Whether two-factor sign-in is required, and who it applies to
      description: |
        T-37.4. The owner's (the account holder's) page: whether the business requires a second factor of the roles that hold
        pay rates, refunds or exports, and each such person with whether they have an authenticator. Needs the licence permission.
      responses:
        "200":
          description: The switch and the people.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TwoFactorOverview" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/settings/security/second-factor:
    put:
      tags: [Settings]
      summary: Require, or stop requiring, two-factor sign-in
      description: |
        T-37.4. The owner's switch, default off. Turning it on needs the owner's own authenticator first, so the owner is not the
        one locked out (`409 owner_not_enrolled`); turning it off needs the owner's current `code` or one `recoveryCode`, so a stolen
        password cannot lift the protection. Rate limit bucket `secondFactor`. Audited (`security.second_factor_required` /
        `security.second_factor_not_required`). Takes effect on each session's next gated request. Every owner of the business is
        emailed once for each actual change (switching on what is on tells nobody), in fixed words that name nobody.
      x-rate-limit: "secondFactor: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TwoFactorSetting" }
      responses:
        "200":
          description: The switch and the people, after the change.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TwoFactorOverview" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: The owner has no authenticator yet (`error:"owner_not_enrolled"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/settings/security/second-factor/people/{userId}/reset:
    post:
      tags: [Settings]
      summary: Reset a person's authenticator (a lost phone)
      description: |
        T-37.4. The owner's, with the owner's own current `code` or `recoveryCode`. Removes the person's authenticator, recovery
        codes and lock, and every session of theirs loses its proof, so they set up a new one before pay rates, refunds and exports
        open to them again. Rate limit bucket `secondFactor`. Audited (`security.second_factor_reset`, naming who and the role,
        never a secret).
      x-rate-limit: "secondFactor: 10/min"
      parameters:
        - name: userId
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TwoFactorCode" }
      responses:
        "204": { description: Reset. }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: No such person in this business (`error:"person_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/auth/logout:
    post:
      tags: [Auth]
      summary: Sign this device out
      description: |
        Revokes the refresh tokens of the session the access token belongs to (its `sid` claim, V82), so this
        device can no longer refresh, and the access token it carries answers 401 from then on (every request is checked against its session);
        the user's other devices stay signed in. A token issued before V82
        carries no `sid`; for one of those every refresh token the user holds is revoked, as before.
      responses:
        "204":
          description: Signed out — this session's refresh tokens are revoked.
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/auth/sessions:
    get:
      tags: [Auth]
      summary: The current user's signed-in devices
      description: |
        One entry per session (V82) that still holds a live refresh token, newest first. `current` marks the
        session the calling token belongs to. Any authenticated user; only ever the caller's own sessions.
      responses:
        "200":
          description: Signed-in devices.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/SessionDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/auth/sessions/{id}:
    delete:
      tags: [Auth]
      summary: Sign one of your devices out remotely
      description: |
        Revokes every refresh token of the session, so that device cannot refresh again and has to be signed in
        afresh. An access token it already holds is refused at once (401), not when it expires: a token is held to its session on every request.
        Only the caller's own sessions can be revoked.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: That device is signed out.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: No live session of the caller's has that id (`error:"session_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/auth/password:
    post:
      tags: [Auth]
      summary: Change your own password while signed in
      description: |
        D-202. Only the caller's own account, and only a person's (a screen signed in as itself is refused). The current
        password is checked first, and a wrong one changes nothing. The new password follows the same rule as sign-up and a
        reset link: at least 10 characters, at most 128, not only spaces or one character repeated, and not the email address.
        The password is changed only while it is still the one just checked. Every OTHER session of the caller is signed out
        at once (its access token is refused at its next request and its refresh token stops working), the session the change
        was made from stays signed in, and unspent reset links stop working. The caller is then emailed that their password
        was changed; `noticeSent` says whether the email service took it.
      x-rate-limit: "ownPassword: 5/hour"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OwnPasswordRequest" }
      responses:
        "200":
          description: Changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OwnPasswordChanged" }
        "400":
          description: The new password breaks the rule (`error:"weak_password"`, the rule's own sentence in `message`), or is the current one typed again (`error:"same_password"`; nothing changes, no session ends, nobody is emailed).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The current password is wrong (`error:"wrong_password"`), or the caller is a screen (`error:"person_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: The password was changed elsewhere meanwhile (`error:"password_changed_meanwhile"`); nothing was changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: The `ownPassword` bucket for this person, or the sign-in rate limit (see `Retry-After`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/auth/name:
    post:
      tags: [Auth]
      summary: Change your own name while signed in
      description: |
        D-212. The name Ruva calls the caller: the greeting when they sign in and the name beside their email in the menu.
        Only the caller's own account, and only a person's (a screen signed in as itself is refused). The name is kept trimmed;
        a blank one clears it. When the caller is on the business's People list, their name there changes with it (and a
        rename on People changes this name). The business's contact details are not changed. The answer is the account as
        it now stands, the same shape `/auth/me` answers.
      x-rate-limit: "ownName: 20/hour"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OwnNameRequest" }
      responses:
        "200":
          description: Changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UserDto" }
        "400":
          description: The name is longer than 120 characters (`error:"name_too_long"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The caller is a screen signed in as itself (`error:"person_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: The caller's account no longer exists (`error:"user_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: The `ownName` bucket for this person, or the sign-in rate limit (see `Retry-After`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Devices (device_registrations, T-2.4) ─────────────────────────────
  /api/v1/devices:
    get:
      tags: [Devices]
      summary: The business's signed-in devices
      description: |
        Every device registered to this business, most recently seen first. A device is registered when an owner
        or manager signs it in with a `device` on `POST /auth/login`. `current` marks the calling device. Managers only.
      responses:
        "200":
          description: Devices.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Devices]
      summary: Add a kitchen screen or kiosk that pairs itself
      description: |
        Adds a screen set to `kds` or `kiosk` at a location (and, for a kitchen screen, optionally a prep station),
        with its own `DEVICE` account, and answers its first one-time code. The code is in this answer only: the
        server keeps its hash. The screen spends it with `POST /auth/pair` within ten minutes. Managers only.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeviceCreateRequest" }
      responses:
        "201":
          description: The screen, and the code to type on it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DevicePairingCodeDto" }
        "400":
          description: No name, a surface that is not `kds` or `kiosk`, or an unknown location or station.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: |
            A kitchen screen past what the business's plan includes (`error:"plan_limit"`); the message names the plan's
            number, the screens in use and the way to more. Nothing is written.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/devices/pair-claims:
    post:
      tags: [Devices]
      summary: Add the screen a QR belongs to (scan to pair)
      description: |
        Rate limit buckets `pairClaim`: 30 requests/min per client, `pairClaimBusiness`: 20 requests/min per business, and
        `pairToken`: 90 requests/min per pairing token (spent once the pairing is found). A manager's
        phone sends the QR's `claimToken` (or the `code` typed from under it) with a name and a location of the manager's OWN
        business; a blank name is the screen's own kind ("Kitchen screen", "Ready to collect screen", "Kiosk"). The screen is added exactly as `POST /devices` adds one (the kitchen licence and the plan's kitchen-screen limit
        apply) and bound to that business and location only. The screen is NOT signed in by the claim: it is shown the business
        and location and signs in only when the person at it taps Join, or removes the screen with Not mine. When the screen
        started its pairing from another network (IPv4 /24, IPv6 /56) than this claim, the claim is refused 409
        `screen_on_another_network` before anything is written, with the question the phone asks ("This screen is not on the
        network you are on. Only add a screen standing in front of you. Add it anyway?"); on yes the phone sends the claim again
        with `anotherNetworkConfirmed: true`, and the answer's `sameNetwork` is false. A refused claim does not spend the token.
        Managers only.
      x-rate-limit: "pairClaim: 30/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DevicePairClaimRequest" }
      responses:
        "201":
          description: The screen as it now stands, and the surface it opens as.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DevicePairClaimedDto" }
        "400":
          description: An unknown location or station, or neither/both of `claimToken` and `code`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: No pairing holds that token or code (`error:"pairing_unknown"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: A kitchen screen past what the business's plan includes (`error:"plan_limit"`), or a screen that started from another network than this claim and `anotherNetworkConfirmed` is not true (`error:"screen_on_another_network"`). Nothing is written and the token is kept.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "410":
          description: The pairing ran out (`error:"pairing_expired"`) or another claim got it first (`error:"pairing_used"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/devices/kitchen-screens:
    get:
      tags: [Devices]
      summary: The plan's kitchen-screen limit and how many are in use
      description: |
        What the business's plan lets it have in use (`limit`, null for no limit: no plan, a plan with none, or a
        business holding a till product) and how many kitchen screens are in use now (`inUse`: set to `kds` and not
        signed out). It is the same count `POST /devices` refuses on with `409 plan_limit`. Managers only.
      responses:
        "200":
          description: The limit and the count.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/KitchenScreenAllowance" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/devices/{id}/pairing-code:
    post:
      tags: [Devices]
      summary: A fresh pairing code for a screen
      description: |
        For a screen added with `POST /devices` — its code ran out, or the screen is being replaced. Older unused
        codes for it stop working; pairing with the new one ends the screen's previous sign-in. Refused
        (`error:"not_a_paired_screen"`) for a device a person signed in with their email and password. Managers only.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The screen, and the code to type on it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DevicePairingCodeDto" }
        "400":
          description: Not a screen that pairs with a code.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: A signed-out kitchen screen paired again past what the plan includes (`error:"plan_limit"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/lan/secret:
    get:
      tags: [Devices]
      summary: The venue's LAN key, for till-to-till journal gossip
      description: |
        A per-business key every till of the business receives identically, used to sign journal gossip between tills
        on the venue's own network (HMAC-SHA256). Derived on the server; nothing is stored. Any person's role;
        refused to a `DEVICE`-role display, because the key exists to tell a till from a screen.
      responses:
        "200":
          description: This business's key.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LanHubSecret" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The caller is a display signed in as itself (`error:"till_only"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/lan/hub-name:
    put:
      tags: [Devices]
      summary: A hub till asks for its https name and certificate
      description: |
        T-37.18. A hub till sends the private LAN address it serves on and, once, a PKCS#10 request made with a key that
        never leaves it. The name is the server's and is bound to the caller's own registration (never an id in the body).
        Needs the capability to sell at a till (`TILL_SELL`); a `DEVICE`-role display is refused `till_only`. The answer
        carries the name, its status and, once issued, the certificate chain (never a private key). Refusals:
        `address_not_private` (400, not 10.x, 172.16-31.x or 192.168.x), `csr_refused` (400, not a certificate request,
        not signed by its own key, or not naming exactly this till's hub name), `no_device` (409, the session has no
        registration), `too_many_hub_names` (409, five tills of a business already hold one) and
        `hub_names_not_set_up` (503, this server has no hub name domain).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/HubNameRequest" }
      responses:
        "200":
          description: The till's name and where it stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HubNameAnswer" }
        "400":
          description: "`address_not_private` or `csr_refused`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The caller is a display signed in as itself, or lacks `TILL_SELL` (`error:"till_only"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`no_device` or `too_many_hub_names`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: Hub https names are not set up on this server (`hub_names_not_set_up`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/lan/hub-names:
    get:
      tags: [Devices]
      summary: The venue's hub tills' https names, for a browser till
      description: |
        T-37.18. The hub tills of this business that hold a certificate, so a browser till can call one over https.
        Needs `TILL_SELL`; a `DEVICE`-role display is refused `till_only`.
      responses:
        "200":
          description: The business's hub names (possibly none).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HubNamesList" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The caller is a display signed in as itself, or lacks `TILL_SELL` (`error:"till_only"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/devices/this/health:
    post:
      tags: [Devices]
      summary: The calling device reports its outbox
      description: |
        Writes the server refused and writes still waiting, as the device counts them (T-14.1), sent with its
        once-a-minute check-in. The device is the token's own session; the latest word replaces the last.
        Any authenticated user. Negative counts are refused.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeviceSyncHealth" }
      responses:
        "204": { description: Recorded. }
        "400": { description: "bad_sync_health — a negative count." }
        "404": { description: "device_not_registered" }
  /api/v1/devices/this:
    get:
      tags: [Devices]
      summary: What the calling device is set to
      description: |
        The device the calling token was issued to, found by its session (`sid`), never by an id in the request.
        A device re-reads this to pick up a pin a manager set after it signed in. Any authenticated user.
        Where a location has "registered devices only" on (T-22.3), a device the venue registered with no secret yet is handed one,
        once, as `secret` — on its manager's own session, with any second factor proved, and only when the client asks with
        `keepsSecret=true` (it keeps the secret beside its id). Where every switch of the business is off, nothing is handed.
      parameters:
        - name: keepsSecret
          in: query
          required: false
          description: "`true` from a client that keeps a registration secret it is handed (T-22.3 fix 4); absent, none is handed."
          schema: { type: boolean }
      responses:
        "200":
          description: This device.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: The session registered no device (`error:"device_not_registered"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/devices/this/unpin:
    post:
      tags: [Devices]
      summary: Unpin the calling device on a manager's PIN
      description: |
        Typed at the pinned device itself. The PIN must be an active manager's of this business. Every refusal is
        the same 403 `manager_pin_required` — whether the PIN is nobody's or a non-manager's is not said — never 401,
        which a client reads as a lost session. Rate limited with sign-in per client, and counted per business (one count
        with `POST /staff/verify-manager-pin`, T-2.49): after
        10 refusals in 15 minutes at any of its devices, every unpin of the business is a 429 `unpin_locked` until the
        window moves on (`POST /devices/{id}/pin` from the back office still works).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeviceUnpinRequest" }
      responses:
        "200":
          description: Unpinned; the device is shared again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The PIN is not an active manager's here (`error:"manager_pin_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Too many refusals at this business's devices (`error:"unpin_locked"`), or the sign-in rate limit.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: The session registered no device (`error:"device_not_registered"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/devices/{id}:
    post:
      tags: [Devices]
      summary: Rename a device, or set its location or prep station
      description: |
        A null field is left as it is; an empty string clears `locationId` or `stationId`. The station must be an
        active prep station of this business, and its printer is the device's prep printer. Managers only.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeviceUpdateRequest" }
      responses:
        "200":
          description: The device as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    delete:
      tags: [Devices]
      summary: Remove a device (unpair a screen)
      description: |
        Ends the session the device holds — its next refresh is refused and an access token it holds is refused at once
        (401) — and removes it from the list. A screen paired as itself (`role: DEVICE`) loses its own account, its
        pairing codes and its open sync sockets with it, and frees its kitchen-screen place; it pairs again only as a new
        screen. The device the caller is using is refused (409 `this_device`): sign it out from the menu. Managers only.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Removed.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The device the caller is using (`error:"this_device"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/devices/{id}/pin:
    post:
      tags: [Devices]
      summary: Pin a device to one surface, or unpin it
      description: |
        `surface` is one of `pos`, `admin`, `kds`, `kiosk`, `customer-display`, or null to make the device shared
        again. The device picks it up on its next sign-in or `GET /devices/this`. Managers only.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DevicePinRequest" }
      responses:
        "200":
          description: The device as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "400":
          description: Not a surface a device can be set to (`error:"unknown_surface"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/devices/{id}/pin-lock/clear:
    post:
      tags: [Devices]
      summary: Let a device's PIN pad take PINs again
      description: |
        After too many wrong PINs a device's PIN pad stops taking PINs for a while. This stamps the device's
        `pinLockClearedAt`; the device reads it within a minute and forgets its count of wrong PINs, once per stamp.
        Managers only.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The device as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/devices/{id}/sign-out:
    post:
      tags: [Devices]
      summary: Sign a device out remotely
      description: |
        Revokes the session the device holds, so its next refresh is refused and it returns to its sign-in screen.
        An access token it already holds is refused at once (401), a person's and a paired screen's (`role: DEVICE`) alike,
        along with any pairing code made for it before the sign-out. The row stays, with `signedOutAt`, until the
        device is signed in again. Managers only; the other devices stay signed in.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The device as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/devices/{id}/registered:
    post:
      tags: [Devices]
      summary: Register or unregister a device
      description: |
        Sets whether the venue has registered the device (`registered`). It changes only where a location has "registered devices
        only" on: with every switch off the answer is 409 `registered_devices_off`, and a screen paired from Devices (always
        registered) is 409 `paired_device`. Either way the device's registration secret is cleared and the row stays; a manager's
        sign-in on it hands it a new one. Unregistering signs out the people who are not managers signed in on the device or at it,
        so an access token they hold is refused at once (401) and the next sign-in on it is 403 `device_not_registered`; a
        manager's own session is left. Both changes are audited as `device.registered` and `device.unregistered` with who made
        them; a repeat changes and records nothing. Needs the Devices page's permission (EDIT_SETTINGS); never a screen.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeviceRegisteredRequest" }
      responses:
        "200":
          description: The device as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/devices/sign-out-unregistered:
    post:
      tags: [Devices]
      summary: Sign out a location's unregistered devices
      description: |
        T-22.3: turning "registered devices only" on ends no running session, so this ends, at one location, every live session of
        a person who is not a manager that holds no proven registered device (round 3, P2-3): one on a device the venue has not
        registered (a device with no location yet counts at every location; signed out as `POST /devices/{id}/sign-out` does), and
        one on no device at all — a sign-in that named none, a registered device's id without its secret, or one signed in AT a
        device it did not prove — counted at every location. A session on a registered device, or signed in AT one it proved by its
        secret, is kept. Never the session the manager is using, a paired screen, or a manager's own session. Writes one audit row,
        `devices.unregistered_signed_out`, naming the location, the count and the devices' ids (never a secret). Managers only
        (EDIT_SETTINGS).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                locationId: { type: string }
              required: [locationId]
      responses:
        "200":
          description: How many sessions were ended (each unregistered device's, and each on no device).
          content:
            application/json:
              schema:
                type: object
                properties:
                  signedOut: { type: integer }
                required: [signedOut]
        "400":
          description: No location named (`error:"location_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: The id names no live location of the business — removed, another business's or unknown (`error:"location_not_found"`). Nothing is ended.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: The location's "registered devices only" switch is off (`error:"registered_devices_off"`). Nothing is ended and no audit row is written.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Licensing (V40/V72) ─────────────────────────────
  /api/v1/signup:
    post:
      tags: [Auth]
      summary: A venue signs itself up for QR Ordering
      description: |
        Public. Rate limit bucket `signUp`: 5 requests/min per client. Proves the email before it makes anything
        (T-2.41): the request is stored and the address is sent ONE confirmation link in fixed words (nothing typed
        here is in the email). The business (QR Ordering on its trial), one location, its owner, and its subscription
        on the plan (`starter` or `pro`) and the way of paying chosen (`PAYFAST`: a card debited each month) are made
        only when that link is opened and confirmed (opening it shows what it will make and makes nothing; confirming it
        records the terms with the confirmer's own address). The owner chooses the password here (`password`, typed again as
        `passwordConfirm`; hotfix 2026-11-24): at least 10 characters, not the email (`400 weak_password`), the two the same
        (`400 password_mismatch`); only its hash is kept until the link is spent, the owner signs in with it, and no
        set-your-password email is sent. A request with no `password` (an app built before it) is confirmed into an owner who
        is emailed a link to set one, as before. An address already in use never has its password changed. The answer
        is the same `202` whatever the address: new, already waiting, or already signing in to a business. It carries
        no id and no link. A plan or way of paying not offered (`plan_not_offered`, `rail_not_offered`,
        `rail_required`) or a bad name or email is a `400`. At most a few confirmation emails go to one address an
        hour and a day (`429 signup_address_limit`) and a few sign-ups a day start from one client network (an IPv4 /24,
        an IPv6 /56) or one block (an IPv4 /16, an IPv6 /48; `429 signup_client_limit`). Past an hourly ceiling of
        confirmation emails across the whole server, sign-up is `503 signup_busy` with `Retry-After` and nothing is
        mailed; it reopens within the hour. A newer request for
        an address retires its older link only once that link is five minutes old. The owner accepts Ruva's
        terms, privacy notice and operator agreement at the version published now (`acceptedTermsVersion`, T-3.6):
        without it `422 terms_not_accepted`, at another version `422 terms_version_changed`, and while no version is
        published sign-up is closed, `503 terms_not_published`. The acceptance is recorded with the business, when the
        link is confirmed. One free trial per business (T-3.11): an email at a throwaway-mail service is `400 disposable_email`;
        `mobileNumber` with the `mobileCode` that `POST /api/v1/signup/mobile-code` sent to it proves the owner's mobile
        (`400 mobile_invalid` for a number that is not one, `422 mobile_code_wrong` for a code that is not its newest, unused
        code — five wrong tries burn it). A number an earlier trial proved makes the business with no trial, and so does a
        sign-up that proves none while codes can be sent. Where Ruva could not send that number's code in the last 30 minutes
        (`503 mobile_code_later`, T-41.88), the number with no code starts the free trial with its mobile to confirm from the
        back office within 3 days — once per email, capped per client network and block — and the trial ends if it never is.
        Only a keyed hash of the number is kept. The owner's own name is required (`ownerName`, T-41.48):
        without it `400 owner_name_required`, past 120 characters `400 owner_name_too_long`; it becomes the business's
        contact when the link is confirmed. The website's `/sign-up/` form and the one app's "Create your business
        account" both post here, from what `GET /api/v1/signup/options` offers.

        An optional agent code (T-34.2, `agentCode`, from an agent's share link or typed) attributes the new business to the Ruva
        agent who brought it, once, when the link is confirmed. A code that is unknown, suspended or not shaped like a code is
        `422 agent_code_not_accepted`, one answer for every cause that names no agent, with nothing stored or mailed: send the same
        request without `agentCode` and the business is made. An agent suspended after the request but before the link is
        confirmed is not attributed, and neither is a business whose confirmed email or proved mobile is the agent's own; in both
        cases the business is still made, and the request's answer never depends on whose email or mobile it carries.
      x-rate-limit: "signUp: 5/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [businessName, ownerEmail, ownerName, plan, rail]
              properties:
                businessName: { type: string }
                ownerEmail: { type: string }
                ownerName: { type: string, description: "The owner's own name, at most 120 characters (T-41.48)." }
                locationName: { type: string, nullable: true }
                plan: { type: string, enum: [starter, pro] }
                rail: { type: string, enum: [PAYFAST, YOCO] }
                term: { type: string, enum: [MONTHLY, YEARLY], nullable: true, description: "How often the plan is paid (T-41.30); monthly when absent. `400 term_not_offered` for any other value." }
                acceptedTermsVersion: { type: string, description: "The version of the legal documents the owner accepted." }
                mobileNumber: { type: string, nullable: true, description: "The owner's mobile, as typed (T-3.11)." }
                mobileCode: { type: string, nullable: true, description: "The six-digit code sent to it by /api/v1/signup/mobile-code." }
                password: { type: string, nullable: true, description: "The owner's password (hotfix 2026-11-24). Only its hash is kept." }
                passwordConfirm: { type: string, nullable: true, description: "The same password typed again; `400 password_mismatch` when it differs." }
                products: { type: array, nullable: true, items: { type: string }, description: "The `RuvaProduct` codes the business is buying (T-23.2); absent means QR Ordering, exactly as before. Only what GET /api/v1/signup/options lists under `products` is accepted: any other (a product not on sale, an unknown code, an empty list) is `400 product_not_offered`, and a set holding a till is one subscription at its `bundles` or product price." }
                agentCode: { type: string, nullable: true, description: "A Ruva agent's code, for example RUVA-NAME-AB (T-34.2). Optional." }
                agentVia: { type: string, nullable: true, enum: [link, code], description: "link when the agent's share link filled the field and it was left alone, otherwise code. Recorded as the attribution's source, as the browser said it: advisory, never proved." }
      responses:
        "202":
          description: Accepted. The same answer for any address.
          content:
            application/json:
              schema: { type: object, properties: { status: { type: string, enum: [check_email] } } }
        "400":
          description: Not a sign-up the form can take.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "422":
          description: The legal documents were not accepted, or not at the version published now; or the mobile's code was wrong (`mobile_code_wrong`); or the agent code is not accepted (`agent_code_not_accepted`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "503":
          description: No version of the legal documents is published yet, so sign-up is closed (`terms_not_published`); or the hour's ceiling of confirmation emails is reached (`signup_busy`, with `Retry-After`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/signup/options:
    get:
      tags: [Auth]
      summary: What sign-up offers, for a client that draws its own form
      description: |
        Public. Rate limit bucket `signUpOptions`: 60 requests/min per client, its own, so reading the offer spends nothing of
        the `signUp` bucket the code and the sign-up share. Never cached (`Cache-Control: no-store`). T-41.48: the
        website's `/sign-up/` form as data, for the one app's "Create your business account" — the plans with the form's price
        sentence, how often a plan may be paid, the ways of paying offered (one means there is nothing to ask: PayFast alone
        while Ruva offers no Yoco payment links, read for each request), each legal
        document to accept with its title and public path, the version published now, the longest name taken, and the form's
        words for every refusal `POST /api/v1/signup` answers, by its `error` code. While no version of the legal documents is
        published, `open` is false and nothing but the words is sent.
      x-rate-limit: "signUpOptions: 60/min"
      security: []
      responses:
        "200":
          description: The offer.
          content:
            application/json:
              schema:
                type: object
                properties:
                  open: { type: boolean }
                  termsVersion: { type: string, nullable: true }
                  documents:
                    type: array
                    items: { type: object, properties: { slug: { type: string }, title: { type: string }, path: { type: string } } }
                  plans:
                    type: array
                    items: { type: object, properties: { key: { type: string }, name: { type: string }, includedOrders: { type: integer }, note: { type: string } } }
                  terms:
                    type: array
                    items: { type: object, properties: { name: { type: string, enum: [MONTHLY, YEARLY] }, label: { type: string }, note: { type: string } } }
                  rails:
                    type: array
                    items: { type: object, properties: { name: { type: string, enum: [PAYFAST, YOCO] }, said: { type: string } } }
                  maxName: { type: integer }
                  words: { type: object, additionalProperties: { type: string } }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/signup/resend:
    post:
      tags: [Auth]
      summary: Send a sign-up's confirmation link again
      description: |
        Public. Rate limit bucket `signUp`: 5 requests/min per client. Hotfix 2026-11-24: "Send the link again" from a sign-in
        form that was answered `403 account_not_confirmed`. When the email's newest sign-up is still waiting and the password
        opens it, the request is stored again through `POST /api/v1/signup`'s own door (its caps; an older link is retired) and
        the confirmation is mailed in its fixed words. Otherwise nothing is stored or sent. The answer is the same `202` either
        way, given before the password is checked, so neither it nor its time depends on the password (a cap reached sends nothing).
      x-rate-limit: "signUp: 5/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password]
              properties:
                email: { type: string }
                password: { type: string }
      responses:
        "202":
          description: Sent, or not — the same answer either way.
          content:
            application/json:
              schema: { type: object, properties: { status: { type: string, enum: [check_email] } } }
        "429":
          description: Confirmation emails have already gone to that address this hour (`signup_address_limit`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/signup/mobile-code:
    post:
      tags: [Auth]
      summary: Send a sign-up's one-time code to the owner's mobile
      description: |
        Public. Rate limit bucket `signUp`: 5 requests/min per client. T-3.11 (one free trial per business): sends a six-digit
        code to the number by WhatsApp, from Ruva's own number (an AUTHENTICATION template), good for ten minutes and once —
        South African mobiles only (+27 6x/7x/8x; any other number is `400 mobile_not_za`);
        `POST /api/v1/signup` takes it beside the number. The answer is the same `202` for every number — it never says whether
        a number has had a trial. At most 3 codes an hour and 5 a day to one number, and a few a day from one client network
        or block (`429 mobile_code_limit`); past an hourly or daily ceiling across the server, `503 mobile_code_unavailable`
        (a sign-up without a code gets no trial while codes can be sent). T-41.88 (D-192): when Ruva's own send fails — no
        WhatsApp sender configured, or WhatsApp refused or did not answer — the answer is `503 mobile_code_later` with a
        sentence saying to carry on: for 30 minutes the server remembers (by the number's keyed hash, never anything the client
        sends) that it could not send, and `POST /api/v1/signup` with that number and no code starts the free trial with the
        mobile to confirm from the back office within 3 days (`POST /api/v1/billing/mobile-code`, `/billing/mobile-confirm`);
        unconfirmed by then, the trial ends and the owner is emailed once. A number that is not one is `400 mobile_invalid`.
        Only a keyed hash of the number and a salted hash of the code are kept, for a day.
      x-rate-limit: "signUp: 5/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mobileNumber]
              properties:
                mobileNumber: { type: string }
      responses:
        "202":
          description: Sent, or not — the same answer for any number.
          content:
            application/json:
              schema: { type: object, properties: { status: { type: string, enum: [code_sent] } } }
        "400":
          description: Not a mobile number (`mobile_invalid`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "503":
          description: |
            No code can be sent just now: `mobile_code_unavailable` (a ceiling across the server), or `mobile_code_later`
            (Ruva could not send it — carry on and sign up without a code; the mobile is confirmed from the back office).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/billing/mobile-code:
    post:
      tags: [Auth]
      summary: Send the owner a WhatsApp code to confirm the mobile a free trial waits for (owner)
      description: |
        T-41.88 (D-192). For a free trial that started without its mobile proved (the sign-up's code could not be sent), sends
        a six-digit code to `mobileNumber` by WhatsApp, under the sign-up code's rules (South African mobiles only, ten minutes,
        once, the same per-number and per-server caps). Needs MANAGE_LICENCE; spends `billingWrite` and `trialMobileCode`
        (5/hour per business). `409 mobile_nothing_to_confirm` when no trial waits for a mobile; `503 mobile_code_unavailable`
        when WhatsApp still cannot send, with a sentence saying the trial keeps running and how many days are left to confirm.
        Audited.
      x-rate-limit: "billingWrite: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mobileNumber]
              properties:
                mobileNumber: { type: string }
      responses:
        "202":
          description: Sent.
          content:
            application/json:
              schema: { type: object, properties: { status: { type: string, enum: [code_sent] } } }
        "400": { description: "Not a South African mobile number (`mobile_invalid`, `mobile_not_za_mobile`).", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "403": { description: "Not the owner." }
        "409": { description: "No trial waits for a mobile (`mobile_nothing_to_confirm`).", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "429": { description: "A code cap (`mobile_code_limit`), or more than the `billingWrite` or `trialMobileCode` bucket allows; see `Retry-After`." }
        "503": { description: "WhatsApp cannot send the code just now (`mobile_code_unavailable`); the trial keeps running.", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
  /api/v1/billing/mobile-confirm:
    post:
      tags: [Auth]
      summary: Confirm the mobile a free trial waits for with its WhatsApp code (owner)
      description: |
        T-41.88 (D-192). Proves `mobileNumber` by the code `POST /api/v1/billing/mobile-code` sent it, and answers the billing
        pane's data after it. One free trial per mobile number still holds: a number an earlier business's trial proved ends
        this trial now (`mobileToConfirm.state` `REPEAT`; the business and its data are kept, and a plan can be chosen); any
        other number keeps the trial and is bound to it. Needs MANAGE_LICENCE; spends `billingWrite`. A wrong code is
        `422 mobile_code_wrong` (five burn it); `409 mobile_nothing_to_confirm` when no trial waits for a mobile. Audited.
      x-rate-limit: "billingWrite: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mobileNumber, code]
              properties:
                mobileNumber: { type: string }
                code: { type: string }
      responses:
        "200": { description: "The billing pane's data after it; `mobileToConfirm` is absent once the trial is kept.", content: { application/json: { schema: { type: object } } } }
        "400": { description: "Not a South African mobile number (`mobile_invalid`, `mobile_not_za_mobile`).", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "403": { description: "Not the owner." }
        "409": { description: "No trial waits for a mobile (`mobile_nothing_to_confirm`).", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "422": { description: "The wrong code, or none waiting (`mobile_code_wrong`).", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
  /api/v1/agent-request:
    get:
      tags: [Auth]
      summary: Where this business stands on asking its agent (owner)
      description: |
        Whether the business has an agent (`linked`, never which one), whether a request is waiting (`open`, with `requestedAt` and
        `expiresAt`), whether it may ask now (`mayAsk`) and, when it may not, why (`refusal`: `already_has_agent`, `request_open`
        or `request_window_closed`, with `refusalWords`). `askUntil` is the last moment the business may ask: 90 days from sign-up.
        Needs MANAGE_LICENCE.
      responses:
        "200": { description: "The business's standing.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
    post:
      tags: [Auth]
      summary: Ask the agent this business forgot to name at sign-up (owner)
      description: |
        `{agent}`: the agent's email or code, typed by the owner. Only a business with no agent, within 90 days of its sign-up, with
        no request already waiting, may ask; the agent is told, sees the request in their own page, and the business is attributed
        to them only if they accept. The answer is the same `202` whatever was typed, so it never says whether such an agent exists,
        and the typed text is never stored. Needs MANAGE_LICENCE. Errors: `400 agent_request_missing`, `400 agent_request_too_long`,
        `409 already_has_agent`, `409 request_window_closed`, `409 request_open`.
      x-rate-limit: "agentRequest: 5/hour"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [agent]
              properties:
                agent: { type: string, description: "The agent's email or code, as the owner typed it." }
      responses:
        "202": { description: "Asked. The same whatever was typed.", content: { application/json: { schema: { type: object } } } }
        "400": { description: "Nothing typed, or too long.", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "403": { description: "Not the owner." }
        "409": { description: "The business already has an agent, a request is waiting, or the 90 days have passed.", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "429": { description: "More than the `agentRequest` bucket allows for this business in an hour; see `Retry-After`." }
  /api/v1/agent-request/withdraw:
    post:
      tags: [Auth]
      summary: Take back the waiting request (owner)
      description: Closes the request waiting for an agent's answer, so the business may ask another agent. Needs MANAGE_LICENCE. `409 no_open_request` when none is waiting.
      responses:
        "200": { description: "The new standing.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "409": { description: "No request is waiting.", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
  /api/v1/legal/terms:
    get:
      tags: [Auth]
      summary: Which version of Ruva's legal documents this business accepted (owner)
      description: |
        The version of the terms of service, privacy notice and operator agreement published now (null while none is),
        each document's title and public page, the documents this business has not accepted at that version yet
        (`outstanding`: ask the owner once) and every acceptance on record — document, version, the page's SHA-256,
        who, when and through which door (the address it came from is kept on record and never answered). Needs MANAGE_LICENCE.
      responses:
        "200": { description: "The business's standing.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
  /api/v1/legal/terms/accept:
    post:
      tags: [Auth]
      summary: Accept the published version of Ruva's legal documents (owner)
      description: |
        Records the signed-in owner's acceptance of every published document at `version`, once per business and
        version (a repeat records nothing), and answers the new standing. Needs MANAGE_LICENCE. `422
        terms_not_accepted` without a version, `422 terms_version_changed` at a version that is not the one published
        now, `503 terms_not_published` while none is.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [version]
              properties:
                version: { type: string }
      responses:
        "200": { description: "The new standing.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "422":
          description: No version, or not the one published now.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: Nothing is published.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/billing:
    get:
      tags: [Auth]
      summary: The subscription, its plan and its invoices (owner)
      description: |
        The plan, its monthly fee, how it is paid, whether a payment has landed (`PENDING` until the first, `ACTIVE`
        after, `LAPSED` when a Yoco link went unpaid three weeks past the end), the licence's last day, one invoice per
        paid period, newest first, and `payUrl`, the open Yoco link for the next month. Needs MANAGE_LICENCE.
        T-23.3: `products` lists each product held or waiting to start with its `state` (`PAID`, `TRIAL` from an add until its
        first payment with the first charge day, `ENDING` with its last day, `STARTING` — added again after its trial, in a paid
        period longer than a month (months paid ahead included), or not in the set a paid link priced — with the first day of the period that pays for it, or, once paid ahead, of the period it was paid for; no date is before today); `productAddRefused` is always null.
        T-23.9 (D-143): `tills` (a till plan only) says how many tills are signed in (`inUse`, across `locations`), the `included` three for each
        location, the `extra` above them, the `billed` count the next debit carries, `extraTillCents` each and the `from` day, with the `said` sentence.
        A till is a device selling (its check-in says it shows the till, or it rang a sale); the next debit carries the most held since the last
        payment, and `productFees` names the further tills and kitchen screens on lines of their own (`FURTHER_TILLS`, `FURTHER_KITCHEN_SCREENS`).
        A till is never refused for the count; PayFast is told first.
        `404 no_subscription` for a business with none. T-3.7: `state` is what the pane says (`TRIAL`, `ACTIVE`,
        `RENEWAL_FAILED`, `CANCELLING`, `LAPSED_IN_GRACE`, `LAPSED`) and `stateDate` the date it says it with;
        `lastGuestDay`, `cancelled`, `debitRunning`, and a waiting downgrade as `nextPlan` / `nextPlanFrom` — the first change of plan the
        days run — with `renewalPlan` / `renewalPlanFrom`, the plan the renewal after them is priced at and its first day (absent when it is
        today's plan with no change before it); each choice's `appliesFrom` is the first day it changes, and a choice that cannot be made
        now carries the server's sentence in `refused`. T-2.81: `monthlyCents`
        follows the live locations of a per-location plan (Group) — adding, deleting or restoring a location moves it, from the next
        debit, at the fee per location the subscription already pays (never a newer price list) — and `debitBehindSince` (epoch ms,
        absent when PayFast has it) is set while PayFast has not yet confirmed that amount. `monthlyIfLocationAddedCents` is what
        `monthlyCents` becomes if one more location is added, absent when an add changes nothing. T-35.24: `priceChange`
        (absent when none) is a change of Ruva's price list the owner has been told of and not yet moved to: `fromCents`, `toCents`,
        `movesOn` (the first day a payment is taken at the new amount, ISO), `refused` (the day has come and PayFast has not taken
        the new amount) and `said`, the sentence Billing shows. T-2.42:
        `heldPayments` lists a payment of the owner's that a rail took and Ruva has not booked as a period paid (`rail`,
        `kind`, `amountCents` when it is known, `takenAt`) until finance has dealt with it; empty when there is none.
        T-41.30: `term` is what the period being used was paid on (`MONTHLY` or `YEARLY`), `nextTerm` / `nextTermFrom` a switch
        waiting for the next renewal, and `terms` the choices (`term`, `cents` for one payment on it, `appliesFrom`, `current`);
        on a yearly plan `monthlyCents` is the year's fee, eleven months for twelve, and each plan choice's `renewalCents` its price
        on the term the next payment buys.
      responses:
        "200": { description: "The billing pane's data.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
  /api/v1/billing/payfast:
    post:
      tags: [Auth]
      summary: Where to set up the monthly PayFast debit (owner)
      description: |
        Answers `{payUrl}`, the page that posts PayFast's signed subscription form for the plan's fee. Needs
        MANAGE_LICENCE. `409 not_paid_by_payfast` or `409 debit_already_set_up` when there is nothing to set up
        (`409 card_already_kept` where the page keeps a card that Ruva charges, instead of a debit, and one is kept).
        A free trial's first debit that PayFast declined, or that has not come through by the end of the second day after it
        ran, leaves the business paused: then that debit is stopped at PayFast first and the form takes the first month now,
        which runs from that day. `502 payfast_unconfirmed` when PayFast did not confirm the stop (nothing changed); `409
        change_in_progress` beside another change of the subscription.
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "The page to open.", content: { application/json: { schema: { type: object, properties: { payUrl: { type: string } } } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Not paid by PayFast, the debit is already set up, or another change is in progress." }
        "502": { description: "PayFast did not confirm that the first debit was stopped; nothing changed." }
  /api/v1/billing/payfast/card:
    post:
      tags: [Auth]
      summary: Where to change the card the PayFast debit takes (owner)
      description: |
        Answers `{payUrl}`, PayFast's own card-update page for this business's held debit
        (`/eng/recurring/update/{token}?return=…` on PayFast's host — its test host when Ruva's PayFast account is in test
        mode), returning to the back office. Needs MANAGE_LICENCE. `409 not_paid_by_payfast` when the subscription is paid by
        a link, `409 subscription_cancelled` while cancelled (resume first), `409 no_card_on_file` when no debit is held (set
        one up with `POST /billing/payfast`).
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "The page to open.", content: { application/json: { schema: { type: object, properties: { payUrl: { type: string } } } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Not paid by PayFast, cancelled, or no debit is held." }
  /api/v1/billing/yoco:
    post:
      tags: [Auth]
      summary: Pay the next month now by the Yoco link (owner)
      description: |
        Answers `{payUrl}`, the hosted Yoco checkout on Ruva's own account for the next month's plan fee — the open
        link when one was already emailed, else one raised now (one per month; the same link every time). Nothing is
        charged without the owner paying it. Needs MANAGE_LICENCE. `409 not_paid_by_link` when the subscription is
        paid by the PayFast debit, `409 period_already_paid` when the next month is settled, `503
        payment_link_unavailable` when Yoco could not make the link.
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "The checkout to open.", content: { application/json: { schema: { type: object, properties: { payUrl: { type: string } } } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Not paid by a link, or the next month is already paid." }
        "503": { description: "The link could not be made just now." }
  /api/v1/billing/plan:
    post:
      tags: [Auth]
      summary: Change the plan (owner)
      description: |
        Body `{plan}`, a plan key. An upgrade (a dearer month) applies now and is charged from the next renewal; a
        downgrade applies from the day after the paid period ends, at its own price; no part-month is charged or
        refunded. The running PayFast debit's amount is changed at PayFast first; the open Yoco link is withdrawn and
        the next raised at the new price. Answers the billing pane's data; asking twice changes nothing more. Needs
        MANAGE_LICENCE. `422 plan_not_offered`, `409 group_needs_locations`, `409 subscription_cancelled`, `409
        plan_follows_products` (the business holds a till, so its price is its products' and it moves to no QR plan, T-23.2), `409
        plan_ended_upgrade` (the paid days are over and the plan is not a cheaper one: pay for the next month, or year on a yearly plan, or come back on a
        cheaper plan, which applies at once), `502 payfast_unconfirmed` (nothing changed). One change of a subscription runs at a time: a second while one is with
        PayFast is answered `409 change_in_progress` at once (nothing asked, nothing changed — look at Billing and try
        again); `409 changed_meanwhile` when the subscription moved while this was being made — nothing was changed, and
        PayFast's debit is set back to what Ruva records while this change still holds its turn.
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "The billing pane's data after the change.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Group before its locations, the subscription is cancelled, another change is in progress (`change_in_progress`), or it changed meanwhile (`changed_meanwhile`)." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "422": { description: "Not a plan this business may move to itself." }
        "502": { description: "PayFast did not change the debit; nothing changed." }
  /api/v1/billing/products:
    post:
      tags: [Auth]
      summary: Add a product to the subscription (owner, T-23.2, T-23.3)
      description: |
        Body `{products: [code]}`, `RuvaProduct` codes Ruva sells today. The business keeps its one subscription and its one
        licence: on a monthly plan a product new to the business is added through the licence's one writer and is on at once,
        its days until the next renewal its trial — once per product per business. A product it held before, and any product
        added while the paid period running is longer than a month (a paid year, even after a switch to monthly), is not on yet (`STARTING`): it comes on with the period that pays for it, on that period's first day. The subscription's
        fee becomes the renewal set's (its own agreed fee moved by the product's price; every part, a till too, priced for each
        location), charged from the next renewal. A running PayFast debit is told the new amount first, and an open Yoco link is withdrawn so the next is raised at the new price. Answers the billing pane's data. Needs
        MANAGE_LICENCE. `400 product_not_offered` (not on sale, or unknown), `409 product_held` (nothing new), `409 ask_support`
        (the business holds nothing, or holds a product that is not on sale: Ruva's support changes it), `409 change_in_progress`,
        `409 changed_meanwhile`, `409 subscription_cancelled`, `404 no_subscription`, `502 payfast_unconfirmed` (PayFast did not
        take the new amount: nothing changed). Audited with the products and the amount before and after. Web only: a store build
        and the desktop app offer no product add.
      x-rate-limit: "billingWrite: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [products]
              properties:
                products: { type: array, items: { type: string } }
      responses:
        "200": { description: "The billing pane's data after the change.", content: { application/json: { schema: { type: object } } } }
        "400": { description: "A product that is not on sale." }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Nothing new to add, the subscription is cancelled, Ruva's support changes what this business holds, another change is in progress, or it changed meanwhile." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "502": { description: "PayFast did not change the debit; nothing changed." }
  /api/v1/billing/kitchen-screens:
    post:
      tags: [Auth]
      summary: Set the further kitchen screens a till plan pays for (owner, T-23.6)
      description: |
        Body `{extra: n}`, 0 to 50: the total of further kitchen screens beyond the two a till plan includes for each location, at R149
        a month each (a flat amount, never repriced by a location). A raise lets a screen be added at once and is charged from the next
        renewal (the debit is told first, `502 payfast_unconfirmed` changes nothing; an open Yoco link at the old amount is superseded);
        a cut lowers the next renewal's amount and signs no screen out, so a cut below the screens in use is refused
        (`409 kitchen_screens_in_use`: sign one out first). A body without `extra` is `400`. Asking for what is already paid for changes nothing. Needs MANAGE_LICENCE. `409 kitchen_screens_need_a_till`
        (no till plan, or its till is being removed), `422 kitchen_screens_not_offered`, `409 subscription_cancelled`,
        `409 change_in_progress`, `409 changed_meanwhile`, `404 no_subscription`. Audited.
      x-rate-limit: "billingWrite: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [extra]
              properties:
                extra: { type: integer, minimum: 0, maximum: 50 }
      responses:
        "200": { description: "The billing pane's data after the change (`extraKitchenScreens`, `monthlyCents`).", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "No till plan, the subscription is cancelled, another change is in progress, or it changed meanwhile." }
        "422": { description: "Not between 0 and 50." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "502": { description: "PayFast did not change the debit; nothing changed." }
  /api/v1/billing/tier:
    post:
      tags: [Auth]
      summary: Move a till plan between the standard tier and Plus (owner, T-23.10)
      description: |
        Body `{tier: "BASE" | "PLUS"}`. Plus is a tier of the Restaurant and Shop plans: stock across locations, forecasts and
        reorder suggestions, API access and webhooks, and accounting integrations. Moving up is on at once and
        charged from the next renewal; inside a period longer than a month (a year, or months paid ahead) Plus starts when the
        renewal is paid, and a plan whose paid days are over is `409 plan_ended_upgrade`. Moving down keeps Plus through the last
        day a payment at the Plus price paid for, and is standard at once when none did. The
        next payment moves by the price list's difference between the two tiers (the debit is told first, `502 payfast_unconfirmed`
        changes nothing; an open Yoco link at the old amount is superseded). Asking for the tier the plan is on changes nothing;
        asking for Plus while a move down is waiting withdraws it. A business on the standard tier is answered
        `403 plus_required` by the routes of what Plus adds — every `/accounting` route that connects a package or sends it
        anything among them (its reads, disconnect and forgetting a key stay open) — and its webhooks wait, undelivered and kept. Needs MANAGE_LICENCE. `422 tier_not_offered`, `409 tier_needs_a_till`
        (no till plan: QR Ordering has no tier), `409 subscription_cancelled`, `409 change_in_progress`, `409 changed_meanwhile`,
        `404 no_subscription`. Audited.
      x-rate-limit: "billingWrite: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [tier]
              properties:
                tier: { type: string, enum: [BASE, PLUS] }
      responses:
        "200": { description: "The billing pane's data after the change (`tier`, `monthlyCents`).", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "No till plan, the paid days are over (`plan_ended_upgrade`), the subscription is cancelled, another change is in progress, or it changed meanwhile." }
        "422": { description: "Not a tier Ruva offers." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "502": { description: "PayFast did not change the debit; nothing changed." }
  /api/v1/billing/products/remove:
    post:
      tags: [Auth]
      summary: Remove a product from the subscription (owner, T-23.3)
      description: |
        Body `{products: [code]}`. A product paid for stays on until the paid period ends (the pane shows it `ENDING` with its last
        day), the debit is told the smaller amount first (`502 payfast_unconfirmed` changes nothing), and a sweep then switches it
        off through the licence's one writer; a product still in its trial, and every product when no paid days are left, ends at
        once; a product waiting to start is withdrawn, unless a payment already paid for it (`409 paid_add_waits`: it is taken off
        once it has started). Adding an ending product back withdraws its removal. Taking a till off
        leaves the business on its QR Ordering plan. Needs MANAGE_LICENCE. `400 product_not_offered`, `409 product_not_held`,
        `409 last_product` (that ends the subscription, which Cancel does), `409 renewal_in_flight` (the licence's last day has
        passed and its PayFast renewal may be on its way: try again once it is booked), `409 change_in_progress`,
        `409 changed_meanwhile` (a renewal booked meanwhile included), `409 subscription_cancelled`, `404 no_subscription`. Audited.
      x-rate-limit: "billingWrite: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [products]
              properties:
                products: { type: array, items: { type: string } }
      responses:
        "200": { description: "The billing pane's data after the change.", content: { application/json: { schema: { type: object } } } }
        "400": { description: "A product Ruva does not know." }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Not held, the last product, a renewal on its way, the subscription is cancelled, another change is in progress, or it changed meanwhile." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "502": { description: "PayFast did not change the debit; nothing changed." }
  /api/v1/billing/term:
    post:
      tags: [Auth]
      summary: Pay monthly or yearly from the next renewal (owner)
      description: |
        Body `{term}`, `MONTHLY` or `YEARLY` (T-41.30). The period being used runs as it was paid; the next payment is on the
        new term at the business's own fee converted (a year is eleven months' fee), with nothing charged, refunded or pro-rated
        for the switch. The running PayFast debit's amount and frequency are changed at PayFast first; the open Yoco link is
        withdrawn and the next raised on the new term. Asking for the term already chosen changes nothing. Usage (orders past
        the allowance, WhatsApp) stays monthly on either term. Needs MANAGE_LICENCE. `422 term_not_offered`, `409
        subscription_cancelled`, `409 change_in_progress`, `409 changed_meanwhile`, `502 payfast_unconfirmed` (nothing changed).
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "The billing pane's data after the switch.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "The subscription is cancelled, another change is in progress, or it changed meanwhile." }
        "422": { description: "Not monthly or yearly." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "502": { description: "PayFast did not change the debit; nothing changed." }
  /api/v1/billing/payment-method:
    post:
      tags: [Auth]
      summary: Change how the business pays Ruva (owner, with password)
      description: |
        Body `{change, currentPassword}` (T-41.59). `change` is one of the billing pane's `paymentChanges`: `NEW_CARD` (a new card
        for the PayFast debit), `TO_PAYFAST` (from Yoco links to the debit) or `TO_YOCO` (from the debit to Yoco links, only while
        Ruva offers links); `changesFrom` is the day the new way first pays — the day after the last paid day, or today once the
        paid days are over. Nothing already paid for is charged again, and the old way stops only once the new one is set.
        `NEW_CARD` and `TO_PAYFAST` change nothing yet: the answer's `payUrl` opens PayFast's form (a 30-minute link), which sets
        up a debit taking R0.00 now with its first run on `changesFrom` (in a trial, nothing before the trial ends); the link is
        `no-store` and stops opening once the change is made. When PayFast confirms it, the old card's debit is
        stopped at PayFast first and then the new one is kept (or the Yoco link withdrawn); if the old debit cannot be stopped
        the new debit is stopped at once instead and the owners emailed to try again (the ITN is answered `503` only when the
        new one cannot be stopped either). `TO_YOCO` stops the PayFast debit at
        PayFast now; the paid period stands and the link for the period after it is emailed as each renewal comes. Every change
        made is audited and emailed to the business's owners. Needs MANAGE_LICENCE and the owner's current password, asked
        before anything else: `403 reauth_required` (nothing changed). `400 payment_change_required`, `409 rail_not_offered`,
        `409 payment_change_not_now` (a running debit takes its next payment today or tomorrow, a debit payment is overdue, or
        the debit is paused while the account is on hold; the error's sentence names which — `paymentChangeWithheld` on the
        billing pane says the same before asking), `409 payment_change_not_offered`, `409
        subscription_cancelled`, `409 change_in_progress`, `502 payfast_unconfirmed` (the debit was not stopped; nothing changed),
        `503 payfast_not_configured`.
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "`{billing, payUrl}`: the billing pane's data, and PayFast's page to open for a card.", content: { application/json: { schema: { type: object, properties: { billing: { type: object }, payUrl: { type: string, nullable: true } } } } } }
        "400": { description: "No change named, or not one Ruva knows." }
        "403": { description: "Not the owner, or the password was missing or wrong (`reauth_required`)." }
        "404": { description: "No subscription." }
        "409": { description: "Not offered now (the debit runs today or tomorrow, is overdue or is paused), the subscription is cancelled, or another change is in progress." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "502": { description: "PayFast did not confirm the debit stopped; nothing changed." }
        "503": { description: "PayFast is not configured on Ruva's account." }
  /api/v1/billing/cancel:
    post:
      tags: [Auth]
      summary: Cancel the subscription at the end of the paid period (owner)
      description: |
        The subscription runs to the licence's last paid day, then the guests' grace; nothing more is taken or asked
        for (the PayFast debit is cancelled at PayFast; the Yoco link is withdrawn). Answers the billing pane's data
        (`CANCELLING`, dated); asking twice changes nothing more and is answered the same; asking while another change is
        with PayFast is `409 change_in_progress` (nothing asked). Needs MANAGE_LICENCE. `502 payfast_unconfirmed` when
        PayFast did not confirm the debit stopped (nothing changed).
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "The billing pane's data after the cancellation.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Another change is in progress (`change_in_progress`)." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
        "502": { description: "PayFast did not stop the debit; nothing changed." }
  /api/v1/billing/resume:
    post:
      tags: [Auth]
      summary: Undo a cancellation (owner)
      description: |
        Withdraws the cancellation, before its day or after. On Yoco the next month is asked for again; on PayFast the
        debit was cancelled at PayFast, so `debitRunning` is false and Billing offers to set it up again. Answers the
        billing pane's data. Needs MANAGE_LICENCE. `409 change_in_progress` while a cancellation is with PayFast.
      x-rate-limit: "billingWrite: 10/min"
      responses:
        "200": { description: "The billing pane's data after it.", content: { application/json: { schema: { type: object } } } }
        "403": { description: "Not the owner." }
        "404": { description: "No subscription." }
        "409": { description: "Another change is in progress (`change_in_progress`)." }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
  /api/v1/pay/payfast/subscription/{reference}:
    get:
      tags: ["Webhooks"]
      summary: The page that sets up a subscription's monthly PayFast debit
      description: >-
        An HTML page that posts PayFast's signed subscription form (monthly, until cancelled) for the plan's fee to
        Ruva's own PayFast account. Renders only for a PayFast subscription whose debit is not running yet.
      parameters:
        - { name: reference, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: "The auto-posting form.", content: { text/html: { schema: { type: string } } } }
        "404": { description: "Nothing to set up by that reference.", content: { text/html: { schema: { type: string } } } }
  /api/v1/pay/payfast/subscription/{reference}/change:
    get:
      tags: ["Webhooks"]
      summary: The page at a change link, which posts the link's ticket
      description: >-
        The page the `payUrl` `POST /billing/payment-method` answers opens, for a change of how the business pays (T-41.59). The
        link carries its signed ticket in the fragment (`#t=…`), which a browser never sends, so no request line holds it
        (T-41.67). The page is the same for everyone: its one script, allowed by hash, reads the fragment, takes it out of the
        address and posts the ticket to `POST` on this path. A request with a `t` query parameter is refused `410` with a sentence
        to start again from Settings → Billing. Every answer is `Cache-Control: no-store` and `Referrer-Policy: no-referrer`.
      parameters:
        - { name: reference, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: "The page that posts the ticket.", content: { text/html: { schema: { type: string } } } }
        "410": { description: "The old query link: never opened, whatever it carries.", content: { text/html: { schema: { type: string } } } }
    post:
      tags: ["Webhooks"]
      summary: The page that sets up a new card, or the PayFast debit in place of links, once per ticket
      description: >-
        An HTML page that posts PayFast's signed subscription form for the change the ticket names. The ticket signs this
        subscription and change, lasts 30 minutes, and opens the form once: it is spent as the form is issued (T-41.67). The form
        takes R0.00 now and first debits the day after the last paid day; once the paid days are over it takes the period due now.
        Renders only while the change is still offered, and stops opening once the change is made (or the way of paying changes
        otherwise). Every answer is `Cache-Control: no-store` and `Referrer-Policy: no-referrer`. Rate limit bucket `billingLink`.
      x-rate-limit: "billingLink: 10/min"
      parameters:
        - { name: reference, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [t]
              properties:
                t: { type: string, description: "The ticket from the change link's fragment." }
      responses:
        "200": { description: "The auto-posting form.", content: { text/html: { schema: { type: string } } } }
        "410": { description: "The ticket has expired, was used already, is another subscription's, or the change is no longer offered; the page says to start again from Settings → Billing.", content: { text/html: { schema: { type: string } } } }
        "429": { description: "More than the `billingLink` bucket allows for this client in a minute; see `Retry-After`." }
  /api/v1/pay/payfast/usage/{order}:
    get:
      tags: ["Webhooks"]
      summary: The page that pays a PayFast plan's usage
      description: >-
        An HTML page that posts PayFast's signed one-off payment form, to Ruva's own PayFast account, for exactly the
        usage the link carries (QR orders past the plan's allowance and WhatsApp messages, every month still owed). Its
        `m_payment_id` is the link's own reference, never the plan's, so the payment settles usage and never a plan
        month. Nothing is taken from the debit's card. Emailed to the owner when a month closes and opened from
        Billing; renders only while the link is open, and a link replaced by a later month's opens that one.
      parameters:
        - { name: order, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: "The auto-posting form.", content: { text/html: { schema: { type: string } } } }
        "404": { description: "Nothing to pay on that link.", content: { text/html: { schema: { type: string } } } }
  /api/v1/pay/payfast/subscription/{order}/card:
    get:
      tags: ["Webhooks"]
      summary: The page that pays a plan's period after its card was declined
      description: >-
        An HTML page that posts PayFast's signed one-off payment form, to Ruva's own PayFast account, for exactly the
        sum of one period's order (the plan's fee and any usage it carries) whose automatic charge on the kept card was
        declined or never answered. The card typed on PayFast's page is kept for later payments in place of the old
        one. Its `m_payment_id` is the order's own pay-link reference, so the payment settles that order once. Emailed
        to the owner once when the card is declined; renders only while the order is unpaid, and is never cached.
      parameters:
        - { name: order, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: "The auto-posting form.", content: { text/html: { schema: { type: string } } } }
        "404": { description: "Nothing to pay on that link.", content: { text/html: { schema: { type: string } } } }
        "429": { description: "More than the `billingLink` bucket allows for this client in a minute; see `Retry-After`." }
  /api/v1/licence/entitlements:
    get:
      tags: [Auth]
      summary: The products this tenant is licensed to run
      description: |
        Ruva is sold as three products — RESTAURANT, RETAIL and QR_ORDERING (V72). Entitlements also ride
        the access token as the `prd` claim (comma-separated codes), re-stamped on every refresh; this
        endpoint is the readable copy for UIs. Any authenticated staff may read it.
      responses:
        "200":
          description: The tenant's entitlements.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EntitlementsDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/licence/redeem:
    post:
      tags: [Auth]
      summary: Redeem a licence key (manager)
      description: |
        Replaces the tenant's product set with what the key grants and dates the term from redemption.
        Keys are normalised — case, spaces and dashes never decide whether a paying customer gets in.
        Each key redeems exactly once.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                code: { type: string, description: "The licence key, e.g. RUVA-7K2P-9QXM." }
              required: [code]
      responses:
        "200":
          description: Redeemed — the tenant's new entitlements.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EntitlementsDto" }
        "400":
          description: "`code_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`licence_not_found` — also the answer for a typo, deliberately."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`licence_already_redeemed` — by this tenant or another."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "422":
          description: "`licence_grants_nothing` — a bad issue, not a bad customer."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Setup (T-14.6) ─────────────────────────────
  /api/v1/setup:
    get:
      tags: [Auth]
      summary: Where the owner got to in first-run setup (manager)
      description: |
        Which setup steps are done or put off, whether the sample menu is on, and when setup was finished. Which steps
        apply follows the products switched on (no floor without table service, no till steps for QR Ordering alone);
        the client works that out from the same entitlements. A tenant that has never opened setup reads an empty record.
      responses:
        "200":
          description: The tenant's setup record.
          content:
            application/json:
              schema:
                type: object
                properties:
                  done: { type: array, items: { type: string }, description: "Steps marked done (BUSINESS, PRODUCTS, TAXES, CATALOGUE, FLOOR, STAFF, HARDWARE, FIRST_SALE; a business with no till has BUSINESS, CATALOGUE, TAXES, PAYMENTS, CODES, KITCHEN_SCREEN, TEST_ORDER)." }
                  skipped: { type: array, items: { type: string }, description: "Steps put off; they no longer hold up the next one." }
                  sampleMenu: { type: boolean, description: "Whether the sample products are on the menu." }
                  completedAt: { type: integer, format: int64, nullable: true, description: "When every step that applies was first closed (epoch ms)." }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/setup/steps:
    post:
      tags: [Auth]
      summary: Mark a setup step done or put it off (manager)
      description: |
        Done outranks skipped in either order. Setup is finished once, the first time every step that applies is closed;
        a step a later product adds does not reopen it. Each step's own work is done through that page's routes.
        `TEST_ORDER` closes by itself when a guest's order has been placed (reading the record closes it); marking it done
        before then is refused with `test_order_missing`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                step: { type: string, description: "A step name, case-insensitive." }
                outcome: { type: string, enum: [DONE, SKIPPED] }
              required: [step, outcome]
      responses:
        "200":
          description: The tenant's whole setup record after the change.
          content:
            application/json:
              schema:
                type: object
                properties:
                  done: { type: array, items: { type: string }, description: "Steps marked done (BUSINESS, PRODUCTS, TAXES, CATALOGUE, FLOOR, STAFF, HARDWARE, FIRST_SALE; a business with no till has BUSINESS, CATALOGUE, TAXES, PAYMENTS, CODES, KITCHEN_SCREEN, TEST_ORDER)." }
                  skipped: { type: array, items: { type: string }, description: "Steps put off; they no longer hold up the next one." }
                  sampleMenu: { type: boolean, description: "Whether the sample products are on the menu." }
                  completedAt: { type: integer, format: int64, nullable: true, description: "When every step that applies was first closed (epoch ms)." }
        "400":
          description: "`unknown_setup_step` — an unknown step or outcome; the message names the choices."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`test_order_missing` — `TEST_ORDER` marked done before any guest order was placed."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/setup/sample-menu:
    post:
      tags: [Auth]
      summary: Put the sample menu on or take it off (manager)
      description: |
        On adds a short sample menu (a shop catalogue when every location is a shop) once, with SKUs starting
        `SAMPLE-`; a second switch-on shows the same products again rather than adding more. Off hides every sample
        product from the menu and deletes nothing, so a sample that has been sold keeps its history.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                on: { type: boolean }
              required: [on]
      responses:
        "200":
          description: How many sample products are now shown and hidden, how many were added, and the setup record.
          content:
            application/json:
              schema:
                type: object
                properties:
                  shown: { type: integer }
                  hidden: { type: integer }
                  added: { type: integer }
                  progress: { type: object, description: "The setup record, as GET /api/v1/setup." }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Catalogue ─────────────────────────────
  /api/v1/catalogue/categories:
    get:
      tags: [Catalogue]
      summary: List categories for the tenant
      responses:
        "200":
          description: Categories, ordered by `sortOrder`.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CategoryDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Catalogue]
      summary: Upsert a category (Manager-gated)
      description: Upserts by `id` when supplied and owned by this tenant; otherwise inserts a new row. `409 id_conflict` if the `id` belongs to another tenant.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CategoryUpsertRequest" }
      responses:
        "200":
          description: Updated existing category.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "201":
          description: Created new category.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/catalogue/prep-stations:
    get:
      tags: [Catalogue]
      summary: List prep stations for the tenant
      description: KDS routing config (V12). Readable by any authed staff — the KDS station chips and the category/product editors need it.
      parameters:
        - name: includeInactive
          in: query
          description: When `true`, includes deactivated stations (back-office view). Defaults to active-only.
          schema: { type: boolean, default: false }
      responses:
        "200":
          description: Prep stations, ordered by `sortOrder`.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PrepStationDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Catalogue]
      summary: Upsert a prep station (Manager-gated)
      description: Upserts by `id` when supplied and owned by this tenant; otherwise inserts a new row. `409 id_conflict` if the `id` belongs to another tenant. `409 station_is_redirect_target` when switching off (`active` false) a station that closed stations send their work to (T-36.10) — reopen them, or send their work elsewhere, first.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PrepStationUpsertRequest" }
      responses:
        "200":
          description: Updated existing prep station.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "201":
          description: Created new prep station.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/catalogue/prep-stations/{id}/printer:
    put:
      tags: [Catalogue]
      summary: Set only a prep station's ticket printer (Manager-gated)
      description: |
        T-9.5 — what a till sends after **Find printers**: the station's network printer and nothing else, so the
        station's name, order, target time and active flag are left as they are. A blank `printerHost` clears it
        (tickets on the kitchen screen only); a missing `printerPort` with a host means 9100.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StationPrinterRequest" }
      responses:
        "200":
          description: The station as it now is.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PrepStationDto" }
        "400":
          description: "`invalid_printer_port` — a port outside 1–65535."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`station_not_found` — no such station for this business."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/catalogue/products:
    get:
      tags: [Catalogue]
      summary: List products for the tenant
      parameters:
        - name: includeInactive
          in: query
          description: When `true`, includes deactivated products (back-office view). Defaults to active-only (POS terminal view).
          schema: { type: boolean, default: false }
      responses:
        "200":
          description: Products, ordered by `sortOrder`.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ProductDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Catalogue]
      summary: Upsert a product (Manager-gated)
      description: True upsert — inserts when `id` is absent/unknown, updates the existing row (same tenant) otherwise. The request's `active` field is honoured on every upsert.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ProductUpsertRequest" }
      responses:
        "200":
          description: Updated existing product.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "201":
          description: Created new product.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/catalogue/products/{id}/activate:
    post:
      tags: [Catalogue]
      summary: Reactivate a product (Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Product reactivated.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, active: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/catalogue/products/{id}/deactivate:
    post:
      tags: [Catalogue]
      summary: Deactivate a product (Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Product deactivated.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, active: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/catalogue/products/{id}/prep-target:
    put:
      tags: [Catalogue]
      summary: Set or clear one dish's own prep target (Manager-gated)
      description: |
        How long a ticket carrying this dish should take on the kitchen display. A ticket's target is the
        longest of its dishes' own targets, else its station's, else the board's default. Send
        `targetSeconds: null` to clear it so the dish uses its station's target. A target is between 1 and
        120 minutes, in seconds. Its own route, so a product editor that never shows it cannot clear it.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                targetSeconds: { type: integer, nullable: true, minimum: 60, maximum: 7200, example: 900 }
      responses:
        "200":
          description: Target saved; echoes what was stored.
          content:
            application/json:
              schema: { type: object, properties: { targetSeconds: { type: integer, nullable: true } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/catalogue/products/{id}/variants:
    get:
      tags: [Catalogue]
      summary: List a product's variants (V18)
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: includeInactive, in: query, required: false, schema: { type: boolean, default: false } }
      responses:
        "200":
          description: Active (or all) variants, sort-ordered.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/VariantDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Catalogue]
      summary: Upsert a variant (V18, Manager-gated)
      description: sku/sortOrder are keep-on-absent on update. Variants sync to terminals like any catalogue row.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/VariantUpsertRequest" }
      responses:
        "200":
          description: Variant updated.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "201":
          description: Variant created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/catalogue/products/{id}/variants/{variantId}/retire:
    post:
      tags: [Catalogue]
      summary: Retire a variant (V18, Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: variantId, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Variant retired (soft delete).
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Unknown variant (`error:"variant_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/catalogue/labels:
    post:
      tags: [Catalogue]
      summary: Barcode label sheet PDF (V18, Manager-gated)
      description: |
        A4 sheet of Code 128 labels (3 per row): product name (+ variant), price, barcode, human-readable
        code. Encodes the variant SKU when a variantId is given, else the product barcode, else its SKU.
        Items with no code are skipped; `400 no_codes` when nothing printable remains. Capped at 1000 labels.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LabelSheetRequest" }
      responses:
        "200":
          description: The label sheet.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        "400":
          description: no_items / no_codes.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/catalogue/products/{id}/delete:
    post:
      tags: [Catalogue]
      summary: Remove a product from the menu (EDIT_CATALOGUE)
      description: |
        Takes the product off every guest menu and soft-deletes it (`deletedAt` set, `active` false, `sync_version`
        bumped), so tills drop it on their next pull and `GET /catalogue/products` no longer lists it. Past sales keep it.
        Removing a product already removed answers the same.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200": { description: The product is removed. }
        "403":
          description: The caller lacks EDIT_CATALOGUE (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such product in this business (`product_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/catalogue/categories/{id}/delete:
    post:
      tags: [Catalogue]
      summary: Remove a category (EDIT_CATALOGUE)
      description: |
        Soft-deletes the category (`deletedAt` set, `active` false, `sync_version` bumped), so tills drop it on their next pull
        and `GET /catalogue/categories` no longer lists it. A category under it becomes a top-level one. Refused while any
        product not removed (hidden ones included) is still in it. Removing a category already removed answers the same.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200": { description: The category is removed. }
        "403":
          description: The caller lacks EDIT_CATALOGUE (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such category in this business (`category_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Products are still in it (`category_has_dishes`); the message names how many and the remedy.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/catalogue/modifier-groups/{id}/delete:
    post:
      tags: [Catalogue]
      summary: Remove a modifier (option) group (EDIT_CATALOGUE)
      description: |
        Soft-deletes the group and its options and takes it off every product it was attached to (each `sync_version`
        bumped), so guests and tills stop offering it. Past sales keep the options they recorded. Removing a group already
        removed answers the same. To take a group off one product only, use `DELETE /catalogue/products/{id}/modifier-groups/{groupId}`.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200": { description: The group is removed. }
        "403":
          description: The caller lacks EDIT_CATALOGUE (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such group in this business (`modifier_group_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/catalogue/prep-stations/{id}/delete:
    post:
      tags: [Catalogue]
      summary: Remove a prep station (EDIT_SETTINGS)
      description: |
        Soft-deletes the station (`deletedAt` set, `active` false, `sync_version` bumped) and clears every route naming it —
        a category's default station, a product's own and extra stations, an option's station — so that work goes to the
        category's station or the usual routing instead. Past tickets keep it. Refused while orders are open there, while a
        closed station redirects its work to it, or while a kitchen screen is set to show it. Removing a station already
        removed answers the same.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200": { description: The station is removed. }
        "403":
          description: The caller lacks EDIT_SETTINGS (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such station in this business (`station_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: |
            Orders are open there (`station_has_open_tickets`), a closed station sends its work here
            (`station_is_redirect_target`), or a kitchen screen shows it (`station_on_screens`); the message gives the remedy.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/catalogue/products/{id}/photo:
    get:
      tags: [Catalogue]
      summary: Product photo bytes (Public)
      description: "Public (no JWT) — the customer QR menu's `<img>` tags fetch this directly. Served with `Cache-Control: public, max-age=300`. `503 picture_store_unavailable` when the picture store cannot be read."
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/PictureSize"
      responses:
        "200":
          description: Raw image bytes in the stored mime type.
          content:
            image/png: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/webp: { schema: { type: string, format: binary } }
        "404":
          description: Unknown product, or no photo stored (`error:"no_photo"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: [Catalogue]
      summary: Upload a product photo (Manager-gated)
      description: |
        Prepares a photo for the guest menu and rewrites the product's `imageUrl` to the internal
        `/api/v1/catalogue/products/{id}/photo` path, bumping `sync_version` so terminals repull the product on the
        next sync. The type is read from the bytes (the `mime` field is ignored): PNG or JPEG, at most 10 MB and
        50 megapixels, long edge at least 400 px. A WebP is taken only when it is lossy, already 800 px or smaller, still and
        metadata-free (a lossless WebP is refused), and is decoded and stored as a JPEG like any other photo.
        The server cuts the optional `crop`, turns the picture upright by its EXIF orientation, shrinks it to 800 px on its
        long edge and stores it as a JPEG, so the original is not kept and the camera's metadata (location included) is
        not served. A refusal is a 400 whose `message` says what to do (`invalid_image`, `image_too_large`, `invalid_crop`).
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ProductPhotoUploadRequest" }
      responses:
        "200":
          description: Photo stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ProductPhotoResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/catalogue/products/{id}/photo/delete:
    post:
      tags: [Catalogue]
      summary: Remove the stored product photo (Manager-gated)
      description: Nulls the stored photo. `imageUrl` is cleared only when it points at the internal photo path — a venue-set external URL is kept.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Photo removed; `imageUrl` reflects what the product now holds (may be an external URL or null).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ProductPhotoResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/catalogue/products/{id}/modifier-groups:
    get:
      tags: [Catalogue]
      summary: List a product's attached modifier groups
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Active links, in sort order.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ProductModifierLinkDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Catalogue]
      summary: Attach a modifier group to a product (Manager-gated, idempotent)
      description: Re-attaching an existing or soft-deleted link revives it and updates its sortOrder.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ProductModifierLinkRequest" }
      responses:
        "201":
          description: Link created (200 when an existing link was updated/revived).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ProductModifierLinkDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/catalogue/products/{id}/modifier-groups/{groupId}:
    delete:
      tags: [Catalogue]
      summary: Detach a modifier group from a product (Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
        - name: groupId
          in: path
          required: true
          schema: { type: string }
      responses:
        "204":
          description: Link soft-deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: No active link between this product and group (`error:"link_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/catalogue/modifier-groups:
    get:
      tags: [Catalogue]
      summary: List modifier groups (with their options) for the tenant
      responses:
        "200":
          description: Modifier groups, ordered by `sortOrder`, each with its active options.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ModifierGroupDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Catalogue]
      summary: Upsert a modifier group and atomically replace its option set (Manager-gated)
      description: Options present in the request are upserted (by `id` when given); options previously on the group but missing from the request are soft-deleted so `sync pull` propagates the removal.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ModifierGroupUpsertRequest" }
      responses:
        "200":
          description: Updated existing group.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModifierGroupDto" }
        "201":
          description: Created new group.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModifierGroupDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/catalogue/tax-rates:
    get:
      tags: [Catalogue]
      summary: List VAT/tax rates for the tenant
      responses:
        "200":
          description: Tax rates.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/TaxRateDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Catalogue]
      summary: Upsert a tax rate (Manager-gated)
      description: "`(tenant_id, code)` is unique — a duplicate `code` returns `409 duplicate_code`."
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TaxRateUpsertRequest" }
      responses:
        "200":
          description: Updated existing rate.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "201":
          description: Created new rate.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/catalogue/tax-rates/{id}:
    delete:
      tags: [Catalogue]
      summary: Delete a tax rate no item uses (EDIT_SETTINGS)
      description: >-
        D-225. A rate no live product is sold at is deleted: it leaves the list, and the till's next pull carries it with
        `deleted_at` set so its pickers drop it. The row is kept (soft delete), so a deleted product that carried the rate
        still names it. A rate any live product uses is refused `409 tax_rate_in_use`, whose message says how many items
        use it and to move them to another tax rate first. Saving a new rate with a deleted rate's `code` brings that rate back.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"

  # ───────────────────────────── Staff ─────────────────────────────
  /api/v1/staff:
    get:
      tags: [Staff]
      summary: List all staff for the tenant (Manager-gated)
      description: Includes inactive staff; check the `active` flag per row.
      responses:
        "200":
          description: Staff list, ordered by name.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/StaffDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Staff]
      summary: Create a staff member (Manager-gated)
      description: |
        A person who works at a screen with a PIN pad is made with a `pin`, stored as a PBKDF2 hash
        (`pbkdf2$<iters>$<salt>$<hash>`). A person who signs in with an email is made with `invite: true`, an `email` and
        optionally a `pin` (D-108: a manager in a business with no till also works the kitchen screen's pad): one account is
        made and one email carries a link to choose a password (works once, for 7 days; a newer invite retires it).
        The answer never carries the link; `inviteSent` says whether the email provider took it. The address is stored
        trimmed and lower-cased. `409 email_in_use` when the address already signs in here or is on the roster (one answer
        for both); `429 invite_limit_business` past 20 invite emails an hour for the business, resends included.
        Where the business requires a second factor (T-37.4), making or inviting anyone into a role it is for is
        `403 second_factor_required` from a session that has not typed its code — recorded, and emailed to the owner at most
        once an hour — and such a session sets no pay rate.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StaffCreateRequest" }
      responses:
        "201":
          description: Staff member created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StaffDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: The email is in use (`email_in_use`), or another active person already holds the PIN (`error:"pin_in_use"`, naming nobody).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Today's answers that a PIN is in use are spent for this person or the business (`error:"pin_checks_spent"`, until tomorrow), past 20 invite emails an hour (`invite_limit_business`), or the `staffPin` bucket when a PIN is sent (see `Retry-After`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/staff/approval-requests:
    post:
      tags: [Staff]
      summary: A till asks a manager's phone to approve a void, comp or discount
      description: |
        T-37.7. The asking till (TILL_SELL) names the change it needs approved, with the same body as
        `POST /staff/verify-manager-pin` less the PIN, and is answered 201 with the request's id. Managers who hold the
        kind's permission and are signed in on their own phone are sent a push that says only what, which order and how
        much, never who asked. A change with no bill (no-sale, kiosk exit, settings, floor edit) cannot be asked this way:
        400 `approval_not_for_a_phone`. At most 3 requests wait per till and 12 are asked per 15 minutes: 429
        `approval_requests_busy`. A request lasts 2 minutes.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ManagerPinCheckWithoutPin" }
      responses:
        "201":
          description: Asked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PhoneApprovalOpened" }
        "400":
          description: Not for a phone (`approval_not_for_a_phone`), no bill, or a figure the bill does not carry.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: The order or line is not this business's (`order_not_found`, `line_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Too many waiting or asked (`approval_requests_busy`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    get:
      tags: [Staff]
      summary: What is waiting for this manager to approve
      description: |
        T-37.7. The requests this person may decide now (APPLY_DISCOUNT, VOID_LINE or COMP_ITEM, the kind's own
        permission), each with the sentence to show. Never who asked, a till's name or a guest.
      responses:
        "200":
          description: The open requests.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PhoneApprovalWaitingList" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/staff/approval-requests/{id}/decision:
    post:
      tags: [Staff]
      summary: A manager approves or declines a till's request from their phone
      description: |
        T-37.7. Needs the permission of the request's kind, held by a person signed in with their own account: the asking
        till's own user, session and device are refused (403 `approval_not_your_own`), so is a session on a device pinned to a
        shared screen — a till, kitchen screen, kiosk or guest display (403 `approval_not_from_a_shared_screen`, before the request
        is read) — and a request that is answered, withdrawn or expired is 409 `approval_request_closed`. An approval gives the till nothing until the asking
        till's own session claims it; the decision is audited with the manager's id.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PhoneApprovalDecision" }
      responses:
        "204":
          description: Recorded.
        "403":
          description: Not a person who may approve this kind (`permission_required`), the asker itself (`approval_not_your_own`), or a shared screen (`approval_not_from_a_shared_screen`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: No such request in this business (`approval_request_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Already answered, withdrawn or expired (`approval_request_closed`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/staff/approval-requests/{id}/claim:
    post:
      tags: [Staff]
      summary: The asking till collects a manager's answer
      description: |
        T-37.7. Polled by the till that asked (TILL_SELL; only its own user, session and device, else 404
        `approval_request_not_found`). The answer is a status (WAITING, APPROVED, DECLINED, CLAIMED, CANCELLED, EXPIRED)
        and, on the one claim that gets it, the same single-use `approval` `POST /staff/verify-manager-pin` issues, bound to
        the request's kind, order, line and amount, to the asking user and to the manager who approved (handed only to the asking
        session on the asking device; once issued it is spent as a PIN's approval is, by that user, once). A later
        claim answers CLAIMED with no approval. The manager must still hold the permission when it is claimed.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The status, and the approval once.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PhoneApprovalAnswer" }
        "404":
          description: Not this till's request (`approval_request_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/staff/approval-requests/{id}/cancel:
    post:
      tags: [Staff]
      summary: The asking till withdraws its request
      description: T-37.7. Best effort, by the till that asked; an answered or unknown request is left as it is.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Withdrawn, or nothing to withdraw.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/staff/verify-manager-pin:
    post:
      tags: [Staff]
      summary: Check a manager's PIN typed at a till, and issue a single-use approval
      description: |
        T-2.49 (D-93). A till signed in by a cashier holds no manager's PIN hash, so the server checks it. Open to any
        seller (TILL_SELL): the gate is the PIN. The answer says which manager approved and carries `approval`, a token
        bound to this business, `orderId`, `kind` (DISCOUNT or OPEN_PRICE) and `amountCents`, good for 5 minutes and
        spent once by `POST /orders/{id}/lines` (`discountApproval` / `openPriceApproval`), which checks again that its
        approver is still an active manager here. No PIN hash and no account detail is ever answered.

        Every refusal is the same 403 `manager_pin_required`, whether the PIN is nobody's or a non-manager's, never 401.
        Rate limited with sign-in per client, and counted per business together with `POST /devices/this/unpin`: every
        attempt from any device is recorded before its PIN is checked, and after 10 refusals in 15 minutes (or 30 in a day)
        every attempt is a 429 `manager_pin_locked` until the window moves on.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ManagerPinCheck" }
      responses:
        "200":
          description: A manager's PIN; the approval.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ManagerApproval" }
        "400":
          description: No order, or an amount not above nothing (`error:"bad_approval_request"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Not an active manager's PIN here (`error:"manager_pin_required"`), or the caller cannot sell.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Too many refusals at this business's devices (`error:"manager_pin_locked"`), or the sign-in rate limit.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/staff/me/pin:
    get:
      tags: [Staff]
      summary: Whether the signed-in person has a PIN, and may set one
      description: |
        D-179. For any person (never a screen signed in as itself): `hasPin`, and `canSet` — true for every person's account,
        one on no staff list yet included (D-206: its first PIN puts it there).
      responses:
        "200":
          description: The person's PIN state.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OwnPinState" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Staff]
      summary: Set the signed-in person's own PIN, after their password
      description: |
        D-179. Only the caller's own row, and only a person's (a screen signed in as itself is `403 person_required`). The
        password is typed again. The PIN is 4-8 digits, and one digit repeated, a run like 1234 or two digits taking turns is
        `400 weak_pin`. A shared station's pad finds a person by their PIN alone, so a PIN a colleague holds is
        `409 pin_taken` ("Choose a different PIN."), naming nobody, and only after the weak-PIN check and the password: at
        most three a day per person (South Africa's date, counted in the database, each audited as `staff.own_pin_taken`
        naming the caller), then `429 own_pin_tries_spent` for every call until tomorrow. Bumps the row's sync version, so
        every till pulls the new hash. A manager's `POST /staff/{id}/reset-pin` is unchanged.
      x-rate-limit: "ownPin: 10/hour"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OwnPinRequest" }
      responses:
        "200":
          description: The PIN is set.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OwnPinState" }
        "400":
          description: Not a PIN this rule accepts (`error:"weak_pin"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The password is wrong (`error:"wrong_password"`), or the caller is a screen (`error:"person_required"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: A colleague holds that PIN (`error:"pin_taken"`), or the sign-in is no person's account here (`error:"no_staff_row"`). An account on no staff list yet is put on it by its first PIN (D-206).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Today's three `pin_taken` answers are spent for this person, or the business's ten (an owner's own three only) (`error:"own_pin_tries_spent"`, until tomorrow), or the `ownPin` bucket for this person or the sign-in rate limit (see `Retry-After`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/staff/{id}/invite:
    post:
      tags: [Staff]
      summary: Send a person invited by email a fresh set-your-password link (Manager-gated)
      description: |
        Retires the earlier link, so one is live. Only for a person who has an email account and has not yet claimed it (chosen a password from a link, or signed in);
        `409 no_account` (a PIN person), `account_inactive`, `already_signed_in`, `429 invite_limit` (three an hour for one person), `429 invite_limit_business` (20 an hour for the business);
        `403 target_outranks_caller` when that person's role outranks the caller's; `403 second_factor_required` for a role the
        business's second factor is for, from a session that has not typed its code (T-37.4).
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Whether the email provider took the email.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, inviteSent: { type: boolean } }, required: [id, inviteSent] }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/staff/{id}:
    post:
      tags: [Staff]
      summary: Partially update a staff member (Manager-gated)
      description: |
        Where the business requires a second factor (T-37.4), raising anyone into a role it is for, or changing the email of or
        reactivating someone who holds one, is `403 second_factor_required` from a session that has not typed its code; nothing
        changes, the try is recorded and the owner is emailed at most once an hour. Only fields present in the body change. `active:false` deactivates — the staffer loses POS access once terminals sync.
        For a person who signs in with an email, deactivating or a new role also ends every refresh token they hold (an access
        token already issued is refused at its next request: every request is checked against its session, T-2.22), and
        deactivating retires their unspent invite link, so activating them again revives none. The email is stored trimmed
        and lower-cased, is never blank (`400 email_required`), cannot be another person's here (`409 email_in_use`) and,
        once they have claimed the account — chosen a password from a link, or signed in — cannot be changed here at all
        (`409 sign_in_email_is_theirs`). Before that, only the person who sent the invite or someone senior to the invitee
        may change it (`403 invite_email_not_yours`); the change retires the link sent to the old address and is audited as
        `staff.email_changed`, naming who changed it and never either address.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StaffUpdateRequest" }
      responses:
        "200":
          description: Updated staff member.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StaffDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/staff/{id}/reset-pin:
    post:
      tags: [Staff]
      summary: Reset a staff member's PIN (Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StaffResetPinRequest" }
      responses:
        "200":
          description: PIN reset.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, pinReset: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Another active person already holds the PIN — the person being reset included, whose own current PIN is no new PIN (`error:"pin_in_use"`, naming nobody).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Today's answers that a PIN is in use are spent for this person or the business (`error:"pin_checks_spent"`, until tomorrow), or the `staffPin` bucket (see `Retry-After`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/shifts/clock-in:
    post:
      tags: [Staff]
      summary: Clock in (open a shift)
      responses:
        "201":
          description: Shift opened.
          content:
            application/json:
              schema: { type: object, properties: { shiftId: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: Staffer already has an open shift (`error:"shift_already_open"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ClockInRequest" }
  /api/v1/shifts/clock-out:
    post:
      tags: [Staff]
      summary: Clock out (close a shift)
      description: >-
        A person closes their own shift; closing someone else's (a leaver's, a colleague's) needs CLOSE_SHIFT (403
        `permission_required`) and is written down as `shift.clock_out_for_another`. Minutes of breaks recorded on the shift (see
        `/shifts/{id}/break/start`) come off its paid minutes, and a `breakMinutes` typed in the body is kept only when no break was
        recorded. While a break runs on the shift the clock-out is refused, 409 `break_running`, its message naming when the break
        began ("Your break started at 14:00. End it first, or ask a manager."): end it first, or a manager force-closes the shift.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ClockOutRequest" }
      responses:
        "204":
          description: Shift closed.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: A break is running on the shift (`error:"break_running"`); the message says when it began.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/duty/on:
    post:
      tags: [Staff]
      summary: Clock on duty, apart from the cash drawer (T-33.1)
      description: >-
        Any person; naming someone else (a till's PIN sign-in) needs TILL_SELL or EDIT_STAFF. The device mints `id` before
        the first attempt and the server looks it up first, so a lost answer or a queued replay lands once. A person already
        on duty is answered 200 with their open stint and nothing is written. A photo the server cannot read never refuses
        the clock-on: the row records `UNREADABLE`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DutyOnRequest" }
      responses:
        "201":
          description: On duty.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyOnAnswer" } } }
        "200":
          description: Already on duty; the open stint.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyOnAnswer" } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/duty/off:
    post:
      tags: [Staff]
      summary: Clock off duty
      description: Ends the stint in force for `dutyId` (followed through any correction). Ending an ended stint changes nothing.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DutyOffRequest" }
      responses:
        "204":
          description: Off duty.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/duty/{id}/correct:
    post:
      tags: [Staff]
      summary: Correct a clock time (EDIT_STAFF)
      description: >-
        A new row naming the one it corrects, with the corrector and the reason; the original is kept as it was recorded.
        A row already corrected is refused 409 `already_corrected`: correct the latest entry.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DutyCorrectionRequest" }
      responses:
        "201":
          description: Corrected.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Already corrected.
  /api/v1/duty/me:
    get:
      tags: [Staff]
      summary: The signed-in person's own open stint (any person)
      parameters:
        - { name: staffId, in: query, required: false, schema: { type: string }, description: "A till's PIN-signed-in person; someone else needs VIEW_STAFF or EDIT_STAFF." }
      responses:
        "200":
          description: Their stint on duty, or `open` absent when they are off duty.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyMine" } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/duty/now:
    get:
      tags: [Staff]
      summary: Who is on duty now (VIEW_STAFF or EDIT_STAFF)
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string } }
      responses:
        "200":
          description: Each stint in force with no end, with minutes late against the published roster.
          content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/DutyRowDto" } } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/duty/floor:
    get:
      tags: [Staff]
      summary: The waiters on duty now, for the kitchen screen's Service face (KDS_VIEW)
      description: Name, role and start only, for the roles the kitchen calls waiters (server, bartender). No photo, lateness or reason; those stay in `/duty/now`.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string } }
      responses:
        "200":
          description: Longest on duty first.
          content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/OnDutyPerson" } } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/duty:
    get:
      tags: [Staff]
      summary: The duty log, every row as recorded (VIEW_STAFF or EDIT_STAFF)
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string } }
        - { name: staffId, in: query, required: false, schema: { type: string } }
        - { name: from, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: until, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: before, in: query, required: false, schema: { type: string }, description: "The previous page's nextBefore." }
        - { name: limit, in: query, required: false, schema: { type: integer, default: 100, maximum: 200 } }
      responses:
        "200":
          description: Newest first; an original carries `supersededBy`, the correction that replaced it.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyLogPage" } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/duty/{id}/photo:
    get:
      tags: [Staff]
      summary: The clock-on photo (VIEW_STAFF or EDIT_STAFF)
      description: The re-encoded still, `Cache-Control private, no-store`. A person looks at it; nothing compares faces.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The photo.
          content:
            image/jpeg: { schema: { type: string, format: binary } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/duty/photo-retention:
    get:
      tags: [Staff]
      summary: How many days clock-on photos are kept (VIEW_STAFF or EDIT_STAFF)
      responses:
        "200":
          description: The period.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyPhotoRetention" } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Staff]
      summary: Set how many days clock-on photos are kept, 1 to 365 (EDIT_STAFF)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DutyPhotoRetention" }
      responses:
        "200":
          description: Set.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyPhotoRetention" } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/duty/photo-setting:
    get:
      tags: [Staff]
      summary: Whether a clock-on takes a photo (VIEW_STAFF or EDIT_STAFF)
      responses:
        "200":
          description: The switch.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyPhotoSetting" } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Staff]
      summary: Switch the clock-on photo on or off (EDIT_STAFF); off, no device opens its camera and no picture is kept
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DutyPhotoSetting" }
      responses:
        "200":
          description: Set.
          content: { application/json: { schema: { $ref: "#/components/schemas/DutyPhotoSetting" } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/duty/photos/{staffId}:
    delete:
      tags: [Staff]
      summary: Erase a person's clock-on photos (EDIT_STAFF)
      parameters:
        - { name: staffId, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: How many were erased; the times stay.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/shifts/{id}/break/start:
    post:
      tags: [Staff]
      summary: Start a break on an open shift (T-25.4)
      description: >-
        Any person for their own shift; another person's needs CLOSE_SHIFT and is written down as `shift.break_started_for_another`.
        Only one break runs at a time: starting while one runs changes nothing, so a retried tap is one break. Online only, never
        queued, and timed by the server's clock: no body is read, so a time a client sends is ignored.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "204":
          description: A break is running.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Unknown shift (`error:"shift_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: The shift is closed (`error:"shift_not_open"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/shifts/{id}/break/end:
    post:
      tags: [Staff]
      summary: End the break running on an open shift (T-25.4)
      description: >-
        Adds the minutes the break ran (to the nearest whole minute) to the shift's recorded break minutes, which come off its paid
        minutes when it closes. Ending when none runs changes nothing and answers the minutes recorded so far, so a retried tap is
        one break. Timed by the server's clock, like the start. Same gate as the start; another person's is written down as
        `shift.break_ended_for_another`.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The shift's recorded break minutes.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ShiftBreakResult" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Unknown shift (`error:"shift_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: The shift is closed (`error:"shift_not_open"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/shifts/{id}/close:
    post:
      tags: [Staff]
      summary: Force clock-out any open shift by id (Manager-gated)
      description: |
        Closes ANY open shift for the tenant — for staff who left without clocking out (EDIT_STAFF). The
        same close as the self `/shifts/clock-out`; a break still running ends at the close time, its
        minutes come off the paid minutes, and ending it is written down as `shift.break_ended_at_close`.
        The body is optional; when `closingFloatCents` is absent the stored value is left untouched.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ShiftCloseRequest" }
      responses:
        "200":
          description: Shift closed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ShiftCloseResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Unknown shift (`error:"shift_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Shift is not OPEN (`error:"shift_already_closed"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/shifts/open:
    get:
      tags: [Staff]
      summary: List currently open shifts for the tenant
      responses:
        "200":
          description: Open shifts.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/OpenShiftDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/shifts/{id}/movements:
    post:
      tags: [Staff]
      summary: Record a register cash movement (V17)
      description: |
        Reason-coded drawer event against an OPEN shift: `PAID_IN` | `PAID_OUT` | `NO_SALE`.
        Amounts are positive; direction comes from the type. `NO_SALE` must carry amount 0
        (audit trail for opening the drawer without a sale — the physical kick happens on the
        terminal). Movements feed the X/Z expected-cash line. `CASH_REFUND` (T-41.39) is written only by a refund that handed
        cash back at this register, never through this route (`400 invalid_movement_type`).
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CashMovementRequest" }
      responses:
        "201":
          description: Movement recorded.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          description: Invalid type/amount/reason (`invalid_movement_type`, `invalid_amount`, `reason_required`), or an id starting `cash-refund-`, which is kept for a cash refund's own movement (`invalid_movement_id`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Unknown shift (`error:"shift_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Shift is not OPEN (`error:"shift_not_open"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    get:
      tags: [Staff]
      summary: List a shift's cash movements (oldest first)
      description: A venue that closes by blind count leaves the `CASH_REFUND` rows out for a caller who is not a manager, as it withholds the expected cash.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Cash movements for the shift.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CashMovementDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/shifts/history:
    get:
      tags: [Staff]
      summary: Closed-register history (V17)
      description: |
        CLOSED shifts newest-first with the closure numbers persisted at Z-report time
        (expected/counted/variance — null on shifts closed before a Z was run) plus per-shift
        paid-in/paid-out totals.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string } }
        - { name: from, in: query, required: false, schema: { type: integer, format: int64 }, description: "clockOutAt ≥ from (epoch millis)" }
        - { name: until, in: query, required: false, schema: { type: integer, format: int64 }, description: "clockOutAt ≤ until (epoch millis)" }
        - { name: limit, in: query, required: false, schema: { type: integer, default: 60, maximum: 200 } }
      responses:
        "200":
          description: Closed shifts with closure numbers.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ShiftSummaryDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"

  # ───────────────────────────── Locations ─────────────────────────────
  /api/v1/locations:
    get:
      tags: [Locations]
      summary: List active locations for the tenant
      responses:
        "200":
          description: Active locations with business-profile fields (receipt header/footer, `hasLogo`).
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/LocationDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Locations]
      summary: Upsert a location (Manager-gated)
      description: |
        Inserts when `id` is absent/unknown, updates otherwise. Optional fields are keep-on-absent on
        update (null leaves the stored value alone); on insert `timezone`/`currency` default to
        `Africa/Johannesburg`/`ZAR`. T-2.81: on a plan that charges for each location (Group), a NEW location
        moves the monthly debit (to the fee per location the subscription already pays, for each live location,
        from the next debit), so it also needs MANAGE_LICENCE: anyone else is refused `403 billing_owner_only`,
        whose message names the new monthly amount. An update of an existing location, or a replayed add with the
        same `id`, is never refused for this. T-23.3: a till is priced for each location, so a second live location reprices
        the set like any other part (`409 change_in_progress` while another change to the subscription is being made).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LocationUpsertRequest" }
      responses:
        "200":
          description: Upserted.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/locations/{id}/logo:
    get:
      tags: [Locations]
      summary: Location logo bytes (Public)
      description: "Public (no JWT) — digital receipts and the QR ordering surface render the branding logo directly. Served with `Cache-Control: public, max-age=300`. Always the re-encoded copy Ruva stored (a PNG or JPEG of at most 512 px with no camera data). `503 picture_store_unavailable` when the picture store cannot be read."
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/PictureSize"
      responses:
        "200":
          description: Raw image bytes in the stored mime type.
          content:
            image/png: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/webp: { schema: { type: string, format: binary } }
        "404":
          description: Unknown location, or no logo stored (`error:"no_logo"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: [Locations]
      summary: Upload the location's branding logo (Manager-gated)
      description: |
        Stores the base64 image (decoded size ≤1 MB; PNG/JPEG/WebP) used on printed/digital receipts. The type is read from the
        file's bytes, never `mime`; a WebP only when lossy, still, at most 200 KB and 512 px, and carrying no camera data. What is
        stored is a re-encoded copy, never the upload: a PNG (when transparent) or JPEG of at most 512 px, with none of the
        camera's data (a photo's location, for one). A body past the limit is `413 image_too_large`;
        a file that is not a readable picture, or over 1 MB, is `400 invalid_image` / `400 image_too_large` with the reason.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ImageUploadRequest" }
      responses:
        "200":
          description: Logo stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LocationLogoResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/locations/{id}/layby-policy:
    get:
      tags: [Locations]
      summary: This location's lay-by policy (TILL_SELL)
      description: The smallest deposit that opens a lay-by and the fee kept on cancellation, in basis points (V98, T-4.4). The till reads it to offer only what the server accepts.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The policy; a location never set up answers 0 and 0.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LaybyPolicyDto" }
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: [Locations]
      summary: Replace this location's lay-by policy (Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LaybyPolicyDto" }
      responses:
        "200":
          description: The policy as stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LaybyPolicyDto" }
        "400":
          description: "`invalid_layby_policy` — a deposit outside 0%–90%, or a cancellation fee above 1% of the price; the message says which."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: Not a manager (`manager_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/locations/{id}/tip-policy:
    get:
      tags: [Locations]
      summary: How this location shares its tips (Manager-gated)
      description: DIRECT (each server keeps their own; only tips with no server are pooled), POOLED (one pool shared by minutes worked) or ROLE_SHARES (one pool shared between roles by `roleShares`, then by minutes worked within each role), and the tip-outs passed to a role first (T-3.6, V96, T-35.7, V391). Every change is audited (`TIP_POLICY_CHANGED`, with the policy before and after).
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The policy; a location never set up answers DIRECT with no tip-outs.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TipPolicyDto" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: [Locations]
      summary: Replace this location's tip policy (Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TipPolicyDto" }
      responses:
        "200":
          description: The policy as stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TipPolicyDto" }
        "400":
          description: "`invalid_tip_mode`, `invalid_tip_out_role` (not a person's role), `invalid_tip_out` — a rate outside 0.01%–50%, two rules for one role, or rules passing on more than 50% together — or `invalid_role_share`: role shares that do not add up to 100%, a role named twice or holding a tip-out as well, or shares sent with another mode; the message says which."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: Not a manager (`manager_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/locations/{id}/kitchen-hours:
    put:
      tags: [Locations]
      summary: Replace this location's kitchen hours, the week whole (MANAGE_LOCATIONS, T-39.20)
      description: "Until when the kitchen takes orders, per weekday, in the location's own time zone. A day left out no longer opens; an empty week sets none, and guests' menus show only the table again. The guest menu (`GET /qr/menu`) carries the week as `kitchenHours`. Outside the hours a guest's order for now (POST /qr/orders, QR and kiosk) is refused `409 kitchen_closed` (T-41.40); a takeaway or delivery for a later time is judged by that time, and `/qr/slots` lists only times inside the hours (T-41.42); an order already placed is never touched, and a till's own orders are never refused. Audited by the plugin (`location.kitchen_hours`). Online only."
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/KitchenWeek" }
      responses:
        "200":
          description: The week as stored, Monday first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/KitchenWeek" }
        "400":
          description: "`invalid_kitchen_hours` — a weekday outside 1–7 or given twice, a time outside 00:00–23:59, a day that closes when it opens, or a late night that runs past the next day's opening; the message says which and what to change."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: Not allowed to manage locations (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/locations/{id}/logo/delete:
    post:
      tags: [Locations]
      summary: Remove the stored location logo (Manager-gated)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Logo removed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LocationLogoResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"

  /api/v1/locations/{id}/delete:
    post:
      tags: [Locations]
      summary: Remove a location (MANAGE_LOCATIONS)
      description: |
        Soft-deletes the location, so guests can no longer order there and it is no longer counted in the bill; its
        sales, orders and reports stay. Refused `409 last_location` for the business's only location and
        `409 location_has_devices` while a device is still set to it, and `409 kitchen_screens_in_use` when the plan's kitchen-screen
        limit at one location fewer (a till's two a location, Starter's one) is below the screens in use, each with a sentence naming the remedy. When the
        removal changes what the business pays, only the owner (MANAGE_LICENCE) may make it (`403 billing_owner_only`).
        Removing a location already removed answers the same.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200": { description: The location is removed. }
        "403":
          description: The caller lacks MANAGE_LOCATIONS, or the removal changes the bill and the caller is not the owner.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such location in this business (`location_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The last location, one a device is still set to, or one whose removal leaves more kitchen screens in use than the plan includes (`last_location`, `location_has_devices`, `kitchen_screens_in_use`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/locations/{id}/whatsapp-ordering:
    get:
      tags: [Locations]
      summary: Whether guests may order by WhatsApp here, and the link they open (EDIT_SETTINGS, T-43.31)
      description: Off by default. A guest opens the link (a chat with Ruva's ordering number, the location's reference already typed), is answered with the venue's menu in a WhatsApp Flow, and the Flow's basket becomes an ordinary QR order, paid first on the venue's own hosted checkout; it takes orders only while the location's WhatsApp switch (`PUT /locations/{id}/whatsapp`) is on too. The reference is minted by Ruva, never typed. Each guest number and each location has an hourly budget (`whatsappOrderGuest`, `whatsappOrderVenue`).
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The switch and the link.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WhatsAppOrderingView" }
        "403":
          description: Not a role holding EDIT_SETTINGS (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    put:
      tags: [Locations]
      summary: Turn WhatsApp ordering on or off, or replace its link (EDIT_SETTINGS, T-43.31)
      description: The first time ordering is turned on, Ruva mints the location's reference (`wo_` and 144 random bits); turning it off keeps it, so links and QR codes already shared work again when it is turned back on. `newLink` mints a new one, after which every link shared before opens nothing. Nobody types a reference, so none can be taken from another venue. Audited by the realm's plugin.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WhatsAppOrderingChange" }
      responses:
        "200":
          description: The setting as stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WhatsAppOrderingView" }
        "403":
          description: Not a role holding EDIT_SETTINGS (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/locations/{id}/ordering-pace:
    get:
      tags: [Locations]
      summary: Busy mode — whether guests may order here now, and the wait they are told (KDS_VIEW or PACE_ORDERING, T-1.15)
      description: Read by the kitchen screen's bar and the back office. `mayChange` says whether the caller holds PACE_ORDERING (chefs and management; never a paired screen).
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The location's pace now; a location never set takes orders with no extra time.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderingPaceState" }
        "403":
          description: Neither KDS_VIEW nor PACE_ORDERING (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    put:
      tags: [Locations]
      summary: Pause guest ordering or add prep time (PACE_ORDERING, T-1.15)
      description: The whole setting, as absolute values, so a retry lands the same. While paused, POST /qr/orders (QR and kiosk) is refused `409 ordering_paused`; a resume time is read, not run — once it passes the location is open. Audited (`location.ordering_pace`). Online only — a device does not queue it.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                paused: { type: boolean }
                resumeAt: { type: integer, format: int64, nullable: true, description: "Only while paused: in the future, within 24 hours; null is until resumed." }
                extraMinutes: { type: integer, minimum: 0, maximum: 120, default: 0 }
              required: [paused]
      responses:
        "200":
          description: The pace as stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderingPaceState" }
        "400":
          description: "`extra_minutes_out_of_range`, `resume_without_pause` or `resume_at_out_of_range`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: Not a chef or management (`permission_required`) — a paired kitchen screen or kiosk included.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/locations/{id}/whatsapp:
    put:
      tags: [Locations]
      summary: Turn WhatsApp to guests on or off at a location (EDIT_SETTINGS, T-5.5)
      description: Every location starts OFF (D-132); a person with EDIT_SETTINGS turns it on here, and `on` must be said (a body without it is a 400, never an implied on). Off, nothing is sent from the location and nothing is charged; order-ready records `SWITCHED_OFF` and the browser buzzer still goes. Audited. Answers this month's WhatsApp, as `GET /api/v1/whatsapp`.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                on: { type: boolean }
              required: [on]
      responses:
        "200":
          description: This month's WhatsApp after the change.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WhatsAppUsageView" }
        "403":
          description: Not someone who may change settings (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/whatsapp:
    get:
      tags: [Locations]
      summary: This month's WhatsApp messages and cost, per location, with each location's switch (EDIT_SETTINGS or MANAGE_LICENCE, T-5.5)
      description: Every message Meta accepted, counted once, at the one published rate (`rateCents`), on its own line beside the plan's. The month is the calendar month in South African time.
      responses:
        "200":
          description: The month so far.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WhatsAppUsageView" }
        "403":
          description: Neither EDIT_SETTINGS nor MANAGE_LICENCE (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/locations/{id}/kiosk-slides:
    get:
      tags: [Locations]
      summary: The location's kiosk attract pictures (EDIT_SETTINGS, T-6.2)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Slides in loop order, without their bytes.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/KioskSlide" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Locations]
      summary: Add a kiosk attract picture (EDIT_SETTINGS, T-6.2)
      description: |
        Base64 PNG, JPEG or WebP, at most 10 MB; at most 10 per location; shown for 3–60 seconds
        (default 8). The type is judged by the file's own bytes, not `mime`, and a WebP is judged whole
        (trailing bytes, an unknown chunk, EXIF or a header with nothing behind it are refused). What is
        stored and served is a re-encoded picture whose long edge is at most 1920 px (a 1080 x 1920 portrait
        screen), with none of the upload's EXIF, as a PNG (when the source has transparency) or a JPEG; a WebP is
        decoded on the server and never served as it came, and must be a lossy, still, metadata-free file of at most 900 KB
        and 1920 px (a lossless WebP is refused). A refusal is 400 with `slide_refused`, `dwell_refused` or `invalid_image` and a sentence saying what
        to change (core `KioskAttract`, over `ImageBytes`); a body declared over 14 MB is 413 `image_too_large` before it
        is read.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [imageBase64, mime]
              properties:
                imageBase64: { type: string }
                mime: { type: string, enum: [image/png, image/jpeg, image/webp], description: "What the picker reported; advisory only. The stored type follows the file's bytes." }
                dwellSeconds: { type: integer, minimum: 3, maximum: 60, default: 8 }
                altText: { type: string, nullable: true }
      responses:
        "201":
          description: The slide.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/KioskSlide" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "413":
          description: The body is declared larger than any slide may be (`image_too_large`), refused before it is read.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/locations/{id}/kiosk-slides/{slideId}:
    get:
      tags: [Locations]
      summary: Kiosk attract picture bytes (Public, T-6.2)
      description: "Public (no JWT) — the kiosk draws it with no sign-in. Served with `Cache-Control: public, max-age=300`. Always the re-encoded copy Ruva stored (T-2.13). `503 picture_store_unavailable` when the picture store cannot be read."
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: slideId, in: path, required: true, schema: { type: string } }
        - $ref: "#/components/parameters/PictureSize"
      responses:
        "200":
          description: Raw image bytes in the stored mime type.
          content:
            image/png: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/webp: { schema: { type: string, format: binary } }
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Locations]
      summary: Change a kiosk picture's dwell, description or place (EDIT_SETTINGS, T-6.2)
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: slideId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: Only what is sent changes.
              properties:
                dwellSeconds: { type: integer, minimum: 3, maximum: 60 }
                altText: { type: string }
                sortOrder: { type: integer }
      responses:
        "200":
          description: The slide.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/KioskSlide" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    delete:
      tags: [Locations]
      summary: Remove a kiosk attract picture (EDIT_SETTINGS, T-6.2)
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: slideId, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Removed.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"

  /api/v1/floor/layouts/{level}:
    delete:
      tags: [Floor]
      summary: Remove a level of the floor (EDIT_SETTINGS, 1.0.7)
      description: |
        The level's walls, labels and decor go with it; no table, bill or sale is touched. Judged by core
        `LevelRemoval` under the location's row lock: refused 409 `level_holds_tables` while a live table is drawn on
        it (move it to another level or retire it first) and 409 `only_level` for the floor's only level, each with
        the sentence a person reads. A level that is not there answers 200 as done. Answers every level after it.
      parameters:
        - { name: level, in: path, required: true, schema: { type: integer, minimum: 0, maximum: 20 } }
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: Every level after the removal.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/FloorLayout" } }
        "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"
  /api/v1/room-charge/connection:
    delete:
      tags: [Accounting]
      summary: Disconnect the hotel system (MANAGE_INTEGRATIONS, 1.0.7)
      description: |
        Takes the business's PMS connection off: no charge is sent to a folio and the till stops offering a room.
        Every room charge on record stays, with what the hotel answered. Credentials are not held per business (they
        are this server's environment), so there is none to forget. Refused 409 `room_charge_unanswered` while a
        charge is PENDING or may have landed and is neither posted nor released, with how many and how to settle
        them. A second disconnect answers as the first. Answers the connection as it now reads: none.
      responses:
        "200":
          description: Disconnected (or never connected).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RoomChargeConnection" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: '`permission_required`: MANAGE_INTEGRATIONS, the owner or an admin.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/campaigns/{id}:
    delete:
      tags: ["Marketing"]
      summary: Delete a campaign that never sent (Manager, 1.0.7)
      description: |
        A draft, or a campaign cancelled before anything went out, leaves the list. A scheduled one is refused 409
        `campaign_not_deletable` (cancel it first), and so is one that sent or has a recipient on record: it stays as
        the record of what went out. Judged under the row's lock, which a send takes too. A second delete answers
        204 as the first; another business's campaign is a 404.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/reports/schedules/{id}:
    put:
      tags: ["Saved Reports"]
      summary: Edit a schedule's recipients, frequency, format and hour (EXPORT_DATA, 1.0.7)
      description: |
        The same gate and checks as making one (`invalid_cadence`, `recipients_required`, `invalid_recipient`,
        `invalid_hour`, `invalid_day_of_week`, `invalid_day_of_month`, `invalid_format`); a schedule of a labour report
        also asks VIEW_WAGES, as making and resuming one do. Its report and its owner do not change. The same body
        sent twice answers the same schedule.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [cadence]
              properties:
                cadence: { type: string, enum: [DAILY, WEEKLY, MONTHLY] }
                hourOfDay: { type: integer, minimum: 0, maximum: 23, default: 7 }
                dayOfWeek: { type: integer, minimum: 1, maximum: 7, description: "WEEKLY only; 1 is Monday." }
                dayOfMonth: { type: integer, minimum: 1, maximum: 28, description: "MONTHLY only." }
                recipients: { type: array, items: { type: string }, description: "Email addresses or WhatsApp numbers." }
                format: { type: string, enum: [CSV, HTML], default: CSV }
      responses:
        "200":
          description: The schedule as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportSchedule" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/platform/apps/{id}:
    post:
      tags: [Webhooks]
      summary: Rename, re-scope or revoke an API app (MANAGE_INTEGRATIONS)
      description: |
        `name` renames it (1.0.7): one name per business whatever its case, else 409 `app_name_taken`; a blank one is
        400 `name_required`. A rename leaves the client id, secret, scopes and live tokens alone. Any scope change, and
        `active: false`, revokes the app's live tokens; widening its scopes or switching it back on asks the second
        factor. Another business's app is a 404. Sending the same body again answers the same app.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                scopes: { type: string, description: "Space-separated scopes." }
                active: { type: boolean }
      responses:
        "200":
          description: The app as it now stands (never its secret).
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/platform/webhook-endpoints/{id}:
    post:
      tags: [Webhooks]
      summary: Move, re-subscribe, describe, disable or re-enable a webhook endpoint (MANAGE_INTEGRATIONS)
      description: |
        `url` moves it (1.0.7): the address passes the same outbound rules as a new endpoint's (`WebhookUrlPolicy`:
        https and a public host on production; refused 400 with the rule's code), another active endpoint here at that
        address is 409 `endpoint_url_exists`, and moving it asks the second factor as creating one does. Its signing
        secret and subscriptions stay; deliveries waiting to be retried go to the new address. Widening the events it
        hears or switching it back on asks the second factor too. Another business's endpoint is a 404.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                url: { type: string, format: uri }
                description: { type: string }
                eventTypes: { type: string, description: "Comma-separated event types." }
                active: { type: boolean }
      responses:
        "200":
          description: "`{\"ok\": true}`."
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/floor/layouts/pdf:
    get:
      tags: [Floor]
      summary: The floor on paper — a map page per level, every table's QR code, table tents or a sticker sheet (MANAGE_TABLES, T-7.6, T-1.18)
      description: |
        `what=map` draws each level as saved (tables at their size and turn, with seats and labels; walls, decor and
        room labels), one landscape A4 page per level. `what=qr` lays out every live table's QR code, three to a row,
        each with its name and the link it opens: `<site>/?loc=<location>&table=<label>`. `site` is
        accepted for older clients and ignored: a venue's own domain is not offered (D-226), so every code opens Ruva's own
        guest address whatever `site` says, and a print is never refused for it (choosing a base through the ordering-site
        setting is 409 `custom_domain_not_offered`).
        `what=tent` is a folded tent per live table: an A4 page holding an A5 sheet (two A6 faces, the code on both) in the
        venue's name and accent colour, with the trim and 3 mm bleed boxes set and crop marks, the fold and the bleed
        marked. `what=stickers` is the same on A4 sheets of nine stickers with cut outlines. Every code is a vector QR of
        at least 25 mm with its quiet zone, opening the same link as `what=qr`, and each print ends with a takeaway one
        (`<site>/?loc=<location>&mode=takeaway`) unless `takeaway=false`.

        **The table's code (T-39.9).** While the location's `tableCodesRequired` is on, `what=qr`, `tent` and `stickers` also
        print each table's short code beside its QR, and a table without one is given one by the print. The code is never
        in the QR's link. While it is off nothing is printed and no code is made. `what=map` never carries one.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
        - { name: what, in: query, required: true, schema: { type: string, enum: [map, qr, tent, stickers] } }
        - { name: site, in: query, required: false, description: "what=qr, tent and stickers: Ruva's guest address (a venue's own domain is 409 custom_domain_not_offered, D-226). Default Ruva's.", schema: { type: string } }
        - { name: takeaway, in: query, required: false, description: "what=tent and stickers: false leaves the takeaway tent or sticker off. Default true.", schema: { type: boolean } }
      responses:
        "200":
          description: The PDF, as an attachment.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "Nothing to print — no floor drawn (`no_floor`) or no tables (`no_tables`) — (`site` is ignored while a venue's own domain is not offered, D-226: `custom_domain_not_offered` is what choosing one answers)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/floor/table-codes/rotate:
    post:
      tags: [Floor & Tables]
      summary: Make new table codes for a location (EDIT_SETTINGS, T-39.9)
      description: |
        Replaces the short code of every live table at the location at once, so every printed tent, sticker and sheet
        stops working the moment this answers; print the new ones straight after (`GET /floor/layouts/pdf`). Nothing
        renews a code by itself. Refused `409 table_codes_off` while the location's `tableCodesRequired` is off.
        The answer carries the number of tables and the time, never a code: codes are read only on the printed sheet.
        Audited with the method, path and status like every staff write.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TableCodesRotateRequest" }
      responses:
        "200":
          description: Every table has a new code.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TableCodesRotated" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`table_codes_off` — the location does not ask for table codes."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/floor/layouts:
    get:
      tags: [Floor]
      summary: Every level of a location's floor as drawn (MANAGE_TABLES, T-7.1)
      description: |
        One layout per level, at the current version (core `FloorLayout`, `version` 2), agreeing with the live
        tables: a retired table is never drawn, and a table on no level is placed on the ground floor where its
        legacy `positionX`/`positionY` put it. A location that is not the caller's is a 404.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The levels, ground floor first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/FloorLayout" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    put:
      tags: [Floor]
      summary: Save one level whole (EDIT_SETTINGS, T-7.1)
      description: |
        Refused 400 `floor_layout_refused` with the reason when the layout breaks a rule (core `FloorLayouts.refusal`:
        sizes, rotation 0–359, seats numbered from 1, each element once), and 400 `unknown_table` when it names a
        table that is not live at this location. A table it holds leaves any other level. Each table's position
        and shape are mirrored onto its `tables` row for the readers that have not moved to layouts. Answers every level.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/FloorLayout" }
      responses:
        "200":
          description: Every level after the save.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/FloorLayout" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/upsell-rules:
    get:
      tags: [Promotions]
      summary: The venue's checkout suggestions (MANAGE_PROMOTIONS, T-6.3)
      responses:
        "200":
          description: Rules in the venue's order.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/UpsellRule" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Promotions]
      summary: Add a checkout suggestion (MANAGE_PROMOTIONS, T-6.3)
      description: |
        Exactly one trigger (a dish or a category), a dish to suggest that is not the trigger, and an
        optional line of at most 80 characters. Refused 400 `upsell_refused` with the reason (core `Upsell.refusal`).
        Which suggestions a guest sees (up to three at checkout, and an "add a drink?" after a main) are chosen on the device by core `Upsell`, never here.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/UpsellRule" }
      responses:
        "201":
          description: The rule.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UpsellRule" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/upsell-rules/{id}:
    post:
      tags: [Promotions]
      summary: Replace a checkout suggestion (MANAGE_PROMOTIONS, T-6.3)
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/UpsellRule" }
      responses:
        "200":
          description: The rule.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UpsellRule" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    delete:
      tags: [Promotions]
      summary: Remove a checkout suggestion (MANAGE_PROMOTIONS, T-6.3)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "204":
          description: Removed.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/reports/upsell:
    get:
      tags: [Reports]
      summary: How often each checkout suggestion was offered and taken (VIEW_REPORTS, T-6.3)
      description: |
        One row per rule, including rules never offered. An offer is recorded once per guest order that
        was shown the suggestion, however many suggestions that order was shown and however many ways it saw this one; taken means that order holds the suggested dish, judged by the server.
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Rates per rule.
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    ruleId: { type: string }
                    suggestProductId: { type: string }
                    offered: { type: integer }
                    accepted: { type: integer }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kiosk/funnel:
    post:
      tags: [Customer QR]
      summary: A kiosk's counts of where its guests got to (T-39.15)
      description: |
        Counts only: for each venue day and step, how many guests reached it. No guest, basket, amount or free text is sent or
        kept, and one row is a sum, never a session. Steps are `STARTED`, `BASKET_OPENED`, `REVIEWED`, `PLACED`, `LEFT_BROWSING`,
        `LEFT_BASKET` and `LEFT_REVIEW`; there is no paid step, because paid is read from the business's own kiosk sales. The
        kiosk is the device the token belongs to, never a field of the body. Send as a screen paired as a kiosk (it counts at its
        registration's location in Devices whatever `locationId` says; one with no location is `403 kiosk_has_no_location`), or as a person who may sell at a till on a device not set to anything
        but the kiosk (`403 not_a_kiosk` otherwise). `batchId` is chosen by the kiosk and kept until the server answers, so a batch
        sent twice counts once. A batch holds at most 120 counts; one day and step comes to 1 to 10 000 in a batch, however many
        entries carry it; a day's stored count at one step stops at 10 000. A day is today or one of the 14 before it, by the venue's
        clock (with 15 minutes' allowance for a kiosk's clock at midnight); a later day is refused.
      x-rate-limit: "kioskFunnel: 6/min"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [batchId, locationId, counts]
              properties:
                batchId: { type: string, description: "8 to 64 letters, digits, dashes or underscores." }
                locationId: { type: string }
                counts:
                  type: array
                  maxItems: 120
                  items:
                    type: object
                    required: [day, step, count]
                    properties:
                      day: { type: string, format: date, description: "The venue day, yyyy-MM-dd, South African time." }
                      step: { type: string, enum: [STARTED, BASKET_OPENED, REVIEWED, PLACED, LEFT_BROWSING, LEFT_BASKET, LEFT_REVIEW] }
                      count: { type: integer, minimum: 1, maximum: 10000 }
      responses:
        "204": { description: Added, or already added (a repeat of a batch counts once). }
        "400": { description: "A batch id, day, step or count that is not allowed, or a location the business does not have." }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403": { description: "Not a kiosk (`not_a_kiosk`), or a paired kiosk with no location set in Devices (`kiosk_has_no_location`)." }
        "409": { description: "This device is not registered; sign the kiosk in again." }
        "429": { description: "More than the `kioskFunnel` bucket allows from this device in a minute; see `Retry-After`." }
  /api/v1/kiosk/loyalty:
    post:
      tags: [Customer QR]
      summary: A new guest's mobile number typed at a kiosk, so the order starts their points (T-39.14)
      description: |
        Earn-only. Sent by a kiosk for the order it has just placed, opened with that order's key in `X-Ruva-Order-Key`. A number no
        customer of the venue holds makes that guest's own record ("Kiosk guest", with no marketing consent and no other detail) and the
        order is linked to it, so the venue's loyalty rules give it the points when the order is paid. A number a customer already holds
        links nothing and changes nothing of theirs: a number is no proof of who is typing it, so existing members earn and redeem at a
        till until a proof step exists. Nothing is redeemed here.
        **The answer says nothing about the number.** It is `204` whether the number belongs to a member or to nobody, so the door
        cannot be used to find out who is a customer, and no name, balance or history is returned. The refusals are about the request
        (a number that is not a mobile number, an order that is not this kiosk's or is closed, a venue with the step off) and never
        about the person. Both budgets are spent before the body is read (the business's only once the caller is known to be a kiosk), so
        a list of numbers is stopped at the eleventh try from one kiosk, or the thirty-first from one business. Send as a screen paired as a kiosk, or as a person who may sell at a till on a
        device not set to anything but the kiosk (`403 not_a_kiosk` otherwise). The venue turns the step on per location in Settings
        (`kioskLoyalty`, off by default); `GET /qr/menu` carries it as `kioskLoyalty`.
      x-rate-limit: "kioskLoyalty: 10/min"
      parameters:
        - { name: X-Ruva-Order-Key, in: header, required: true, schema: { type: string }, description: "The key the kiosk was given when it placed the order." }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [orderId, phone]
              properties:
                orderId: { type: string }
                phone: { type: string, description: "A South African mobile number as typed; read as E.164." }
      responses:
        "204": { description: "Accepted. Says nothing of whether the number was already held." }
        "400": { description: "The number is not a mobile number (`invalid_phone`)." }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403": { description: "Not a kiosk (`not_a_kiosk`), or the caller's role may not (`permission_denied`)." }
        "404": { description: "No such order for this kiosk's venue and key (`order_not_found`)." }
        "409": { description: "The venue has not turned the step on (`kiosk_loyalty_off`), the order is no longer open (`order_closed`), or this device is not registered." }
        "429": { description: "More than the `kioskLoyalty` or `kioskLoyaltyBusiness` bucket allows in a minute; see `Retry-After`." }
  /api/v1/kiosk/orders:
    post:
      tags: [Customer QR]
      summary: A paired kiosk places a guest's order, which carries no per-order fee (T-35.14)
      description: |
        The same order as `POST /api/v1/qr/orders` — same body, same answer, same re-pricing, slots, kitchen hours, limits and
        replay by `clientOrderId` (a retry sends the order's own key in `X-Ruva-Order-Key`, as there) — placed through the signed-in
        door so the server can PROVE who sent it. A kiosk order carries no per-order fee only when it comes from here (or from a
        paired kiosk's own queued replay): the server writes the kiosk's registration on the order from the session and from nothing
        the request says, and a `channel` or `kioskDeviceId` in the body proves nothing. The public `POST /qr/orders` names the KIOSK
        channel too, but from 1 February 2027 an order placed there counts as a QR order whatever it says.
        Send as a screen paired as a kiosk, at its own location: anything else is `403 not_a_kiosk` (a kitchen screen, a person, a
        person's till set to the kiosk) or `403 kiosk_at_another_location`. The order's channel is always KIOSK. There is no
        fallback: a `401`, `429` or `5xx` places nothing, and the kiosk tries this door again.
      x-rate-limit: "kioskOrder: 60/min"
      parameters:
        - { name: X-Ruva-Order-Key, in: header, required: false, schema: { type: string }, description: "The key the kiosk minted for this order; sent on the first attempt and every retry, as at `POST /qr/orders`." }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QrOrderRequest" }
      responses:
        "201":
          description: The order, as at `POST /qr/orders`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrOrderResponse" }
        "400": { description: "Refused as at `POST /qr/orders`, or a tab asked for (`kiosk_takes_no_tab`: `ADD_TO_TAB` or a `tabOrderId`) — a kiosk order is paid now or at the counter." }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403": { description: "Not a paired kiosk (`not_a_kiosk`), or the order names another location than this kiosk's (`kiosk_at_another_location`)." }
        "409": { description: "Refused as at `POST /qr/orders` (`ordering_paused`, `kitchen_closed`, `slot_full`, `id_conflict`…)." }
        "429": { description: "More than the `kioskOrder` bucket allows from this session in a minute; see `Retry-After`." }
  /api/v1/reports/kiosk-funnel:
    get:
      tags: [Reports]
      summary: Whether the kiosk earns its price (VIEW_REPORTS, T-39.15)
      description: |
        Per kiosk and in total: guests who started an order, put something in the basket, reached the review and placed an
        order, and how many left at each step. Counts are the kiosks' own, by venue day, so the window is widened to the whole
        venue days it touches (`periodStart`/`periodEnd` say which). `paidOrders` and `paidSalesCents` are the business's own sales
        on the kiosk channel over the same days (refunds taken off), so they are one figure for all kiosks together, the browser
        kiosk's orders included although it counts no steps.
        Every figure is worked out on the server, with the share each step kept of the one before in basis points.
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: The funnel.
          content:
            application/json:
              schema:
                type: object
                properties:
                  periodStart: { type: integer, format: int64 }
                  periodEnd: { type: integer, format: int64 }
                  kiosks:
                    type: array
                    items: { $ref: "#/components/schemas/KioskFunnelKiosk" }
                  total: { $ref: "#/components/schemas/KioskFunnelKiosk" }
                  paidOrders: { type: integer }
                  paidSalesCents: { type: integer, format: int64 }
                  paidPerStartBp: { type: integer, format: int64, nullable: true }
                  stages:
                    type: array
                    items:
                      type: object
                      properties:
                        key: { type: string }
                        label: { type: string }
                        count: { type: integer, format: int64 }
                        keptBp: { type: integer, format: int64, nullable: true }
                        lost: { type: integer, format: int64 }
                  definition: { type: string }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  # ───────────────────────────── Floor & Tables ─────────────────────────────
  /api/v1/tables:
    get:
      tags: [Floor & Tables]
      summary: List floor tables
      parameters:
        - name: includeRetired
          in: query
          description: When `true`, includes soft-deleted (retired) tables.
          schema: { type: boolean, default: false }
      responses:
        "200":
          description: Tables for the tenant.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/TableDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Floor & Tables]
      summary: Upsert a floor table (Manager-gated)
      description: Updates only touch layout fields (label/seats/position/shape) — live seating state (status/guestCount/currentOrderId) is never clobbered.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TableUpsertRequest" }
      responses:
        "200":
          description: Updated existing table.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "201":
          description: Created new table.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/tables/{id}/retire:
    post:
      tags: [Floor & Tables]
      summary: Soft-delete (retire) a table (Manager-gated)
      description: Vanishes from the POS floor but stays referenced by historical transactions. Refuses while occupied.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Table retired.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, retired: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Table has an open order (`error:"table_has_open_order"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/tables/{id}/seat:
    post:
      tags: [Floor & Tables]
      summary: Seat a party at a table
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TableSeatRequest" }
      responses:
        "200":
          description: Table marked OCCUPIED.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/tables/{id}/clear:
    post:
      tags: [Floor & Tables]
      summary: Clear a table back to AVAILABLE
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Table cleared.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/tables/occupancy:
    get:
      tags: [Floor & Tables]
      summary: The tables in use at a venue with no till, each with its seating
      description: >-
        T-39.28 (D-187). At a venue with no till a guest's first order marks the table in use; it frees itself once every order
        on it is paid and served (or voided), or after the location's `tableIdleMinutes` with nobody ordering or paying. Each
        entry is a table in use: since when, the orders on its seating oldest first (each paid, served, voided), when anybody last
        ordered or paid, and the idle time it frees itself after. Empty at a venue with a till, whose floor is its till's.
        MANAGE_TABLES or EDIT_SETTINGS.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The tables in use.
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    tableId: { type: string }
                    since: { type: integer, format: int64 }
                    lastActivityAt: { type: integer, format: int64 }
                    idleMinutes: { type: integer }
                    orders:
                      type: array
                      items:
                        type: object
                        properties:
                          id: { type: string }
                          number: { type: string }
                          paid: { type: boolean }
                          served: { type: boolean }
                          voided: { type: boolean }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/tables/{id}/free:
    post:
      tags: [Floor & Tables]
      summary: Free a table at a venue with no till by hand
      description: >-
        T-39.28. Marks the table free; the next guest who scans its code starts a new order. Its orders are not touched: an
        unpaid one stays open in Orders, where its payment is still taken. Freeing a table already free answers the same.
        A venue with a till is refused `409 table_cleared_on_till`: its till clears its tables (`/tables/{id}/clear`). MANAGE_TABLES.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Table free.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/tables/{id}/transfer:
    post:
      tags: [Floor & Tables]
      summary: Move the open order from this table to another table
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TableTransferRequest" }
      responses:
        "200":
          description: Order moved. `moved` lists the bookings to come whose hold on the destination was moved around the party, each with the tables it holds now (none when no table was free).
          content:
            application/json:
              schema:
                type: object
                properties:
                  from: { type: string }
                  to: { type: string }
                  orderId: { type: string }
                  moved:
                    type: array
                    items: { type: object, properties: { id: { type: string }, guestName: { type: string }, tableIds: { type: array, items: { type: string } } } }
        "409":
          description: "`destination_not_available`; `different_location` (the table is at another location); `table_changed` (the table's bill changed meanwhile); `table_in_a_join` (one table of a seated join with no bill — open the party's bill and move it, or clear the join's other table first)."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/tables/{id}/merge:
    post:
      tags: [Floor & Tables]
      summary: Join this table to another table's party, onto one bill
      description: >
        The table is held (OCCUPIED, pointing at the party's bill), never freed while people sit at it. If it had
        its own bill, its lines, kitchen tickets, discount and tip move onto the party's bill once and its own bill
        is closed as merged; the party's size is both bills' together. Joining a table that is already at that bill
        changes nothing. Needs MANAGE_TABLES.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TableMergeRequest" }
      responses:
        "200":
          description: Joined. `into` is the table that holds the bill.
          content:
            application/json:
              schema:
                type: object
                properties: { merged: { type: string }, into: { type: string }, orderId: { type: string } }
        "400":
          description: The other table has no open bill (`into_has_no_bill`), or it is the same table (`same_table`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Either table is not this business's (`table_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: >
            The table is already joined to another party (`already_joined`), holds more than one bill
            (`several_bills`), or is reserved or being cleaned (`table_not_free`); or both bills carry a voucher
            (`vouchers_on_both`), are for different loyalty guests (`different_guests`) or each redeemed points
            (`points_on_both`) — one bill holds one of each; or guests have paid part of the table's bill on their
            phones (`bill_has_payments`), are paying it now (`payment_in_progress`), started a payment on it more than
            15 minutes ago that never finished (`payment_unfinished`) or a room charge stands on it (`room_charge_held`),
            which joining would leave on a voided bill (T-41.29); or the main table's bill was settled while the join
            waited (`into_bill_closed`: nothing moved). Both bills are locked first. The message names the remedy.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/tables/{id}/separate:
    post:
      tags: [Floor & Tables]
      summary: Separate a joined table from its party
      description: >
        The table is freed and the bill stays with the party on the table that holds it. Separating a table
        that is not joined changes nothing. Needs MANAGE_TABLES.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Separated (or was not joined).
          content:
            application/json:
              schema:
                type: object
                properties: { id: { type: string }, status: { type: string } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Not this business's table (`table_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: This table holds the party's bill (`main_table`) — separate the other tables instead.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/zones:
    get:
      tags: [Floor & Tables]
      summary: List floor zones
      responses:
        "200":
          description: Zones, ordered by `sortOrder`.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ZoneDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Floor & Tables]
      summary: Upsert a floor zone (Manager-gated)
      description: |
        The name is stored trimmed and held to the back office's rule (core `TableZones.nameRefusal`): not blank and at most 30
        characters (`400 invalid_zone_name`), and no other zone at the location by the same name, case aside (`409
        zone_name_taken`) — on a new zone and a rename alike.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ZoneUpsertRequest" }
      responses:
        "200":
          description: Updated existing zone.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "201":
          description: Created new zone.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/zones/{id}/price-list:
    post:
      tags: [Floor & Tables]
      summary: Set or clear a zone's price level (Manager-gated, T-3.4)
      description: Lines rung at the zone's tables are priced from this list; null clears it, so the location's list applies. A customer-group list, or one set for another branch, is refused.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, properties: { priceListId: { type: string, nullable: true } } }
      responses:
        "204":
          description: Set.
        "400":
          description: '`price_list_not_found`, `price_list_is_for_a_group`, `price_list_other_location`.'
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: '`zone_not_found`.'
  /api/v1/reservations:
    get:
      tags: [Floor & Tables]
      summary: List reservations in a time window
      description: Excludes WAITLISTED (walk-in queue) and removed (CANCELLED/NOSHOW) entries.
      parameters:
        - name: from
          in: query
          description: Epoch millis, inclusive. Defaults to `0`.
          schema: { type: integer, format: int64 }
        - name: until
          in: query
          description: Epoch millis, exclusive. Defaults to unbounded.
          schema: { type: integer, format: int64 }
        - name: locationId
          in: query
          description: Optional server-side location filter.
          schema: { type: string }
      responses:
        "200":
          description: Reservations, soonest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReservationDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Floor & Tables]
      summary: Create or edit a reservation (upsert by id)
      description: |
        Posting an existing `id` edits the reservation. Validates `partySize >= 1`, a known
        `status` (PENDING | CONFIRMED | SEATED | NOSHOW | CANCELLED), and that `tableId`
        belongs to the tenant. Rejects (`409 reservation_conflict`) a reservation whose
        `[reservedForAt, reservedForAt + durationMinutes)` window overlaps another active
        reservation for the same table.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReservationUpsertRequest" }
      responses:
        "201":
          description: Reservation created (200 when an existing id was edited).
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: Table already reserved in that window (`error:"reservation_conflict"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/guest-tags:
    get:
      tags: [Floor & Tables]
      summary: The venue's own list of guest tags
      description: Needs VIEW_CUSTOMERS or MANAGE_RESERVATIONS. A business that has none starts with Regular, VIP and Allergy.
      responses:
        "200":
          description: The list.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/GuestTag" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Floor & Tables]
      summary: Add a tag to the venue's list
      description: Needs EDIT_CUSTOMERS. A label is one line of at most 24 characters, unique ignoring case; the list holds at most 30 (`409 tag_exists`, `409 too_many_tags`).
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, properties: { label: { type: string }, kitchen: { type: boolean } }, required: [label] }
      responses:
        "201":
          description: The tag.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestTag" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: Already on the list, or the list is full.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/guest-tags/{id}:
    delete:
      tags: [Floor & Tables]
      summary: Remove a tag from the list and from every guest wearing it
      description: Needs EDIT_CUSTOMERS.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Removed.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/reservations/why:
    get:
      tags: [Floor & Tables]
      summary: Why guests cannot book a date and time (T-27.11)
      description: |
        Needs MANAGE_RESERVATIONS. Asks the availability engine — the same check the booking door makes — for one date, time and party
        size, and says whether guests can book it. When they cannot, `reason` is one of a closed set: `PACING` (the slot's pacing
        limit is reached), `COVERS` (the covers cap is reached), `NO_TABLE` (no table or allowed join seats the party for its whole
        stay), `BLACKOUT` (a closed date), `OUTSIDE_SERVICE` (outside every availability schedule for the weekday) or `TOO_LATE`
        (the time has started or passed — there is no minimum-notice setting). `words` says it, `setting` names what would change it,
        and `nearest` holds the nearest slots guests can book either side, read from the day the guest reads. A guest is never
        told the reason: the public availability answer says only `FULL` for every full time.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
        - { name: date, in: query, required: true, description: "yyyy-MM-dd (Africa/Johannesburg).", schema: { type: string } }
        - { name: time, in: query, required: true, description: "HH:mm (Africa/Johannesburg).", schema: { type: string } }
        - { name: partySize, in: query, required: true, description: "1..20.", schema: { type: integer } }
      responses:
        "200":
          description: The engine's answer.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingWhyAnswer" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/reservations/{id}/guest:
    put:
      tags: [Floor & Tables]
      summary: Set the tags and note kept on a booking's guest
      description: |
        Needs MANAGE_RESERVATIONS and VIEW_CUSTOMERS. `tags` replaces the guest's tags and each must be on the venue's list
        (`400 unknown_tag`); `note` is kept when absent and cleared when blank. The guest is the one customer holding the booking's
        phone, or, failing that, its email where the customer proved it and no phone contradicts it; made from the booking when there
        is none. Writing `note` also needs WRITE_GUEST_NOTES (held by hosts, servers and management) and is audited as
        `guest.note` with who wrote it and which guest, never the words; making the guest's record also needs EDIT_CUSTOMERS
        (each `403 permission_required`, nothing written): a host or server tags a guest already on the list and writes their note. A booking with no phone or email is `409 guest_unreachable`, and a
        number or address shared by two guests `409 guest_ambiguous`: nothing is written on a guess.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, properties: { tags: { type: array, items: { type: string } }, note: { type: string, nullable: true } } }
      responses:
        "200":
          description: The guest as now kept.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingGuest" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: No contact on the booking, or two guests share it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/reservations/{id}/seat:
    post:
      tags: [Floor & Tables]
      summary: Mark a reservation SEATED
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Reservation seated, at the table named, else the first free table of its allotment. `moved` lists the bookings to come that the seat moved off its tables, each with the tables it holds now (none when no table was free); `notTaken` the tables of its allotted join someone else was at, which it no longer holds.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  status: { type: string }
                  tableId: { type: string }
                  moved:
                    type: array
                    items: { type: object, properties: { id: { type: string }, guestName: { type: string }, tableIds: { type: array, items: { type: string } } } }
                  notTaken: { type: array, items: { type: string } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/reservations/{id}/cancel:
    post:
      tags: [Floor & Tables]
      summary: Cancel a reservation
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Reservation cancelled.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/reservations/{id}/no-show:
    post:
      tags: [Floor & Tables]
      summary: Mark a reservation NOSHOW
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Reservation marked no-show.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"

  # ───────────────────────────── Waitlist ─────────────────────────────
  /api/v1/floor/turn-times:
    get:
      tags: [Floor & Tables]
      summary: Usual turn time per party size, from this venue's own history
      description: >
        The median minutes a table stays seated, per party band (1-2, 3-4, 5-6, 7+), over the last
        60 days of closed dine-in checks at the location. Checks shorter than 10 minutes or longer
        than 6 hours are left out. A band with fewer than five turns borrows the venue's median over
        every size; a venue with fewer than five turns overall answers starting guesses, and
        `source` says which. Requires MANAGE_TABLES.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: One turn time per party band.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TurnTimes" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/floor/sections:
    get:
      tags: [Floor & Tables]
      summary: Server sections at a location, with their tables and staff
      description: Requires MANAGE_TABLES. A table belongs to at most one section.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: Sections in display order.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/FloorSection" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Floor & Tables]
      summary: Create a server section, or rename one and replace its tables
      description: >
        Manager roles only. Omit `id` to create. A table named here moves out of whichever section
        held it. Refused with `unknown_table` for a table not at the location, and with
        `section_name_taken` for a name another section already uses.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/FloorSectionUpsert" }
      responses:
        "200":
          description: The section as saved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/FloorSection" }
        "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"
  /api/v1/floor/sections/{id}:
    delete:
      tags: [Floor & Tables]
      summary: Remove a server section
      description: Manager roles only. Its tables, and any checks on them, are untouched.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "204":
          description: Removed.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/floor/sections/{id}/staff:
    post:
      tags: [Floor & Tables]
      summary: Set who is working a server section, replacing the list
      description: Manager roles only.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SectionStaffRequest" }
      responses:
        "200":
          description: The section with its new staff.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/FloorSection" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/waitlist:
    get:
      tags: [Waitlist]
      summary: Get the current walk-in queue for a location
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: |
            Waiting parties in queue order — bumped (VIP) parties first, then by arrival — each with its `position`,
            `waitedMinutes` and quote. The quote plays the floor forward on the venue's turn times (`quoteBasis: TABLES`);
            `quotedWaitMinutes` is null with `NO_TABLE` when no table seats the party, and `PER_PARTY` is the
            15-minutes-a-party fallback.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/WaitlistEntryDto" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Waitlist]
      summary: Add a walk-in party to the back of the queue
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WaitlistAddRequest" }
      responses:
        "201":
          description: Party added to the waitlist.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WaitlistEntryDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/waitlist/{id}/seat:
    post:
      tags: [Waitlist]
      summary: Seat a waiting party at a table
      description: Marks the waitlist entry SEATED and seats the table through the same logic as `POST /tables/{id}/seat`.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WaitlistSeatRequest" }
      responses:
        "200":
          description: Party seated.
          content:
            application/json:
              schema:
                type: object
                properties: { id: { type: string }, status: { type: string }, tableId: { type: string } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Entry is no longer waiting (`error:"not_waitlisted"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/waitlist/{id}/remove:
    post:
      tags: [Waitlist]
      summary: Remove a waiting party (cancelled or no-show)
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WaitlistRemoveRequest" }
      responses:
        "200":
          description: Entry updated.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/waitlist/{id}/vip:
    post:
      tags: [Waitlist]
      summary: Bump a waiting party ahead of everyone not bumped, or take the bump off
      description: Needs `MANAGE_RESERVATIONS`. Among bumped parties, arrival order still holds.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WaitlistVipRequest" }
      responses:
        "200":
          description: Bump set.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, vip: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/waitlist/{id}/ready:
    post:
      tags: [Waitlist]
      summary: Tell a waiting party its table is ready
      description: |
        Needs `MANAGE_RESERVATIONS`. Stamps `readyAt` and sends the guest the `table_ready` WhatsApp template when a
        phone is on the entry and WhatsApp is configured; `message` says which (`SENT`, `FAILED`, `NO_PHONE`,
        `NOT_CONFIGURED`) so the host knows whether to call the name out. A party not seated within 10 minutes of
        `readyAt` is dropped as `NOSHOW` by the server's sweep.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Marked ready.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WaitlistReadyResult" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/waitlist/join:
    post:
      tags: [Waitlist]
      summary: A guest joins the walk-in waitlist from the QR code at the host stand
      description: |
        Public — no JWT required, `booking` rate limit, behind the same online-booking switch as the booking widget.
        The phone is required (it is how the guest is told the table is ready) and normalised to E.164. A second join
        from the same phone at the same location while still waiting answers the first place. The answer's `id` is a
        random token and the guest's only way to read their status.
      x-rate-limit: "booking: 60/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WaitlistJoinRequest" }
      responses:
        "201":
          description: In the queue.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WaitlistJoinStatus" }
        "400":
          description: "`guest_name_required`, `guest_name_too_long`, `invalid_party_size` (1–20), `invalid_phone`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: The venue is not taking waitlist sign-ups online (`waitlist_not_available`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/waitlist/join/{id}:
    get:
      tags: [Waitlist]
      summary: The guest's own place in the waitlist
      description: |
        Public — no JWT required, `booking` rate limit. Only an entry the guest joined themselves, at `loc`; a
        host-added entry or another location is 404. Carries the place, the quote and the state — never a name or
        phone of anyone else.
      x-rate-limit: "booking: 60/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: loc, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The guest's status.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WaitlistJoinStatus" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: The venue is not taking waitlist sign-ups online (`waitlist_not_available`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"

  # ───────────────────────────── Orders ─────────────────────────────
  /api/v1/orders:
    get:
      tags: [Orders]
      summary: List recent orders
      parameters:
        - name: from
          in: query
          description: Epoch millis; only orders opened at/after this time. Defaults to `0`. Result capped at 200 rows, newest first.
          schema: { type: integer, format: int64 }
      responses:
        "200":
          description: Orders.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/OrderDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Orders]
      summary: Create a new open order
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OrderCreateRequest" }
      responses:
        "201":
          description: Order created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, number: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/orders/{id}:
    get:
      tags: [Orders]
      summary: Get an order by id
      description: |
        Needs TILL_SELL or MANAGE_TABLES; tenant-scoped. A table's open bill answers its `shareCode` (T-2.79), which the
        till shows and prints so guests at the table can pay a share by phone, whoever opened the bill.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/orders/{id}/pay-link:
    get:
      tags: [Orders]
      summary: The address the QR on a printed bill opens
      description: |
        Needs TILL_SELL or MANAGE_TABLES; tenant-scoped. The guest pay page of this table bill (T-37.2): the ordering page
        naming the venue, the table and the bill, with the bill's share code in the address's fragment, so one scan opens
        the bill and the guest pays what is left on the hosted checkout, the tip chosen on their phone. `payUrl` is null when
        no QR should be printed: no online payment set up for the business, QR Ordering off, the bill not open, not a
        table's to share, its code withheld (made under an earlier server key), to be paid at the counter or charged to a
        hotel room. A bill carrying the location's automatic service charge has its link: the phone pays the service
        charge too (T-39.17). A bill whose service charge was waived keeps its link too: the bill holds the waiver, so the
        phone owes the bill without the charge. The guest's side is the
        `/qr/bills/{orderId}` routes under the `qr` bucket.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The pay address, or null.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BillPayLinkResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/orders/{id}/lines:
    get:
      tags: [Orders]
      summary: Get every line on an order, plus its money header
      description: |
        Lets a second terminal see items another device fired onto the same open order (the POS ticket view is
        otherwise device-local). Needs TILL_SELL or MANAGE_TABLES; tenant-scoped like every other order read.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Order lines + header totals.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderLinesResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Orders]
      summary: Add a line item to an open order
      description: |
        The client's `unitPriceCents` is never trusted for pricing — the server re-prices from the product's
        base price plus any active price rule (happy hour, etc.); the client value is only a fallback for a
        product the catalogue holds at nothing. A product that is not this business's is refused
        (`unknown_product`), a `quantity` below 1 is refused (`invalid_quantity`) and so is a line that would
        cost less than nothing (`line_price_negative`). The line's VAT is 15/115 of it for `STANDARD` vatType, to the nearest cent, until the bill closes; checkout then shares the bill's exact VAT across its lines.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OrderLineRequest" }
      responses:
        "201":
          description: Line added.
          content:
            application/json:
              schema: { type: object, properties: { lineId: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Order is not OPEN (`error:"order_not_open"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/orders/{id}/checkout:
    post:
      tags: [Orders]
      summary: Checkout an order — record payments, post the sales journal, print/send the receipt
      description: |
        Runs the full settlement pipeline: payment + tip rows, stock decrement, loyalty accrual, POS-transaction
        roll-up to `PAID`, and the Ledgr sales journal, all in one transaction. Underpaid checkouts (payments +
        tips short of the order total) return `400`. Idempotency is per payment leg via `PaymentLeg.idempotencyKey`
        upstream at `/payments/*`; this endpoint itself is not separately idempotency-keyed. A paid order answers
        `409 order_already_paid`, except the same checkout sent again after its answer was lost: when every
        card-terminal approval in it (`CARD_TERMINAL`/`TAP_TO_PAY` `providerReference`) and every other leg is
        already recorded on that bill, it is answered `200` with the original result and records nothing more.
        A `GIFT_CARD` leg pays no tip (`400 gift_card_tip_refused`) and must name its card (`400 gift_card_required`), and the legs on one gift card (its id as `providerReference`),
        with any captured on the bill before, may not ask more than `POST /gift-cards/redeem` drew from that card for this order
        (`transactionId` = the order's id): `409 gift_card_not_drawn`, with the sentence to show. A card issued before gift cards
        were booked as a liability is not held to it.
        A sale closes at paid == total. Legs beyond the bill: cash's excess is its change (`beyondTheBillAsChangeCents`); a card a
        terminal already approved (`CARD_TERMINAL`/`TAP_TO_PAY` with its `providerReference`) is recorded and its excess kept apart
        as money taken twice, listed under the bill for a refund and flagged (`keptApartCents`); any other tender beyond the bill is
        refused `409 paid_beyond_bill` with what to take, nothing written. A leg's `tipCents` is the bill's tip even when the
        request's `tipCents` names none. A lay-by's, special order's or repair's bill is not paid here: `409
        commitment_sale_has_its_own_door`, with the sentence naming its door (the lay-by's last instalment, the special order's
        collect, the repair's handover), nothing written.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CheckoutRequest" }
      responses:
        "200":
          description: Order settled.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CheckoutResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/orders/{id}/layby:
    post:
      tags: [Orders]
      summary: Convert an OPEN order into a layby (V18)
      description: |
        Requires a customer (from the body or already attached) and a non-zero
        total. The optional deposit leg captures immediately and counts towards the taking register's X/Z
        (payments.shift_id). Errors: 400 customer_required / layby_needs_items / invalid_amount /
        overpays_balance, 409 already_layby / order_not_open, and 409 commitment_sale_has_its_own_door for a special order's or a repair's sale (T-21.6 review 4). 400 invalid_method for any method but CASH, CARD, EFT, YOCO_CARD, CARD_TERMINAL or TAP_TO_PAY, before the order is marked or a leg is written (T-21.14).
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LaybyOpenRequest" }
      responses:
        "200":
          description: Layby state after opening (+ deposit when given).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LaybyPaymentResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/orders/{id}/layby-payment:
    post:
      tags: [Orders]
      summary: Take a layby instalment (V18)
      description: |
        The leg captures immediately (CAPTURED, drawer-accurate via payments.shift_id). When the
        cumulative paid covers the total, the sale settles automatically through the normal checkout
        pipeline (stock, loyalty, journal) and `settled` comes back true. 400 overpays_balance guards
        against over-collection; 409 not_a_layby / order_not_open. 400 invalid_method for any method but CASH, CARD, EFT, YOCO_CARD, CARD_TERMINAL or TAP_TO_PAY, before the order is marked or a leg is written (T-21.14).
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LaybyPaymentRequest" }
      responses:
        "200":
          description: Layby state after the instalment.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LaybyPaymentResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
  /api/v1/orders/{id}/layby/collect:
    post:
      tags: [Orders]
      summary: Hand a lay-by's goods over (T-4.4)
      description: Only a lay-by paid in full and closed, and only once; records who handed the goods over and when. Needs TILL_SELL.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LaybyCollectRequest" }
      responses:
        "200":
          description: Handed over.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LaybyCollectResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`layby_balance_due` (the message names what is owed), `already_collected`, `layby_cancelled`, `layby_not_settled` or `not_a_layby`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/orders/{id}/layby/cancel:
    post:
      tags: [Orders]
      summary: Cancel an unfinished lay-by (T-4.4)
      description: |
        Keeps the location's cancellation fee — a share of the full price, at most 1% (Consumer Protection Act,
        Regulation 34), never more than was paid — and refunds the rest as CASH (a paid-out from the canceller's open
        register at this location) or STORE_CREDIT, then voids the order. Fee plus refund equals what was paid. Needs REFUND.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LaybyCancelRequest" }
      responses:
        "200":
          description: Cancelled; the fee kept and the refund given.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LaybyCancelResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`no_open_drawer` (refund as store credit, or clock in to a register), `layby_closed` (paid in full: return it instead), `already_cancelled`, `customer_required` or `not_a_layby`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/orders/{id}/fire-course:
    post:
      tags: [Orders]
      summary: Fire a course (or all courses) to the kitchen
      description: One call → at most one ticket per (course × station). Re-firing the same course creates a new ticket (a separate round).
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/FireRequest" }
      responses:
        "201":
          description: Tickets created (or an empty list if nothing matched the course filter).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/FireResult" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/orders/{id}/lines/{lineId}/move:
    post:
      tags: [Orders]
      summary: Move a line to another seat or course, before or after it was sent
      description: |
        Needs the "Ring up sales" permission. An unsent line just changes. A sent line's kitchen ticket
        changes in place: a seat change rewrites the item on its ticket; a course change moves it onto
        that course's live ticket for the same station, else relabels a ticket it is alone on, else
        opens a ticket for the course carrying the original fire time. The plate is on exactly one
        ticket after every move, and moving a line where it already is changes nothing.
      parameters:
        - $ref: "#/components/parameters/PathId"
        - name: lineId
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LineMoveRequest" }
      responses:
        "200":
          description: Where the line is now, and the kitchen ticket that holds it (null if unsent).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LineMoveResult" }
        "400":
          description: "`nothing_to_move`, `invalid_course` or `invalid_seat`."
        "404":
          description: "`order_not_found` or `line_not_found`."
        "409":
          description: "`order_not_open` or `line_voided`."
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/orders/{id}/split:
    post:
      tags: [Orders]
      summary: Split the bill across guests
      description: "Split methods: `EVEN`, `BY_ITEM`, `BY_SEAT`, `CUSTOM`."
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SplitRequest" }
      responses:
        "201":
          description: Split computed and recorded.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SplitResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Order already paid (`error:"order_already_paid"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/orders/{id}/customer:
    post:
      tags: [Orders]
      summary: Attach a customer to an OPEN order
      description: |
        Sets `customerId` on an already-open order — e.g. loyalty sign-up after the first course has fired.
        The order must still be `OPEN` and the customer must belong to the caller's tenant.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OrderCustomerAttachRequest" }
      responses:
        "204":
          description: Customer attached.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Order or customer not found (`error:"order_not_found"` or `"customer_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Order is not OPEN (`error:"order_not_open"`), or points were redeemed on it for another guest (`different_guests`; reverse them first).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/orders/{id}/service-charge:
    post:
      tags: [Orders]
      summary: Set a bill's party size and its service-charge waiver
      description: |
        T-39.17 — the bill holds both, so every till, the guests' phones (the table's bill) and checkout price the automatic
        service charge alike. Only the fields given change. Needs TILL_SELL; tenant-scoped (another business's bill is 404).
        Online only. A party size is the table's: a bill at no table is refused it (`not_a_table_bill`), though its charge
        may still be waived. Refused while a payment on the bill is being taken (`payment_in_progress`): it was quoted on the
        bill as it stood. A guest's share left open is asked about with its provider like any guest's payment (the server's
        own check, two hours on) and released only if it was never paid. After guests' payments the bill is re-priced, unless that would leave them having paid more than it comes to
        (`guests_already_paid`). A checkout asking AUTOMATIC on a waived bill charges none, so a till showing the charge is
        refused `service_charge_changed`.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OrderServiceChargeRequest" }
      responses:
        "200":
          description: The bill as it now stands, with its share code.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderDto" }
        "400":
          description: Nothing to change (`nothing_to_change`) or a party size outside 1..999 (`invalid_covers`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The bill is closed (`order_not_open`), a party size was given for a bill at no table (`not_a_table_bill`), a payment on it is being taken (`payment_in_progress`), or guests have paid more than the bill would come to (`guests_already_paid`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/orders/{id}/discard-empty:
    post:
      tags: [Orders]
      summary: Give back an empty walk-up ticket
      description: |
        Gives back the ticket a till opened only so a manager's approval had a bill to belong to (T-2.49), when the cart
        was cleared before anything was sent. Only the till that opened it, or a manager, may; only an `OPEN` ticket with no
        table, no line, comp or void and no money anywhere (the header, payments, tips, splits, discounts, promotions, room
        charges, a phone or house account, a settlement). It is marked `VOIDED`, not deleted, so its number stays accounted
        for. The order is locked first, as the line route locks it, so a line and a discard cannot both stand.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "204":
          description: The ticket was given back.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Not the till that opened it, and not a manager (`error:"not_your_ticket"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: No such order in this business (`error:"order_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Not OPEN (`error:"order_not_open"`) or not empty (`error:"order_not_empty"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/voids:
    post:
      tags: [Orders]
      summary: Void an order or a single line (Manager-gated)
      description: |
        Voids the whole transaction when `lineId` is omitted; otherwise flags just that line. `reason` is required
        (400 `reason_required` when blank). A paid, refunded or already voided order is refused, whole or a line of it
        (409 `order_paid` — refund it instead — `order_refunded` or `order_voided`), decided under the order's lock. Money on
        an order that is still open is read from its payments: any captured payment (a card capture not yet settled, a
        lay-by's instalments) refuses a whole-order void, and a line void unless that money is only guests' paid shares,
        which are judged by the bill the void leaves (409 `order_has_payments` — refund the guest, or cancel the lay-by;
        `guests_already_paid`); a payment still open on the bill, such as a guest paying their share on their phone,
        refuses a void, whole or a line (409 `payment_in_progress`: the share was quoted on the bill as it stood). A void queued offline (`/sync/push`, `adjustment`) is decided by the same rule and is refused
        the same way. The same `id` again is a replay and answers 201. A lay-by's, special order's or repair's bill is never voided
        here, whole or a line: `409 commitment_sale_has_its_own_door`, with the sentence naming its door (cancel the lay-by or the
        special order, abandon the repair).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/VoidRequest" }
      responses:
        "201":
          description: Void recorded.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "400":
          description: "`reason_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`order_paid`, `order_refunded`, `order_voided`, `order_has_payments`, `payment_in_progress` or `guests_already_paid`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/walk-outs:
    post:
      tags: [Orders]
      summary: Close an unpaid bill because the guest left without paying (a manager's; VOID_LINE)
      description: |
        A walk-out is a recorded loss, never a sale and never a void (T-37.5). The bill is closed VOIDED with nothing paid:
        no payment, tip or sale journal is written, so sales, takings, tips and the drawer's expected cash do not move, and no
        VAT is declared (a comp or a void is counted at nil in the VAT201, and so is this). The bill is put on the register
        checkout would have used, its tables are freed where they still hold it, its bar tab is closed (`WALKED_OUT`), a
        guest's phone tab closes with it, and the kitchen's unbumped tickets are struck (served ones stand). What the guest ate
        is written off once under the reason: each line's recipe, else the item, as a stock movement (`reason` the reason's
        code, `referenceId` the bill) and a shrinkage event (`source` `WALK_OUT`). It is counted in `/reports/concessions` and
        the X report on its own line (`walkedOutCents`, `walkOutsCents`), apart from the voids, and the void log lists it with
        its `walkOutReasonCode`. `reasonCode` is one of `GET /walk-outs/reasons`, the venue's own shrinkage reasons about a
        person leaving or an unexplained loss (400 `walk_out_reason_unknown`); a reason that needs a note refuses without one
        (400 `walk_out_note_invalid`). Online only: it is never queued. A bill is walked out of once: the same `id`, or another
        id for the same bill, answers 200 with `replayed: true`; an `id` already in use for something else is 409
        `id_conflict`. Refused before anything is written, each with its remedy (409): a table whose seated booking holds a
        paid deposit (`booking_deposit_held` — comp what the deposit does not cover, then settle, so the deposit pays towards it), a lay-by (`walk_out_layby`), a tab still
        carrying an older card authorisation (`walk_out_card_held`), a bill something was paid on (`walk_out_part_paid`), a bill that is not open — paid, refunded or voided
        (`order_not_open`), a payment open on it or a
        room charge standing on it (`order_has_payments`, `payment_in_progress`, `room_charge_held`), and one that owes
        nothing (`walk_out_nothing_owed`). Another business's bill is 404.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WalkOutRequest" }
      responses:
        "201":
          description: The walk-out was recorded.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WalkOutResult" }
        "200":
          description: This bill had already been walked out of; nothing changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WalkOutResult" }
        "400":
          description: "`walk_out_reason_unknown`, `walk_out_note_invalid` or `transaction_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The bill cannot be closed as a walk-out (see the description).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/walk-outs/reasons:
    get:
      tags: [Orders]
      summary: The reasons a walk-out may be recorded under (a manager's; VOID_LINE)
      description: |
        The venue's active shrinkage reasons whose family is `THEFT` or `UNKNOWN` and that do not need a named staff member;
        the one list of why stock or takings are lost. Empty when the venue has switched them all off.
      responses:
        "200":
          description: The reasons.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/WalkOutReason" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/comps:
    post:
      tags: [Orders]
      summary: Comp a line item (Manager-gated)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CompRequest" }
      responses:
        "201":
          description: Comp recorded.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`payment_in_progress` — a payment on the bill is still open, such as a guest paying their share on their phone, which was quoted on the bill as it stood (T-41.29); a pay link the till sent counts for its first 15 minutes only. A comp queued offline (`/sync/push`, `adjustment`) is refused the same way and never applied."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/discounts:
    post:
      tags: [Orders]
      summary: Apply a structured discount to an open order (Manager-gated)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DiscountApplyRequest" }
      responses:
        "201":
          description: Discount applied.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Order is not OPEN (`error:"order_not_open"`), or a payment on it is still open, such as a guest paying their share on their phone (`payment_in_progress`, T-41.29; a pay link the till sent counts for its first 15 minutes only). A discount queued offline on an open bill (`/sync/push`, `adjustment`) is refused the same way.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Kitchen ─────────────────────────────
  /api/v1/kitchen/stations:
    get:
      tags: [Kitchen]
      summary: List active prep stations for the tenant
      description: One filter chip per station on the KDS (V12). Any authed staff can read it. With `locationId` only the stations that exist at that location (placed at it, or at every location, T-36.4); without it every station.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string }, description: "Only the stations that exist at this location." }
      responses:
        "200":
          description: Active prep stations, ordered by `sortOrder`.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PrepStationDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/kitchen/dishes/{productId}:
    get:
      tags: [Kitchen]
      summary: A dish's card for the kitchen — prep notes, recipe and photo (KDS_VIEW or TILL_SELL)
      description: |
        What a cook reads when a dish is opened from its ticket (T-36.11): the prep notes the venue wrote on the dish, its recipe
        lines in the order written, and the address of its photo. It carries no cost or margin for any role. A business's other
        dishes and unknown ids answer 404 alike. A paired kitchen screen may call it (it is on the screen allow-list); the venue's hub
        answers a partial card (`partial: true`: notes only) when the cloud is out of reach.
      parameters:
        - { name: productId, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The dish's card.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DishCardDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: No such dish in this business (`dish_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/kitchen/ready-board:
    get:
      tags: [Kitchen]
      summary: The ready board — QR and kiosk orders waiting at the pass (TILL_SELL)
      description: Pickup numbers of orders whose every ticket is plated, ready in the last 20 minutes and not yet served, newest first. The customer display shows them while the till is idle (T-5.5).
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The board.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReadyBoardDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kitchen/ready-tv:
    get:
      tags: [Kitchen]
      summary: The Ready to collect screen's numbers — a screen paired as one only (READY_BOARD_VIEW)
      description: >
        Pickup numbers being prepared and ready to collect at the location the screen was paired at (T-36.15). Numbers and times only:
        never a guest's name or phone, a dish or an amount. Asked only by a screen paired as a Ready to collect screen; no person's
        role holds the permission, and a paired screen of any other kind is refused. A `locationId` other than the screen's own is
        refused 403 with the same answer as any refusal, so a screen cannot be used to learn another location's numbers.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string }, description: "The screen's own location; omit it to read the one it was paired at." }
      responses:
        "200":
          description: The numbers.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReadyTvDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kitchen/tickets:
    get:
      tags: [Kitchen]
      summary: List KDS tickets for a location (kitchen board / service expo / recall list)
      description: >
        The default `board` view excludes `BUMPED`/`RECALLED` tickets and is ordered
        rush-first, then oldest-fired-first. `view=expo` powers the waiter/service side:
        every ticket not yet served — including bumped-at-the-pass tickets from the last
        60 minutes — plus just-served ones (10 minutes) so a mis-tap can be undone.
        `view=recall` lists tickets bumped in the last 30 minutes, newest first.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: stationId
          in: query
          required: false
          description: "Filter to one configured prep station by id (V12). The single id an older screen sends; `stationIds` is the list."
          schema: { type: string }
        - name: stationIds
          in: query
          required: false
          description: "Filter to the prep stations a screen is set to (T-36.1): ids separated by commas (a comma or percent inside an id is written `%2C` or `%25`). Wins over `stationId` when both are sent. Absent: every station, a ticket fired to no station among them. Refused with 400 `bad_stationIds` (never read as every station): a blank list, an empty entry (`a,,b`, `,`), an id over 64 characters, more than 24 ids; `stationId=` blank is refused the same way."
          schema: { type: string }
        - name: station
          in: query
          required: false
          description: "Legacy filter by station name/code (BAR | HOT | PASTRY | MAIN); superseded by `stationId`."
          schema: { type: string }
        - name: view
          in: query
          required: false
          description: "Which KDS face is asking (V15): board (default) | expo | recall."
          schema: { type: string, enum: [board, expo, recall] }
      responses:
        "200":
          description: Tickets.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/KitchenTicketDto" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/kitchen/tickets/seen:
    post:
      tags: [Kitchen]
      summary: A kitchen screen marks the tickets its board has shown
      description: |
        T-5.6 — sets each ticket's `seen_at` once (the first screen to show it is when the kitchen had it); ids that are
        not this business's are ignored. A station whose print mode is `IF_SCREEN_MISSES` prints a ticket only when no
        screen has marked it within its wait. Needs the permission to bump kitchen tickets.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TicketIds" }
      responses:
        "204": { description: Marked. }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kitchen/tickets/unseen:
    post:
      tags: [Kitchen]
      summary: Which of these tickets no kitchen screen has shown yet
      description: |
        T-5.6 — the till that fired asks after the station's wait and prints the ones returned. Ids that are not this
        business's are never returned. Needs the permission to ring up sales.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TicketIds" }
      responses:
        "200":
          description: The unseen ones.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TicketIds" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kitchen/tickets/print-claims:
    post:
      tags: [Kitchen]
      summary: A kitchen screen claims the tickets it is about to print
      description: |
        T-1.21 — a kitchen screen prints the tickets no till prints (a guest's QR or kiosk order, a delivery, a course the
        kitchen fired; `autoFired`) for a station that prints every ticket. Each ticket's print is claimed once, by the
        signed-in screen (its token's session — nothing in the body says who claims). The answer lists the ids this screen
        holds: those this call won, and those its own claim won in the last two minutes, so a screen whose answer was lost
        gets them back on asking again; a second screen on the same station is answered with nothing to print. Only
        tickets of this business at `locationId`, and at `stationId` or the `stationIds` the screen shows when given, are claimed. Needs the permission to bump
        kitchen tickets (a paired kitchen screen holds it).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PrintClaim" }
      responses:
        "200":
          description: The ids this screen won and should print.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TicketIds" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kitchen/tickets/held-send-paper:
    post:
      tags: [Kitchen]
      summary: A counter till claims the paper of its held Sends that something else fired
      description: |
        T-43.23 — at a location whose till fires after payment, a Send is held until the bill is paid. When something other than the
        till's own checkout fires it (the webhook of the till's pay link, a guest paying on their phone, the clock, a sale queued
        offline), its tickets are on the board with no till behind them. A till at the location polls here: the tickets of such
        Sends, still being made and not yet printed, at stations with a printer that prints by itself and no kitchen screen showing
        them, are claimed once through the same claim a kitchen screen makes (`/kitchen/tickets/print-claims`), so the till or a
        screen prints each ticket and never both. The answer lists the tickets this till won, to print now, shaped as a Send's.
        Needs the permission to sell at the till.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [locationId]
              properties:
                locationId: { type: string, description: "The till's own location." }
      responses:
        "200":
          description: The tickets this till won and should print now.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/FireResult" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kitchen/tickets/{id}/print:
    post:
      tags: [Kitchen]
      summary: Record a print somebody asked for
      description: |
        T-1.21 — the board's Print key: granted and counted. When no screen has claimed the ticket yet this also
        claims it, so no screen prints it again by itself. Needs the permission to bump kitchen tickets.
      x-rate-limit: "ticketPrint: 60/min"
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "204": { description: Recorded. }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429": { description: "More than the `ticketPrint` bucket allows from this screen in a minute; see `Retry-After`." }
  /api/v1/kitchen/coming-up:
    get:
      tags: [Kitchen]
      summary: Orders held for later that the kitchen has not been sent yet (KDS_VIEW or TILL_SELL, T-36.21)
      description: A takeaway or delivery a guest chose a later time for is not fired at placement; it waits and is sent to the kitchen its lead before that time (`fireLeadMinutes` on the location's window, 20 by default), once. This lists what waits at a location, soonest to fire first — the board's "Coming up" strip. A voided or cancelled order is not listed. The held order has no kitchen ticket until it fires.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The waiting orders.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ComingUpOrder" } }
        "400":
          description: "`missing_locationId`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Neither KDS_VIEW nor TILL_SELL, or the business has no kitchen licence.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/kitchen/coming-up/{orderId}/fire:
    post:
      tags: [Kitchen]
      summary: Fire now — send a held order to the kitchen before its time (KDS_BUMP, T-36.21)
      description: "Fires through the same path as every other fire (routing, paper fallback, the guest's ready message unchanged), once however many screens tap it or the clock reaches it first; whoever is second gets `tickets: 0`. An order voided before its time is not sent (`tickets: 0`). Audited."
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: How many tickets this fire put on the board.
          content:
            application/json:
              schema:
                type: object
                properties:
                  orderId: { type: string }
                  tickets: { type: integer, default: 0 }
                  firedAt: { type: integer, format: int64, default: 0 }
                required: [orderId]
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: Not a role that may bump kitchen tickets (`permission_required`), or no kitchen licence.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "No held order by this id for this business (`scheduled_order_not_found`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/kitchen/tickets/{id}/bump:
    post:
      tags: [Kitchen]
      summary: Bump (complete) a ticket
      description: 'Optional JSON body `{"byStaffId": "..."}` attributes the bump to that (validated) staff member; defaults to the caller.'
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Ticket bumped.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/tickets/{id}/ready:
    post:
      tags: [Kitchen]
      summary: Mark a ticket plated (FIRED → READY) and notify waitstaff
      description: >
        Stamps `readyAt` (first tap wins — re-tapping never resets the pass timer) and
        publishes a `kitchen.ready` "run this table" event on `/sync/ws`, carrying the
        ticket's `serverStaffId` so the till shows it to that waiter (T-5.4). The ticket
        stays on the kitchen board until bumped or served. Optional JSON body
        `{"byStaffId": "..."}` attributes it.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Ticket marked READY.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/orders/{id}/call:
    post:
      tags: [Kitchen]
      summary: The expo or pass calls an order (T-36.5)
      description: >
        At a location with an Expo or Pass station, an order is ready only when every station has
        plated its part AND the expo calls it: this is that call. It stamps `calledAt` on the
        order's tickets (the first call stands, a repeat changes nothing) and, for a QR or kiosk
        order, tells the guest once. `409 parts_outstanding` while any station still has its part
        to plate (the message names them), `409 no_expo_here` at a location that has no Expo or
        Pass (there the order is ready when the last station has plated), `404 order_not_found`
        for an order with nothing in the kitchen or another business's. A kitchen screen paired
        as itself may call it; the LAN hub serves the same route offline and the call reaches
        the server as a queued `kitchen_ticket_event` (`CALL`).
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Called (or already called).
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string, enum: [CALLED] } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Parts outstanding, or no expo or pass at this location.
  /api/v1/kitchen/tickets/{id}/items-ready:
    post:
      tags: [Kitchen]
      summary: Mark items on a ticket ready at the pass before the ticket is (T-36.16)
      description: >
        An item can be out at the pass before the rest of its ticket is. Body
        `{"indexes": [0, 2], "byStaffId": "..."}`: the positions on the ticket's `items` to mark
        (`byStaffId` is optional). A mark is set once: the first moment stands, and marking a line
        that is already ready changes nothing. A voided line is left out. The ticket and the order
        are not made ready by it; the station's own Ready or Bump does that, and a Bump makes every
        item of the ticket ready without writing a mark for each. A recall takes every mark back.
        `400 bad_item_index` names how many items the ticket has, `400 no_items` for an empty
        list, `404 ticket_not_found` for a ticket that is not this business's. The same permission
        as bump; a kitchen screen paired as itself may mark. The LAN hub serves the same route
        offline and each mark reaches the server as a queued `kitchen_ticket_event`
        (`ITEM_READY`). The marks come back as `itemReadyAt` on the kitchen ticket.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [indexes]
              properties:
                indexes: { type: array, items: { type: integer, minimum: 0 } }
                byStaffId: { type: string, nullable: true }
      responses:
        "200":
          description: Marked (or already marked).
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  itemReadyAt: { type: object, additionalProperties: { type: integer, format: int64 }, description: "Item position (as text) to when it was first marked ready." }
        "400":
          description: An item position the ticket does not have, or none given.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/tickets/{id}/target:
    post:
      tags: [Kitchen]
      summary: Add minutes to, or take minutes off, one ticket's target (T-26.6)
      description: >
        Body `{"changeSec": 240, "byStaffId": "..."}`: the NET seconds this one ticket's target is moved by
        (positive later, negative sooner; `byStaffId` is optional). The figure is absolute, not a step, so
        the same request sent again (a retry, a LAN hub's replay) changes nothing and the last one stands.
        It is held to an hour either way, and a target never drops below a minute. The target the ticket was
        resolved with is never rewritten: the due time and colour follow through the board's one ageing
        rule, and the kitchen report keeps both the original target and the change (`retimed`,
        `lateAtOriginalTarget`, `netChangeSec`). `404 ticket_not_found` for a ticket that is not this
        business's. The same permission as bump; a kitchen screen paired as itself may send it. The LAN hub
        serves the same route offline and each change reaches the server as a queued
        `kitchen_ticket_event` (`TARGET`). The figure comes back as `targetChangeSec` on the kitchen ticket.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [changeSec]
              properties:
                changeSec: { type: integer, description: "Net seconds, -3600 to 3600; anything beyond is held to it." }
                byStaffId: { type: string, nullable: true }
      responses:
        "200":
          description: Set (or already that figure).
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  targetChangeSec: { type: integer }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/tickets/{id}/serve:
    post:
      tags: [Kitchen]
      summary: Confirm the food was delivered to the table (V15)
      description: >
        The waiter-side complement to bump. Stamps `servedAt`/`servedByStaffId`; if the
        kitchen never bumped the ticket, taking the food IS the bump, so the ticket is
        bumped off the board too (and SEQUENTIAL course auto-advance still fires).
        Idempotent — re-serving keeps the first stamp. Optional JSON body
        `{"byStaffId": "..."}` attributes the run.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Ticket served (response status SERVED).
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The ticket is in the legacy RECALLED hide-state (`ticket_recalled`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/kitchen/tickets/{id}/unserve:
    post:
      tags: [Kitchen]
      summary: Undo a mis-tapped serve
      description: Clears `servedAt` — the ticket returns to the service run list (it stays BUMPED, off the kitchen board).
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Serve undone (status BUMPED).
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: No served ticket with this id for the caller's tenant (`ticket_not_served`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/kitchen/tickets/{id}/progress:
    post:
      tags: [Kitchen]
      summary: Set a ticket's shared per-item prep ticks (V15)
      description: >
        Full-state set (not a toggle) so concurrent KDS screens converge on
        last-write-wins. Indexes point into the ticket's `items` array; out-of-range
        and duplicate values are dropped. Broadcast to other devices as `kitchen.progress`. A tick is a position, so
        `lineIds` (each item's `lineId`, in order, as the screen drew the ticket) is refused with 409
        `ticket_lines_changed` when the ticket now holds other dishes; a request without it is refused so only on a
        ticket whose dishes a station move changed.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                doneIndexes: { type: array, items: { type: integer } }
                lineIds: { type: array, items: { type: string, nullable: true }, description: "T-36.10 — the line id at each position as the screen drew the ticket." }
      responses:
        "200":
          description: Ticks stored (echoes the cleaned index list).
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, doneIndexes: { type: array, items: { type: integer } } } }
        "400":
          description: "`missing_body`, or `bad_progress`: `lineIds` names more than 500 dishes, or a line id longer than 100 characters; nothing was ticked."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: A dish on the ticket moved since the screen drew it (`ticket_lines_changed`); nothing was ticked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/kitchen/orders/{id}/progress:
    get:
      tags: [Kitchen]
      summary: How far each station is with one order, for the pass (T-1.19)
      description: >
        A read over the order's own kitchen tickets: per station, how many of its tickets have
        reached the pass (READY or later), been served, or had every line voided — two stations
        with one bumped is 1 of 2. Needs "See the kitchen screen" or "Ring up sales", and a
        business that runs a kitchen. Another business's order is not found.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The order's per-station progress.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderProgress" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/progress:
    get:
      tags: [Kitchen]
      summary: Per-station progress for many orders at once, for the expo panel (T-1.11)
      description: >
        The same read as `/api/v1/kitchen/orders/{id}/progress`, for every order a kitchen board
        shows, in one request. Since T-36.6 the board reads the same figure from `orderProgress` on the tickets of
        `GET /api/v1/kitchen/tickets` and does not call this; it stays for older clients. Orders are read only among this business's
        kitchen tickets: an order id with no tickets here — another business's, or one never sent —
        is left out of the answer, never refused. At most 200 ids. Needs "See the kitchen screen"
        or "Ring up sales", and a business that runs a kitchen.
      parameters:
        - name: orderIds
          in: query
          required: true
          description: The orders, comma-separated (`a,b,c`).
          schema: { type: string }
      responses:
        "200":
          description: One entry per order that has kitchen tickets here.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/OrderProgress" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/kitchen/tickets/{id}/fire-next:
    post:
      tags: [Kitchen]
      summary: Fire the course this ticket's order is holding (T-5.4)
      description: >
        The kitchen calls the next course away. `course` is the ticket's `heldCourse` as the
        board showed it; while that is still the course held, the order fires exactly what a
        paced "ALL" fire would (that course, plus any unsent drinks), and the answer lists the
        new tickets. When it is no longer the one held — the till fired it meanwhile, another
        screen got there first, or the tap repeated — nothing fires and `tickets` is empty, so a
        stale tap never sends the course after it. Needs the "Bump kitchen tickets" permission.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [course]
              properties:
                course: { type: string, enum: [STARTER, MAIN, SIDE, DESSERT] }
      responses:
        "200":
          description: What fired; an empty `tickets` list means nothing did.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/FireResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/tickets/{id}/move:
    post:
      tags: [Kitchen]
      summary: Move a ticket, or some of its dishes, to another station (T-36.10)
      description: >
        A grill goes down mid-service and its work goes to another station. With `lineIds` the named dishes
        move; without, the whole ticket. A station holds one ticket per order and course: a move onto a station that
        already has a live one joins it, and makes a new ticket only when there is none. Each ticket keeps the ticks of
        its own dishes (renumbered for the ticket they land on), a dish already made at the destination is not made
        twice, the line is not priced again (only tickets move), the ticket's allergens are recomputed from the dishes it
        now holds, and the new station's printer and screen treat it as new. A ticket already plated, bumped or served
        stays where it was made (409 `ticket_not_live`); a ticket a hub worked offline moves whole or not at all (409
        `ticket_worked_offline`); a closed station takes no work (409 `station_closed`). The `opId` is the claim: a
        retry, or the replay of a move a hub took offline, lands once; another business's same `opId` is its own. At
        most 200 `lineIds`, and no id longer than 100 characters (400 `bad_move`). Another business's ticket is not found
        and another business's station is `unknown_station`. Needs the "Bump kitchen tickets" permission; a Ready TV is refused.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StationMoveRequest" }
      responses:
        "200":
          description: Where the dishes now are; `applied` false when nothing needed to move.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StationMoveResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The ticket is no longer live, was worked offline, or the station is closed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/kitchen/stations/{id}/redirect:
    put:
      tags: [Kitchen]
      summary: Close a station by sending its work elsewhere, or reopen it (T-36.10)
      description: >
        Sets, absolutely, where a closed station's work goes: every open ticket at the station moves to the landing station
        (the end of the chain, when the target is itself closed), and every ticket fired there afterwards lands there until
        the station is reopened (`toStationId` null). Asking for the redirect a station already has changes and moves
        nothing. A station may not send its work to itself or round a circle (400 `bad_redirect`); the target must be a
        live station of this business (400 `unknown_station`). Reopening does not bring moved tickets back. It changes
        where every location's new work goes, so it is the station's configuration: it needs the "Change settings"
        permission, as `POST /catalogue/prep-stations` does, and a kitchen screen signed in as itself is refused it. The
        kitchen must be online: a till firing offline follows the last redirect it pulled.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StationRedirectRequest" }
      responses:
        "200":
          description: The redirect now in force and the tickets it carried.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StationRedirectResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/tickets/{id}/rush:
    post:
      tags: [Kitchen]
      summary: Set or clear a ticket's rush (priority) flag
      parameters:
        - $ref: "#/components/parameters/PathId"
        - name: rush
          in: query
          required: false
          description: "true (default) to rush, false to un-rush. A JSON body {\"rush\": bool} also works."
          schema: { type: boolean }
      responses:
        "200":
          description: Rush flag updated to the requested value.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, rush: { type: boolean } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/kitchen/tickets/{id}/recall:
    post:
      tags: [Kitchen]
      summary: Recall a bumped ticket back to the board (BUMPED → FIRED)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Ticket back on the board (status FIRED).
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, status: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: No BUMPED ticket with this id for the caller's tenant.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Tabs ─────────────────────────────
  /api/v1/tabs:
    get:
      tags: [Tabs]
      summary: List open/pre-billed tabs for a location
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Tabs.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/TabDto" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Tabs]
      summary: Open a new bar tab
      description: Creates the backing order and the tab record together.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TabOpenRequest" }
      responses:
        "201":
          description: Tab opened.
          content:
            application/json:
              schema:
                type: object
                properties: { tabId: { type: string }, orderId: { type: string } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/tabs/{id}/preauth:
    post:
      tags: [Tabs]
      summary: Record a card against a tab (not offered)
      description: |
        Calls a card-authorisation endpoint that Yoco has not published, so it answers 502 `yoco_preauth_failed` unless
        the venue's Yoco account has a partner agreement. The till does not call it: a tab runs on the bill and is settled
        at the end. Do not build against it.
      deprecated: true
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TabPreauthRequest" }
      responses:
        "200":
          description: Recorded.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  preauthAmountCents: { type: integer, format: int64 }
                  preauthRef: { type: string }
                  status: { type: string }
                  redirectUrl: { type: string, nullable: true }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "502":
          description: Yoco refused it (`error:"yoco_preauth_failed"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/tabs/{id}/settle:
    post:
      tags: [Tabs]
      summary: Settle a tab (final bill + tip) through the full checkout pipeline
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TabSettleRequest" }
      responses:
        "200":
          description: Tab settled.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  status: { type: string }
                  tipCents: { type: integer, format: int64 }
                  totalCents: { type: integer, format: int64 }
                  paidCents: { type: integer, format: int64 }
                  subtotalCents: { type: integer, format: int64, nullable: true, description: "Checkout's subtotal, for the receipt." }
                  vatCents: { type: integer, format: int64, nullable: true, description: "Checkout's VAT: the bill as one document, its service charge taxed with the goods (D-218)." }
                  discountCents: { type: integer, format: int64, nullable: true, description: "The discount checkout charged." }
        "400":
          description: Payments + tips don't cover the tab total.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Tab already settled (`error:"tab_already_settled"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Payments ─────────────────────────────
  /api/v1/payments/{id}:
    get:
      tags: [Payments]
      summary: Fetch a payment's status
      description: |
        Status poll for a pending provider payment — the terminal's safety net while it waits for the
        provider webhook to capture (browser tills have no WebSocket push channel). Tenant-scoped.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: The payment's current status (`PENDING` | `CAPTURED` | `FAILED`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: No such payment for this tenant (`error:"payment_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/receipts/link/{transactionId}:
    get:
      tags: [Payments]
      summary: Fetch the signed digital-receipt link for a sale
      description: |
        The link the customer display shows as a QR once a sale has closed. Keyed by the
        transaction's id (the one the till committed it under) and signed for the transaction
        number the server holds, which can differ from the till's own when two offline tills
        allocated the same number. Answers 404 until the sale has synced. Tenant-scoped.
      parameters:
        - name: transactionId
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: The server's transaction number and the signed public receipt URL.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReceiptLinkResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: The sale has not reached the server yet (`error:"receipt_not_synced"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/payments/yoco/checkout:
    post:
      tags: [Payments]
      summary: Create a Yoco card checkout
      description: |
        Supports replay via `idempotencyKey`: a retried create with the same key returns the payment
        recorded by the first attempt instead of charging twice. A lay-by's, special order's or repair's bill is
        refused 409 `commitment_sale_has_its_own_door` before Yoco is asked (T-21.6 review 4); every other pay-by-link door the same.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PaymentRequest" }
      responses:
        "200":
          description: Checkout created (or idempotent replay of an existing one).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: A room charge stands on the bill (`error:"room_charge_held"`, `POSTED` or sent and unconfirmed; not `RELEASED`); no link is opened and the provider is not asked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "502":
          description: Yoco unavailable (`error:"yoco_unavailable"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/payments/snapscan/create:
    post:
      tags: [Payments]
      summary: Create a SnapScan QR payment (not offered right now)
      description: >-
        SnapScan is not offered right now: a new payment is refused (409 `snapscan_not_offered`). A retried create of a payment
        made before that still replays via `idempotencyKey`, including recovering the original QR payload.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PaymentRequest" }
      responses:
        "200":
          description: Payment created (or idempotent replay).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: SnapScan is not offered right now (`error:"snapscan_not_offered"`, with the sentence to show), or a room charge stands on the bill (`error:"room_charge_held"`, `POSTED` or sent and unconfirmed; not `RELEASED`); no link is opened and the provider is not asked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "502":
          description: SnapScan unavailable (`error:"snapscan_unavailable"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/payments/zapper/create:
    post:
      tags: [Payments]
      summary: Create a Zapper QR payment (not offered to venues)
      description: |
        Zapper is hidden from venues: every tenant but Ruva's demo business is refused with `409 zapper_not_offered`
        before anything is sent. Supports replay via `idempotencyKey`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PaymentRequest" }
      responses:
        "200":
          description: Payment created (or idempotent replay).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: Zapper is not offered to this business (`error:"zapper_not_offered"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "502":
          description: Zapper unavailable (`error:"zapper_unavailable"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/payments/cash:
    post:
      tags: [Payments]
      summary: Capture a cash payment
      description: Captures immediately (no provider round-trip) and returns the signed public digital-receipt link. Supports replay via `idempotencyKey`. A lay-by's, special order's or repair's bill is refused 409 `commitment_sale_has_its_own_door` (T-21.6 review 4).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PaymentRequest" }
      responses:
        "200":
          description: Cash captured.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"

  # ───────────────────────────── Refunds ─────────────────────────────
  /api/v1/payments/refund:
    post:
      tags: [Refunds]
      summary: Refund a settled transaction, in full or in part (Manager-gated)
      description: |
        Three-phase refund so a hung provider can never pin a database connection: snapshot the original
        transaction/payments/lines/journal, reverse with each payment's provider, then post the reversing
        journal entry.

        A sale may be refunded more than once (T-4.3): each refund is its own reversal, and together they
        never exceed what the sale took — `409 refund_exceeds_paid` names what is left. Omitting `amountCents`
        refunds everything still unrefunded. An amount names no units, so it moves no stock, except the
        refund that finishes the sale, which restocks every unit not already returned. To return items by the
        line, with reasons, write-offs or an exchange, use `POST /api/v1/returns`. A sale that is not closed
        (`OPEN`, `FIRED`, `VOIDED`) is `409 sale_not_closed`; two refunds of one sale racing each other are
        `409 refund_raced` for the second. A refund that asks Yoco claims the sale's next refund before Yoco is asked, so a
        second refund of the sale while it is at Yoco is `409 refund_in_progress`, sent nowhere, and may be made once the
        first has landed (T-20.2).

        A PayFast payment is refunded through PayFast's Refunds API on the venue's own account (T-1.22): its refund query
        first, then the refund, once per sale, payment, refund and amount — PayFast takes no idempotency key, so Ruva claims
        each send before making it and never sends a claimed one again. A refund PayFast can pay only into the guest's bank
        account, or cannot make, is booked with that leg `MANUAL` and a `notice` naming what to do in PayFast's dashboard;
        Ruva never asks for bank details. A leg a past sale took through Zapper (no longer offered) is `MANUAL` ("Refund this in Zapper's merchant portal"). PayFast is
        told "Refund of your order" and emails the guest; `reason` is never sent to PayFast. A PayFast refund that went out and
        could not be recorded (its booking lost a race with another refund of the sale: `409 refund_raced`, which then says so)
        is listed on the order as a refund check (`sent:…`) to record once.

        Cash handed back (T-41.39) comes out of a register at the sale's location, the till that gave it rather than the one
        that rang the sale: the open register of `staffId`, else the approving manager's there, else the location's only open
        register. A `staffId` whose register is at another location charges no drawer (a return taken at another store), and
        a register at another location is never charged. It is recorded once as a `CASH_REFUND` movement on that register,
        which its expected cash is less; the same `refundId` again records nothing more. With no register to name, the refund
        is still made and no drawer is charged. A card refund moves no drawer.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RefundRequest" }
      responses:
        "200":
          description: Refund processed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RefundResult" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "400":
          description: "`invalid_refund_amount` — an amount of zero or less."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`refund_exceeds_paid` — more than the sale took, counting earlier refunds; the message names what is left. `sale_not_closed`, `is_a_refund`, `refund_raced`, `refund_in_progress` (the same PayFast refund, or another refund of the sale to Yoco, is being sent now and nothing was sent; look the order up again), `refund_attempts_spent` (the sale's next refund to Yoco was tried too many times; refund it in Yoco's portal and Ruva records it), `refund_recorded` (that PayFast refund was paid and is recorded on the order already; nothing was sent), `refund_id_in_use` (that `refundId` is already taken, by any transaction), or `refund_id_mismatch` (that `refundId` was used for a different amount)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "502":
          description: |
            `refund_refused` — the payment provider refused outright (a 4xx, or no account to ask with) every leg it was
            asked to pay back, so no money moved and nothing was written: the sale, its journal and the reports are as they
            were. The message carries the provider's own reason. A provider that did not answer, answered 5xx or sent an
            unreadable answer is NOT a refusal: the refund is booked with that leg `UNCONFIRMED` and a `notice`. Yoco's
            idempotency key carries the sale, the payment, which refund of it this is and the amount. A PayFast refund is
            also refused, unsent, when PayFast shows more refunded on the payment than Ruva has recorded (a refund made in
            PayFast's dashboard), or less left than this refund.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/sales/ratings:
    get:
      tags: [Refunds]
      summary: Guests' ratings — the average and the latest comments (VIEW_REPORTS)
      description: |
        What guests rated their QR orders over the last `days` (T-1.17): how many ratings, their average in tenths
        (`averageTenths: 43` is 4.3 stars; absent when there are none), and the five latest that carry a comment, newest
        first. An order's own rating is on `GET /api/v1/sales/orders/{id}` (`rating`, `ratingComment`).
      parameters:
        - { name: days, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 365, default: 30 } }
      responses:
        "200":
          description: The window's ratings.
          content:
            application/json:
              schema:
                type: object
                required: [count]
                properties:
                  count: { type: integer }
                  averageTenths: { type: integer }
                  lowCount: { type: integer, description: "How many were 2 stars or below — every one, emailed or not (the managers' email is capped per hour)." }
                  latest:
                    type: array
                    items:
                      type: object
                      required: [orderId, rating, comment, at]
                      properties:
                        orderId: { type: string }
                        rating: { type: integer, minimum: 1, maximum: 5 }
                        comment: { type: string }
                        at: { type: integer, format: int64 }
        "400":
          description: "`invalid_days` — not a whole number from 1 to 365."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/sales/orders:
    get:
      tags: [Refunds]
      summary: The business's orders in a window, a page at a time (VIEW_REPORTS)
      description: |
        With `format=csv|pdf` it is a file, refused (`403 second_factor_required`, T-37.4) to a session that has not typed its
        code where the business requires a second factor; the JSON pages are unchanged.
        Newest first; refunds are not orders, they show as `refundedCents` on the order they refunded. `standing` is
        worked out from the order as it stands and never stored: `NEEDS_ATTENTION` is a guest's (QR) order whose captured
        payments cover it and that is still open — the settle after the capture failed (`POST /api/v1/sales/orders/{id}/settle`).
        `counts` are the whole window's, for every filter, on every page. With `format=csv` or `pdf` the same list (up to
        5,000 rows) comes as a file.
      parameters:
        - { name: period, in: query, required: false, schema: { type: string, enum: [today, yesterday, week, month, year] }, description: "A named window (`week` is today and the six days before); today when neither it nor from/until is given." }
        - { name: from, in: query, required: false, schema: { type: integer, format: int64 }, description: "Epoch ms; with until, wins over period." }
        - { name: until, in: query, required: false, schema: { type: integer, format: int64 }, description: "Epoch ms, exclusive." }
        - { name: status, in: query, required: false, schema: { type: string, enum: [all, paid, open, attention, refunded], default: all } }
        - { name: q, in: query, required: false, schema: { type: string, maxLength: 40 }, description: "Part of an order number or a table's name." }
        - { name: locationId, in: query, required: false, schema: { type: string } }
        - { name: channel, in: query, required: false, schema: { type: string, enum: [till, qr, kiosk] }, description: "Only this channel's orders: a guest's own phone (qr), a self-order kiosk (kiosk) or the till (till); every channel when absent. The counts are the narrowed window's." }
        - { name: cursor, in: query, required: false, schema: { type: string }, description: "The previous page's nextCursor." }
        - { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
        - { name: format, in: query, required: false, schema: { type: string, enum: [csv, pdf] } }
      responses:
        "200":
          description: A page of orders, or the list as CSV/PDF.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SalesOrderPage" }
            text/csv:
              schema: { type: string }
            application/pdf:
              schema: { type: string, format: binary }
        "400":
          description: "`invalid_status`, `invalid_channel`, `invalid_cursor`, `invalid_limit`, `invalid_range`, `invalid_period` or `invalid_format`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  /api/v1/sales/orders/{id}:
    get:
      tags: [Refunds]
      summary: One order — lines, payments, refunds and the guest's receipt link (VIEW_REPORTS)
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SalesOrderDetail" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"

  /api/v1/sales/orders/{id}/settle:
    post:
      tags: [Refunds]
      summary: Settle now — close a guest order whose captured payment covers it (TILL_SELL)
      description: |
        Only for an order whose `standing` is `NEEDS_ATTENTION`. It runs the same settle a payment's capture runs: checkout
        with no new payment, which books the sale, its VAT, tip and stock. Nothing is charged again.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Settled; the order as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SalesOrderDetail" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`nothing_to_settle` — the order does not need it; `settle_failed` — it is still paid and open, and nothing was charged again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/sales/orders/{id}/counter-payment:
    post:
      tags: [Refunds]
      summary: Take payment at the counter — close a guest's counter order as paid (SETTLE_COUNTER_ORDER, T-1.20)
      description: |
        For a guest's order that is waiting to be paid at the counter (`standing` `AT_COUNTER` or `UNPAID`), at a business
        with no till whose location has switched the counter on, or a guest's phone tab (T-30.14). The amount is the whole
        bill — there is no part payment — except on a phone tab, where it is what guests have not already paid on their phones
        (`toTakeCents` on the desk). `expectedTotalCents` is that figure as the desk showed it: when the order now comes to
        another (a round added, a share paid since) the answer is `409 order_total_changed` and nothing is booked. It goes through checkout, the one sale writer, so the payment row, journal, receipt, stock and every report are
        those of any sale. `method` is `CASH` (to cash on hand, to the cent, with `roundingCents` only when the customer agreed to it), `COUNTER_CARD` (a card on the
        venue's own machine) or `COUNTER_EFT` (straight to the bank). Idempotent on the order: pressing it again — with any
        method — answers the order and writes nothing. Held by management by default; never by a paired screen.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CounterPaymentRequest" }
      responses:
        "200":
          description: The order as it now stands (Paid).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SalesOrderDetail" }
        "400":
          description: "`invalid_method`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`not_a_counter_order`, `order_already_paid`, `order_voided`, `nothing_to_pay`, `order_partly_paid` (the counter takes the whole bill or none of it; a phone tab excepted), `payment_in_progress` (a payment is open on a guest's phone: nothing is taken until it is finished or cancelled) or `order_total_changed` (checkout's figure is no longer the total the guest was shown, or what is to be taken is no longer `expectedTotalCents` — both amounts in the message; nothing is taken)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/sales/orders/{id}/check-payment:
    post:
      tags: [Refunds]
      summary: Check a guest's payment left open on their phone with its provider — settle or release it (SETTLE_COUNTER_ORDER, T-30.14)
      description: |
        A payment a guest started on their phone (a share of the bill or the whole order, through Yoco, PayFast or SnapScan) and
        never finished holds the order: it cannot be taken at the counter or voided. This asks the provider, under the venue's own
        account, about every such payment on the order. Paid there → `CAPTURED`: it is recorded and the order settled, once, as the
        provider's notice would have. Not paid (a checkout created or started and left, nothing in PayFast's history, an error or
        no record at SnapScan) → `RELEASED`: the payment is failed with who released it, and the order can be taken or voided.
        When the provider cannot say, nothing moves. The server also checks every guest payment open for two hours by itself.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: What the provider said, and what was done.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentCheckAnswer" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`no_payment_in_progress`, `not_a_guest_payment` (a till's own payment; a guest's share of a till's bill is checked), `payment_too_recent` (started under 15 minutes ago: the guest may still be paying), `payment_still_paying`, `payment_amount_mismatch` (the provider shows another amount: look it up there) or `provider_cannot_be_asked`. Nothing moved."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "502":
          description: "`provider_unanswered`: the provider did not answer, so nothing was released. Try again in a few minutes."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/sales/orders/{id}/cancel:
    post:
      tags: [Refunds]
      summary: Cancel a guest's order left waiting on a phone payment never made (SETTLE_COUNTER_ORDER, D-208)
      description: |
        For an order whose only standing is a payment a guest started on their phone (Yoco, PayFast or SnapScan) and never
        finished — nothing captured, not a counter order or a phone tab (`cancellable` on the order's detail). The provider is
        asked first, under the venue's own account, with no wait. Not paid there: every such payment is failed with who released
        it and the order is voided — off every open list, nothing charged, its pay-first hold cancelled and the kitchen told to
        stop any ticket — and the guest's phone shows the order closed with nothing charged. Paid there: the payment is
        recorded as its notice would have and the cancel is refused. A payment the provider takes after the cancel is recorded
        paid twice and listed for a refund; the order stays voided. Pressing it again answers the order as it stands.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The order as it now stands, voided.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SalesOrderDetail" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`guest_paid` (the provider shows it paid: recorded, the order is paid, not cancelled), `nothing_to_cancel` (not an order waiting only on a guest's phone payment), `payment_moved` (finished or cancelled meanwhile), `payment_amount_mismatch` or `payment_still_paying`. Nothing was cancelled."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: "`provider_unanswered`, `provider_cannot_be_asked` or `payments_unavailable`: the provider could not be asked, so the guest may have paid and nothing changed. Try again in a few minutes."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/sales/counter:
    get:
      tags: [Refunds]
      summary: The counter's desk — unpaid counter orders and the counter cash not yet banked (VIEW_REPORTS, T-1.20)
      description: |
        The guest orders waiting to be paid at the counter, oldest first (`pastTradingDay` once they are from an earlier
        trading day: still unpaid, to collect or to void), and for each location the cash its counter recorded and how much
        of it was banked. `mayAct` says whether the caller holds SETTLE_COUNTER_ORDER. Every figure is the server's.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string } }
      responses:
        "200":
          description: The desk.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CounterDesk" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  /api/v1/sales/counter/banked:
    post:
      tags: [Refunds]
      summary: Mark the counter cash at a location as banked (SETTLE_COUNTER_ORDER, T-1.20)
      description: |
        Banks everything the counter holds in cash at the location (taken, less refunded in cash, less banked): Dr 1050 Bank /
        Cr 1000 Cash on hand, one journal. `id` is minted once per attempt and is the business's own; a retry with the same
        `id` for the same location is answered and banks nothing more, and the same `id` for another location is refused
        (409 `banking_id_in_use`). Bankings at the same moment bank the cash once.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CounterBankRequest" }
      responses:
        "200":
          description: The desk as it now stands for that location.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CounterDesk" }
        "400":
          description: "`invalid_banking`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`location_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`nothing_to_bank` — no counter cash is waiting here; `banking_id_in_use` — that id was used for another location."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/sales/orders/{id}/refund-checks:
    post:
      tags: [Refunds]
      summary: Answer one of an order's refund checks (REFUND)
      description: |
        A refund check is something about a refund of the order that a person must look at (`SalesOrderDetail.refundChecks`).
        Send the check's `id` and one of the `answers` it offers; every answer is audited, a refused one too.
        - A refund Yoco did not pay (its `refund.failed`, or refused beside a leg that went through), already taken back off
          the books: `PAID_CASH` / `PAID_EFT` (the guest was paid another way — booked once as a refund in that tender, on
          its account) or `REFUNDED_AGAIN` (refunded again, here or in Yoco's portal; nothing more is booked here).
        - A refund Yoco has not confirmed (sent with no answer, or `pending` for more than a day): `YOCO_PAID` (nothing is
          booked) or `YOCO_DID_NOT_PAY` (its share is taken off the books, and it becomes the check above).
        - A refund Yoco paid that Ruva has not recorded: `RECORD` (book it on the person's word, once — only for one held
          because it may be Ruva's own) or `CHECKED` (nothing is booked); one that is the same money as a refund Yoco did not
          pay offers only `PAYS_BACK` (book it once as paying that refund back, and close both).
        Only a check open on this order of the caller's business is taken; a held refund is claimed in the same transaction
        as its booking, so an answer that lost to another books nothing.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                checkId: { type: string, maxLength: 300 }
                answer: { type: string, enum: [PAID_CASH, PAID_EFT, REFUNDED_AGAIN, YOCO_PAID, YOCO_DID_NOT_PAY, RECORD, CHECKED, PAYS_BACK] }
              required: [checkId, answer]
      responses:
        "200":
          description: Answered; the order as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SalesOrderDetail" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`refund_check_not_found` — no such check is open on this order (answered already, taken by another answer, or not this business's)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`answer_not_offered` — the check does not take that answer; or the refund cap or the order's state refused `RECORD` (its code), and the refund stays held."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/returns/lookup:
    get:
      tags: [Refunds]
      summary: Find a receipt to return against (REFUND)
      description: |
        REFUND, held to the business's second factor (`403 second_factor_required`, T-37.4; the till cannot ask for the code
        yet, so the sentence says to refund from the back office). T-4.3. `number` is the receipt number, or whatever a scanner read off the receipt: the digital-receipt
        link its QR code carries (`…/receipts/{number}?t=…`) finds the same sale. Answers each line's quantity,
        how many units are back already, and what the line was worth after the order discount — the figure a
        line return refunds from.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: number, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The receipt, with what can still come back.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReturnableSale" }
        "400":
          description: "`number_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`receipt_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`is_a_refund` — the number is a refund's; look up the sale it refunded."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/returns:
    post:
      tags: [Refunds]
      summary: Return items, refund them, or exchange them (REFUND)
      description: |
        REFUND, as `POST /api/v1/payments/refund` asks, held to the business's second factor (`403 second_factor_required`,
        T-37.4; the sentence says to refund from the back office). T-4.3. Returns the chosen units of a sale. Each line refunds its worth after the order discount, shared
        so that a line returned in parts refunds exactly its value in total; no unit comes back twice
        (`409 return_refused`, naming how many are left), and all refunds of the sale together never exceed
        what it took (`409 refund_exceeds_paid`).

        Each line is `RESTOCK` (back into the lot it was sold from) or `WRITE_OFF` (back in, then straight out
        again as a `RETURN_WRITE_OFF` shrinkage loss). `refundTo` sends the money back to the tenders that paid
        (shared across them by what each paid) or onto the customer's store credit (needs a customer on the sale).

        With `exchangeOrderId` it is an exchange: the return's value is captured against that open order as an
        `EXCHANGE` tender first; only what is left is refunded; if the replacements cost more, `exchangeDueCents`
        is what the customer still pays at the till. When the return covers the order it is closed as a sale
        (`exchangeSettled`). The exchanged share passes through the store-credit liability (coa-2300): credited by
        the return's reversal, debited by the replacement sale's journal, netting to nothing.

        `returnId` is minted by the caller: the same id sent again answers the same return (`replayed: true`)
        rather than making a second.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReturnRequest" }
      responses:
        "200":
          description: The return, and where its value went.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReturnResult" }
        "400":
          description: "`return_id_required`, `invalid_reason`, `note_required` (OTHER needs a note), `invalid_refund_to`, `invalid_disposition`, `no_lines`, `duplicate_line`, `line_not_on_sale`, `store_credit_needs_customer`, `exchange_order_is_the_sale`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`transaction_not_found` or `exchange_order_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`return_refused`, `refund_exceeds_paid`, `sale_not_closed`, `is_a_refund`, `refund_raced`, `refund_in_progress`, `refund_id_in_use`, `exchange_order_closed`, `exchange_order_changed`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Webhooks ─────────────────────────────
  /api/v1/webhooks/payfast:
    post:
      tags: ["Webhooks"]
      summary: PayFast ITN (instant transaction notification)
      description: |
        Posted by PayFast, form-encoded, never by a client. `m_payment_id` must name
        a PayFast payment or booking deposit of ours; its business's own PayFast
        account (or, for the demo business, the deployment's) is the one every check
        is made against. Believed only after four checks: the signature over the
        posted fields in their posted order with that account's passphrase; the
        caller resolves to a PayFast host; PayFast's `/eng/query/validate` answers
        VALID; and the payment is for that account's merchant, for exactly
        `amount_gross`. Applied once per `pf_payment_id`: a resend answers 200 and
        changes nothing.
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema: { type: object, additionalProperties: { type: string } }
      responses:
        "200": { description: "Handled, or already handled." }
        "401": { description: "Not believed — `m_payment_id` names nothing of ours, a bad signature, or not PayFast's address. One answer with an empty body whatever the reason (the reason is logged only); nothing written." }
        "503": { description: "Empty body: PayFast did not confirm it yet, or the business's PayFast account is not set up — PayFast should resend later." }
  /api/v1/pay/payfast/{paymentId}:
    get:
      tags: ["Webhooks"]
      summary: The page a guest is sent to for a PayFast payment
      description: >-
        An HTML page that posts the signed checkout form to PayFast. Renders only
        for a PENDING PayFast payment; the amount and return URLs come from the
        payment row, never from the query.
      parameters:
        - { name: paymentId, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: "The auto-posting form.", content: { text/html: { schema: { type: string } } } }
        "404": { description: "No open PayFast payment by that id.", content: { text/html: { schema: { type: string } } } }
  /api/v1/platform/audit-events/export:
    get:
      tags: ["System"]
      summary: The audit trail as CSV
      description: |
        Every row matching the same filters as `/platform/audit-events` (actor,
        entityType, entityId, action, from, to), newest first, as CSV. Stops at 50 000
        rows and says so in its last line. Every successful staff write is in the
        trail (T-14.3): the server records one row per POST, PUT, PATCH or DELETE
        answered 2xx, named `entity.verb`, with the method, path and status only.
        Manager-gated. A file: where the business requires a second factor, a session that has
        not typed its code is refused (`403 second_factor_required`, T-37.4).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: actor, in: query, schema: { type: string } }
        - { name: entityType, in: query, schema: { type: string } }
        - { name: action, in: query, schema: { type: string } }
        - { name: from, in: query, schema: { type: integer, format: int64 } }
        - { name: to, in: query, schema: { type: integer, format: int64 } }
      responses:
        "200":
          description: The CSV.
          content:
            text/csv:
              schema: { type: string }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/webhooks/yoco:
    post:
      tags: [Webhooks]
      summary: Yoco payment webhook
      description: |
        Public. Standard-Webhooks (Svix) signature scheme: HMAC-SHA256 over
        `{webhook-id}.{webhook-timestamp}.{raw body}` with the base64 `whsec_` secret, matched against the
        space-separated `v1,<base64>` entries in `webhook-signature`, verified against the raw request body
        before any JSON parsing (timestamp replay window ±3 min). Deduped by the payload's event id — a
        replayed event of any type is acknowledged without reprocessing. Handles `payment.succeeded`
        (captures the matching payment by `payload.metadata.checkoutId`), `payment.failed` (fails it),
        `refund.succeeded` and `refund.failed`. A `refund.succeeded` for one of our payments that Ruva did not make
        itself (a refund made in Yoco's portal) is booked once against the sale, keyed by Yoco's refund id
        (`payload.id`), for `payload.amount`, with the till's own refund cap (the sale's total). A refund Ruva
        made (its leg holds that refund id, or its event's `metadata.ruvaRefundKey` names a leg Yoco never confirmed) is
        not booked again. One that cannot be booked (more than is left, a sale not closed) or that may be one of Ruva's
        own (the same amount as a recent refund of that payment) is acknowledged and kept unhandled with its reason,
        and the order is listed in `GET /sales/orders?status=attention` with `heldRefundCents`. `refund.failed` books
        nothing new: kept against its payment, it is the outcome of the leg of Ruva's own refund it names — by `payload.id`
        when Yoco's refund call answered a refund id, else by `metadata.ruvaRefundKey` — and that leg's share is taken back
        off the books once (a refund row of the sale with a positive total, and its journal), so the order, Trading, the
        VAT201 and the refund cap all read it. The order is listed under `attention` with `unpaidRefundCents` until a person
        answers it (`POST /sales/orders/{id}/refund-checks`). An event naming no payment of ours is acknowledged and books nothing. Rate limit bucket `webhook`: 1000 requests/min.
      x-rate-limit: "webhook: 1000/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, description: "Raw Yoco event payload — verified as text before parsing." }
      responses:
        "200":
          description: Acknowledged (processed, or already-seen and skipped).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "503":
          description: A refund event could not be booked just now; Yoco sends it again and it is booked once.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "400":
          description: Payload was not valid JSON.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "401":
          description: Signature mismatch.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/payments/yoco/webhook/{tenant}:
    post:
      tags: [Webhooks]
      summary: A venue's own Yoco webhook
      description: |
        Public. Where Yoco posts a venue's own events (T-2.1): the URL Settings → Payments' Test connection
        registers with Yoco under the venue's own key. Verified exactly as `/api/v1/webhooks/yoco` is, but with the
        signing secret Yoco gave that venue's registration, and it can move only that venue's payments and booking
        deposits: an event naming another venue's checkout is acknowledged and applied to nothing; a refund made in the
        venue's Yoco portal is booked against its sale once, as on the global path. An unknown venue,
        or one with no connected Yoco account, answers 401 exactly as a bad signature does. Rate limit bucket
        `webhook`: 1000 requests/min.
      x-rate-limit: "webhook: 1000/min"
      security: []
      parameters:
        - { name: tenant, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, description: "Raw Yoco event payload — verified as text before parsing." }
      responses:
        "200":
          description: Acknowledged (processed, or already-seen and skipped).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "503":
          description: A refund event could not be booked just now; Yoco sends it again and it is booked once.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "400":
          description: Payload was not valid JSON.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "401":
          description: Signature mismatch, or no connected Yoco account at this path.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/webhooks/snapscan:
    post:
      tags: [Webhooks]
      summary: SnapScan payment webhook
      description: |
        Public, posted by SnapScan: a form body with the payment object as JSON under `payload`, signed
        `Authorization: SnapScan signature=<hex>` — HMAC-SHA256 of the raw body. The key is that of the business
        whose payment `merchantReference` names (its own webhook authentication key; the deployment's for the demo
        business); a notice naming no payment of ours is acknowledged only when signed by the business whose
        SnapCode it names, and moves nothing. A verified notice is a prompt, not proof: the payment is captured when
        SnapScan's own records (`GET /merchant/api/v1/payments?merchantReference=`, under the business's API key) show
        it completed, for the amount, at the business's SnapCode; until they do the answer is 503 and SnapScan resends,
        and Ruva asks again every minute for an hour. Deduped — a repeat capture event for an already-captured payment
        is a no-op. Rate limit bucket `webhook`: 1000 requests/min.
      x-rate-limit: "webhook: 1000/min"
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema: { type: object, properties: { payload: { type: string, description: "SnapScan's payment object as JSON — verified as raw text before it is believed." } } }
      responses:
        "200":
          description: Acknowledged.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "400":
          description: Payload was not valid JSON, or missing an id.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "401":
          description: Not signed with the key of the business whose payment (or SnapCode) it names; nothing written.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "503":
          description: Verified, but SnapScan's own records do not yet show the payment completed (or SnapScan did not answer); the payment stays PENDING.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/webhooks/couriers/{provider}/{tenantId}:
    post:
      tags: [Webhooks]
      summary: A courier reports where a driver is (public, signed)
      description: |
        Public, posted by the courier a venue connected (T-37.9; `UBER_DIRECT`). What authorises it is the hex HMAC-SHA256 of the
        **raw** body under the signing key the venue pasted into Settings → Integrations → Couriers, read from the courier's own
        signature header, and a fresh `created` time inside the signed body (older than 15 minutes, or ahead of our clock, is
        refused). The business is the one in the path; an unknown business or courier, no signing key held, an unsigned call and a
        wrong signature all answer the same `401`, so a probe learns nothing, and nothing is written before the signature holds.
        A verified call moves the delivery it names, forwards only: a late "on the way" after "delivered" changes nothing, and a
        delivered, cancelled or returned delivery is never left. A call about a delivery Ruva does not hold, or about an event it
        does not track, answers 200 with `applied: false`. Rate limit bucket `webhook`: 1000 requests/min.
      x-rate-limit: "webhook: 1000/min"
      security: []
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [UBER_DIRECT] } }
        - { name: tenantId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, description: "The courier's own delivery-status event, signed as sent." }
      responses:
        "200":
          description: Acknowledged; `applied` says whether it moved a delivery.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CourierWebhookAck" }
        "401":
          description: "`bad_signature` — unsigned, wrongly signed, stale, or for a business or courier that does not exist."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "413":
          description: "`payload_too_large` — over 64 KB."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/webhooks/zapper:
    post:
      tags: [Webhooks]
      summary: Zapper payment webhook
      description: |
        Public, and Ruva's own: Zapper is hidden from venues, so a notice moves the demo business's payments only
        and never another business's. HMAC-SHA256 signature in the `x-zapper-signature` header, hex-encoded. If
        `ZAPPER_WEBHOOK_SECRET` is not configured, the endpoint rejects every request with `503` rather than
        accept unverified payment notifications. Rate limit bucket `webhook`: 1000 requests/min.
      x-rate-limit: "webhook: 1000/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, description: "Raw Zapper event payload — verified as text before parsing." }
      responses:
        "200":
          description: Acknowledged.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "400":
          description: Payload was not valid JSON, or missing an id.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "401":
          description: Signature mismatch.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "503":
          description: Webhook secret not configured — provider disabled.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookAck" }
        "429":
          $ref: "#/components/responses/TooManyRequests"

  # ───────────────────────────── Sync ─────────────────────────────
  /api/v1/sync/push:
    post:
      tags: [Sync]
      summary: Push queued offline mutations from a terminal
      description: |
        Each mutation is idempotent by its own `id` (a retried push with the same id is a no-op, never a
        primary-key violation). A mutation that cannot yet be applied (e.g. a referenced row hasn't synced)
        is reported `accepted:false` so the client keeps it queued and retries later. Each mutation also asks
        what its own route asks — of the signed-in role that pushed it, or of the active staff member it names
        as having done it; one that neither may do is answered `refused` and never applied. Rate limit bucket
        `sync`: 600 requests/min.
      x-rate-limit: "sync: 600/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SyncPushRequest" }
      responses:
        "200":
          description: Per-mutation accept/reject results.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SyncPushResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/sync/pull:
    get:
      tags: [Sync]
      summary: Pull server-side changes since a cursor
      description: "Cursor-based pull — pass the `nextCursor` from the previous response as `since` on the next call. A person's sign-in only, never a device's. A staff row's `hourly_rate_cents` is 0 unless the caller may see pay rates. Rate limit bucket `sync`: 600 requests/min."
      x-rate-limit: "sync: 600/min"
      parameters:
        - name: since
          in: query
          description: Cursor (sync version watermark). Defaults to `0` (full pull).
          schema: { type: integer, format: int64, default: 0 }
      responses:
        "200":
          description: Entities changed since the cursor, plus the next cursor to resume from.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SyncPullResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/sync/queue/count:
    get:
      tags: [Sync]
      summary: Get pending/failed counts for this tenant's sync inbox
      description: "The business's inbox across every till: `pending` is received and not yet applied or refused; `failed` is refused (a 4xx, which the till dead-letters) and not applied since. An applied write counts in neither, however often it was replayed. Rate limit bucket `sync`: 600 requests/min."
      x-rate-limit: "sync: 600/min"
      responses:
        "200":
          description: Queue counts.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SyncQueueCount" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/sync/ws:
    get:
      tags: [Sync]
      summary: Real-time event broadcast channel (WebSocket upgrade)
      description: |
        **This is a WebSocket endpoint, not a plain HTTP GET** — connect with a WebSocket client to
        `wss://<host>/api/v1/sync/ws` and this operation upgrades the connection. The tenant is taken from
        the JWT `tid` claim (pass the bearer token as usual during the handshake); the connection is refused
        if the claim is missing. A browser, whose WebSocket cannot send `Authorization`, offers instead the two
        subprotocols `ruva.ticket` and `ruva.ticket.<ticket>` with a ticket from `POST /api/v1/realtime/ticket`
        (never in the URL); the server answers `ruva.ticket`, and the socket is then held exactly as a bearer
        token's. A ticket beside an `Authorization` header is refused. The server pushes JSON-encoded `RuvaEvent`s (e.g. `TableSeated`,
        `KitchenBumped`, `PaymentCaptured`) as they occur — those raised on the server instance the socket is
        connected to, so a client keeps its own poll beside it; inbound client frames are logged but otherwise
        ignored. Not subject to the `sync` rate-limit bucket (outside the `rateLimit` block) and not
        representable as a standard request/response pair — documented here for completeness.
      responses:
        "101":
          description: Switching Protocols — WebSocket connection established.
  /api/v1/realtime/ticket:
    post:
      tags: [Sync]
      summary: A single-use ticket to open the live socket from a browser
      description: |
        T-41.63 — a browser's WebSocket cannot carry `Authorization`, so a signed-in browser asks for a ticket here
        with its bearer token and offers it to `GET /api/v1/sync/ws` as the subprotocol `ruva.ticket.<ticket>` (beside
        `ruva.ticket`). The ticket is random, opens one socket once, within `expiresInSeconds` (at most a minute), and
        is bound to this session, its business and its device registration; the socket it opens is checked exactly
        as a bearer token's, and closes when the session ends. Kept by the server instance that issued it: a client
        refused at the upgrade asks for a fresh one and polls meanwhile. Answered with `Cache-Control: no-store`.
        Needs a permission that hears at least one live event (selling, the kitchen display, the catalogue, the
        floor or the figures).
      x-rate-limit: "socketTicket: 30/min"
      responses:
        "200":
          description: The ticket.
          content:
            application/json:
              schema:
                type: object
                required: [ticket, expiresInSeconds]
                properties:
                  ticket: { type: string, description: "256 random bits, base64url. A credential: never put it in a URL or a log." }
                  expiresInSeconds: { type: integer, maximum: 60 }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429": { description: "More than the `socketTicket` bucket allows from this device in a minute; see `Retry-After`." }

  # ───────────────────────────── Reports ─────────────────────────────
  /api/v1/reports/dashboard/alerts:
    get:
      tags: [Reports]
      summary: What needs a manager now
      description: |
        Derived on every read from the rows that are the fact (T-14.1): stock at or below its reorder point, items
        86'd, signed-in devices silent for five minutes, devices reporting writes the server refused, and delivery
        orders in the period whose payout is not gross less commission, and booking deposits paid whose party's visit is
        over with no bill taking them (`DEPOSIT_UNSPENT`, T-27.1), and booking deposit refunds a person must check with the
        provider — one Yoco never confirmed within a day, one that failed, or a Yoco refund of a deposit Ruva did not owe
        (`DEPOSIT_REFUND_TO_CHECK`). Only kinds with a case, worst first. A kind added after
        apps were installed is sent only when `with` names it; a deposit's example names its guest only to a role holding
        MANAGE_RESERVATIONS (anyone else reads the amount and the booking's time). Needs VIEW_REPORTS.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string }, description: "Omit for every location." }
        - { name: with, in: query, required: false, schema: { type: string }, description: "Comma-separated kinds added later that the client reads: DEPOSIT_UNSPENT, DEPOSIT_REFUND_TO_CHECK." }
        - { name: period, in: query, required: false, schema: { type: string, enum: [today, yesterday, week, month, year] }, description: "Bounds the payout check only." }
      responses:
        "200":
          description: The alerts.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DashboardAlertsResponse" }
        "403": { description: "No VIEW_REPORTS." }
  /api/v1/reports/dashboard/deposit-refunds:
    get:
      tags: [Reports]
      summary: The deposit refunds listed for a person to check, one by one
      description: |
        Each booking deposit refund behind the `DEPOSIT_REFUND_TO_CHECK` alert (rf1 N2): a refund Yoco never confirmed within a day,
        one that failed, a Yoco refund of a deposit Ruva did not owe, or a deposit Ruva's own refund paid after another had settled it.
        Each carries the id `dealt-with` takes and the line the alert shows (the guest named only to a role holding
        MANAGE_RESERVATIONS). Needs REFUND; never a screen signed in as itself.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string }, description: "Omit for every location." }
      responses:
        "200":
          description: The refunds to check.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DepositRefundsToCheck" }
        "403": { description: "No REFUND." }
  /api/v1/reports/dashboard/deposit-refunds/dealt-with:
    post:
      tags: [Reports]
      summary: Say a listed deposit refund was dealt with, and how
      description: |
        A person who may refund says what was done about one listed refund (rf1 N2). A deposit owed for a person (failed, or
        unconfirmed a day on) becomes HANDLED: nothing is owed or sent any more. A held Yoco refund is marked handled. A deposit paid
        back twice is closed by the record alone. Each writes one audit row naming who and what they said; a second tap records
        and moves nothing. Answers the list as it now stands. Needs REFUND, asked before the body is read.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string }, description: "The list answered is this location's; omit for every location." }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DepositRefundDealtWith" }
      responses:
        "200":
          description: The refunds still to check.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DepositRefundsToCheck" }
        "400": { description: "No reason, a reason over 300 characters (`invalid_reason`), or no id (`invalid_id`)." }
        "403": { description: "No REFUND." }
  /api/v1/reports/dashboard/deposit-refunds/confirmed-refunded:
    post:
      tags: [Reports]
      summary: Confirm that a Yoco deposit refund Yoco never confirmed was paid
      description: |
        A person who may refund, having found the refund in Yoco's portal, confirms it (T-43.21). Only a refund listed as
        UNCONFIRMED is taken: the deposit becomes HANDLED, nothing is owed or sent any more, and one audit row
        (`DEPOSIT_REFUND_CONFIRMED`) names who and when; a second tap records and moves nothing. Answers the list as it now stands.
        Needs REFUND, asked before the body is read.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string }, description: "The list answered is this location's; omit for every location." }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DepositRefundConfirmed" }
      responses:
        "200":
          description: The refunds still to check.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DepositRefundsToCheck" }
        "400": { description: "No id (`invalid_id`)." }
        "403": { description: "No REFUND." }
        "409": { description: "Not a Yoco refund Yoco left unconfirmed a day, nor one already confirmed (`not_confirmable`, with what to do instead)." }
  /api/v1/reports/dashboard:
    get:
      tags: [Reports]
      summary: Sales/covers/tips dashboard for a period
      description: |
        Every figure is an owner's (T-14.2): sales, net sales, VAT, refunds, tips, the hourly split and the average
        check are `Trading`'s — the VAT201's own supplies, so a sale refunded later stays on the day it was rung and the
        refund counts as a minus on its own day; `revenueCents` is VAT-inclusive and **excludes tips** (it was the bill
        total, tips included, until T-14.2). Best sellers are `ProductMix`'s: a comped line counts its units at nil.
        `salesDefinition` says this in a sentence. `previous` is the same-length period just before, with the change on
        each figure — the back office's "vs previous period" reads it rather than working out a window of its own.
        `weekBefore` is the same window a week earlier (the same day last week on a day's dashboard) in the same shape,
        its hours included, so a client can draw both against this period's own. While the period is still running, each
        comparison is totalled only up to the same moment of its own period (`totalledUntil`), so like is set against like.
        Requires `VIEW_REPORTS` (a cashier gets 403).
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
        - $ref: "#/components/parameters/CsvFormat"
      responses:
        "200":
          description: Dashboard data (JSON, or a CSV attachment with `format=csv`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DashboardReport" }
            text/csv:
              schema: { type: string }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/tips:
    get:
      tags: [Reports]
      summary: Who is owed what from a period's tips at one location (VIEW_FINANCIALS)
      description: |
        Tips on sales paid in the window, hours from the shifts in it, shared by the location's tip policy (T-3.6, T-35.7).
        A refund's share of a tip is a minus: it comes off the person the sale's tip was left for (or the pool), before anything is shared.
        Payouts plus `heldCents` equal `totalCents` to the cent. The tips are the bills' own (`Trading`, T-14.2): a tip
        on a sale rung offline reached no pool before. Minutes follow `LabourCost` (the break shared across the window).
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: period
          in: query
          required: false
          schema: { type: string, enum: [today, yesterday, week, month, year], default: today }
        - name: from
          in: query
          required: false
          description: Epoch millis; with `until`, overrides `period`.
          schema: { type: integer, format: int64 }
        - name: until
          in: query
          required: false
          schema: { type: integer, format: int64 }
      responses:
        "200":
          description: The report.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TipsReportDto" }
            text/csv: { schema: { type: string } }
            application/pdf: { schema: { type: string, format: binary } }
        "400":
          description: No `locationId` (`missing_locationId`) — tips are shared per location.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: Not a manager (`manager_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/reports/tips/mine:
    get:
      tags: [Reports]
      summary: One person's own share of a period's tips at one location (any signed-in person)
      description: |
        The tips report's own line for the caller and nobody else's, for the till's "Your tips" and a person's phone (T-35.7).
        `staffId` names a till's PIN-signed-in person; naming anyone else asks VIEW_FINANCIALS, as the whole report does.
        Zeros for a person with no tips or hours in the period.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: staffId
          in: query
          required: false
          schema: { type: string }
        - name: period
          in: query
          required: false
          schema: { type: string, enum: [today, yesterday, week, month, year], default: today }
        - name: from
          in: query
          required: false
          schema: { type: integer, format: int64 }
        - name: until
          in: query
          required: false
          schema: { type: integer, format: int64 }
      responses:
        "200":
          description: Their share.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MyTips" }
        "400":
          description: No `locationId` (`missing_locationId`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/reports/x-report:
    get:
      tags: [Reports]
      summary: X-report (unlocked mid-shift snapshot) for a shift
      parameters:
        - name: shiftId
          in: query
          required: true
          schema: { type: string }
        - $ref: "#/components/parameters/CsvFormat"
      responses:
        "200":
          description: X-report (JSON, or a CSV attachment with `format=csv`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/XReport" }
            text/csv:
              schema: { type: string }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/z-report:
    get:
      tags: [Reports]
      summary: Export a shift's Z figures as CSV (read-only)
      description: The shift's aggregates + cash-up numbers WITHOUT the POST side effects (no journal, no shift lock).
      parameters:
        - name: shiftId
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: CSV attachment.
          content:
            text/csv:
              schema: { type: string }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Reports]
      summary: Generate the Z-report and lock the shift
      description: Posts the closing journal entry and locks the shift (`zReportGenerated`). Fails with `409` if already generated for this shift.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ZReportRequest" }
      responses:
        "200":
          description: Z-report generated; shift locked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ZReport" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Z-report already generated for this shift (`error:"z_report_already_generated"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/reports/heatmap:
    get:
      tags: [Reports]
      summary: Day-of-week × hour sales heatmap
      description: Sales per weekday (Sunday = 0) and hour at the venue, from `Trading` (T-14.2); as a 24 × 7 table with `format`.
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - name: days
          in: query
          description: Trailing window size in days. Defaults to `30`. Ignored when `from`+`until` are supplied.
          schema: { type: integer, default: 30 }
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Heatmap grid.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HeatmapReport" }
            text/csv: { schema: { type: string } }
            application/pdf: { schema: { type: string, format: binary } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/qr-insights:
    get:
      tags: [Reports]
      summary: QR insights — scans to orders, where, and what sells
      description: |
        Whether QR ordering is working, where, and what sells (T-4.8): menu scans and QR orders with their conversion per
        day and per table, best sellers on QR, orders by hour, the average order, the average time from paid to ready and
        the guests' average rating. Every figure is read from its owner — sales, orders and hours from `Trading` over the QR
        channel, best sellers from `ProductMix`, paid to ready from `OrderReady`, the rating from `OrderFeedback` and scans
        from the menu-scan counter (a count per table per day; nothing about the guest). `ready` is false until the venue's
        first 20 QR orders. Needs `VIEW_REPORTS`. As a table with `format`.
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: The window's QR insights.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrInsights" }
            text/csv: { schema: { type: string } }
            application/pdf: { schema: { type: string, format: binary } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: The caller may not read reports (`VIEW_REPORTS`).
  /api/v1/reports/server-performance:
    get:
      tags: [Reports]
      summary: Per-server performance breakdown for a period
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Per-server rows, sorted by gross revenue descending.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServerPerformanceReport" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/discounts:
    get:
      tags: [Reports]
      summary: Discount audit log for a period
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Discount log entries.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/DiscountLogEntry" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/voids:
    get:
      tags: [Reports]
      summary: Void audit log for a period
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Void log entries.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/VoidLogEntry" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/comps:
    get:
      tags: [Reports]
      summary: Comp audit log for a period
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Comp log entries.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CompLogEntry" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/concessions:
    get:
      tags: [Reports]
      summary: Discounts, voids and comps as figures for a period (VIEW_REPORTS)
      description: |
        `Concessions`' totals (T-14.2), dated by the bill they were on, beside the period's sales: line and bill
        discounts, comps at the price they were rung at, lines voided off paid bills and bills voided whole. The
        `/discounts`, `/voids` and `/comps` logs list the events themselves, dated when they were keyed.
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: The totals (JSON), or the table as CSV or PDF.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ConcessionsReport" }
            text/csv: { schema: { type: string } }
            application/pdf: { schema: { type: string, format: binary } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/reports/z-history:
    get:
      tags: [Reports]
      summary: Closed registers with the figures saved at each Z (VIEW_FINANCIALS)
      description: |
        `CashUp`'s register history (T-14.2), the same rows as `GET /shifts/history`: opening float, paid in, paid out,
        and the expected cash, count and over/short saved when the Z ran — never recomputed. Expected and over/short
        are withheld where a blind count applies. Up to 1 000 registers, newest first.
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/Period"
        - { name: from, in: query, schema: { type: integer, format: int64 }, description: "Closed at or after (epoch ms). Read as every report reads its window: with `until`, wins over `period`; one without the other is refused. With none of from, until and period, every closed register." }
        - { name: until, in: query, schema: { type: integer, format: int64 }, description: "Closed at or before (epoch ms)." }
      responses:
        "200":
          description: The registers (JSON), or the table as CSV or PDF.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ShiftSummaryDto" } }
            text/csv: { schema: { type: string } }
            application/pdf: { schema: { type: string, format: binary } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: Not a manager (`manager_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/reports/vat201:
    get:
      tags: [Reports]
      summary: SARS VAT201 return figures for an explicit date range
      parameters:
        - name: from
          in: query
          required: true
          description: Epoch millis, inclusive.
          schema: { type: integer, format: int64 }
        - name: until
          in: query
          required: true
          description: Epoch millis, exclusive.
          schema: { type: integer, format: int64 }
        - name: format
          in: query
          required: false
          description: "`csv` for a CSV attachment, `pdf` for the SARS-style VAT201 PDF; omit for JSON."
          schema: { type: string, enum: [csv, pdf] }
        - name: vatNumber
          in: query
          required: false
          description: "The VAT vendor's number: the return sums the locations carrying it (sales, refunds, kept deposits and goods received). Required when the business's locations carry different numbers; without it that business is refused with 409 `vat_numbers_differ`, in every format. An unknown number is 404 `vat_number_unknown`."
          schema: { type: string }
      responses:
        "200":
          description: VAT201 figures (JSON / CSV / PDF per `format`). Input VAT is taken from the posted goods-received notes, at each product's VAT type.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Vat201Report" }
            text/csv:
              schema: { type: string }
            application/pdf:
              schema: { type: string, format: binary }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/menu-engineering:
    get:
      tags: [Reports]
      summary: Menu-engineering quadrant report (STAR/PLOWHORSE/PUZZLE/DOG)
      description: |
        Per active product that sold in the window: units sold, gross revenue,
        recipe-derived cost (waste-adjusted, like the sale stock deduction),
        margin + margin %, popularity rank, and a Kasavana-Smith quadrant using
        a median split of units sold × per-unit contribution margin.
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Menu-engineering report.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MenuEngineeringReport" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/pacing:
    get:
      tags: [Reports]
      summary: Service-pacing report
      description: |
        Average and p90 for order→fire, fire→bump (kitchen time), and
        order→settle (table turn), from order + kitchen-ticket timestamps; plus
        the slowest stations/courses and a count of long-idle occupied tables.
        `availableMetrics`/`unavailableMetrics` report which timers could be
        computed — `seatedToFirstOrder` is unavailable because `tables.seated_at`
        is cleared at settlement.
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
        - name: idleMinutes
          in: query
          required: false
          description: "Occupied-table idle threshold in minutes. Defaults to 90."
          schema: { type: integer, default: 90 }
      responses:
        "200":
          description: Pacing report.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PacingReport" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/kitchen:
    get:
      tags: [Reports]
      summary: Kitchen productivity report (T-5.8)
      description: |
        Prep time and lateness for the kitchen tickets fired in the window, overall, per station,
        per dish (slowest 30) and per hour of the venue's day. Prep time is fired → plated, else
        fired → bumped. A ticket is late by the rule the kitchen boards colour by: past its target
        (its slowest dish's, else its station's), or past `defaultLateMinutes` when it has none.
        A ticket still on the pass counts as late once it is past that and is not judged before,
        so a late percentage is `late / judged`. Targets are today's.

        `staff` (T-36.13) is who bumped those tickets, most bumps first: per row the tickets bumped
        and the average and slowest time from fired to bumped, in seconds. A `PERSON` row is a staff
        member by display name; a `SCREEN` row is a kitchen screen paired as itself that bumped with
        nobody signed in, never a person; every other signed-in `ACCOUNT` is one nameless row, and a
        bump with no one on record is `UNRECORDED`.
      parameters:
        - $ref: "#/components/parameters/Period"
        - $ref: "#/components/parameters/LocationId"
        - $ref: "#/components/parameters/RangeFrom"
        - $ref: "#/components/parameters/RangeUntil"
      responses:
        "200":
          description: Kitchen report.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/KitchenReport" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/products:
    get:
      tags: [Reports]
      summary: Sales by product (V18)
      description: |
        Per-product quantity / revenue / recipe-aware cost / margin in the window, with category + brand for slicing,
        and the total row — all `ProductMix`'s (T-14.2). Comped lines count units at zero revenue; voided lines are
        dropped; a sale refunded later still counts where it was rung. `marginPctBp` is of net sales.
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - { name: period, in: query, required: false, schema: { type: string, enum: [today, yesterday, week, month, year] } }
        - { name: from, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: until, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: locationId, in: query, required: false, schema: { type: string } }
      responses:
        "200":
          description: Rows sorted by revenue descending.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ProductsReport" }
            text/csv: { schema: { type: string } }
            application/pdf: { schema: { type: string, format: binary } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/customers:
    get:
      tags: [Reports]
      summary: Customer analytics (V18)
      description: Sales-with-customer share, unique/new/returning customers, average basket (overall vs with-customer), repeat rate, top 10 customers by revenue.
      parameters:
        - { name: period, in: query, required: false, schema: { type: string, enum: [today, yesterday, week, month, year] } }
        - { name: from, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: until, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: locationId, in: query, required: false, schema: { type: string } }
      responses:
        "200":
          description: The report.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CustomersReport" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/inventory-aging:
    get:
      tags: [Reports]
      summary: Ageing ("dusty") inventory (V18)
      description: Counted stock with no sale in the last `days` days — on hand, stock value (cost × on hand), last sold, days since. Never-sold products carry null lastSoldAt.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
        - { name: days, in: query, required: false, schema: { type: integer, default: 30, minimum: 1, maximum: 3650 } }
      responses:
        "200":
          description: Rows sorted by stock value descending.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/InventoryAgingReport" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reports/accounting-export:
    get:
      tags: [Reports]
      summary: The ledger as a Xero, Sage or Ledgr journal import file
      description: |
        A file: where the business requires a second factor, a session that has not typed its code is refused
        (`403 second_factor_required`, T-37.4).

        The double-entry ledger (journal_entries/journal_lines) posted in
        `[from, until)`, as the named package imports journals. VAT is carried
        once, on the VAT control account's line; no line carries a tax rate the
        package would apply again. Requires VIEW_FINANCIALS.

        - `xero`: Xero's manual-journal import (signed `*Amount`, debit
          positive, dd/mm/yyyy, tax rate "No VAT"), one journal per day netted
          by account; at most 300 lines.
        - `sage`: Sage Accounting's Import Journals template (Reference, Date,
          Description, Nominal Code, Details, Include on VAT/Tax Return? = No,
          Debit, Credit), one journal per Ruva journal; at most 0.5 MB.
        - `ledgr`: Ledgr's transaction-history template, one journal per Ruva
          journal under its id, accounts mapped to Ledgr's standard chart;
          at most 5 000 rows.
      parameters:
        - name: format
          in: query
          required: false
          description: "`xero` (default), `sage` or `ledgr`."
          schema: { type: string, enum: [xero, sage, ledgr], default: xero }
        - name: from
          in: query
          required: true
          description: Epoch millis, inclusive.
          schema: { type: integer, format: int64 }
        - name: until
          in: query
          required: true
          description: Epoch millis, exclusive.
          schema: { type: integer, format: int64 }
      responses:
        "200":
          description: CSV attachment in the requested provider's layout.
          content:
            text/csv:
              schema: { type: string }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "422":
          description: "`export_too_large`: more than the package takes in one import (Xero 300 lines, Sage 0.5 MB, Ledgr 5 000 rows); choose fewer days."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/migration/import:
    post:
      tags: [Reports]
      summary: Import a vendor CSV export or Ruva's menu template (Manager-gated)
      description: |
        Body is the raw CSV text. `vendor` picks the column adapter
        (`lightspeed` | `pilot`, or `template` for Ruva's own menu template:
        Category, Name, Description, Price in rands, and an optional Photo link). `mode=preview` (default) validates and
        returns a PreviewReport without writing; `mode=commit` find-or-creates
        categories per tenant and inserts every valid product row. For `template`, a row naming
        a dish already on the menu (same category and name, any case or spacing) is left as it
        is and counted in `alreadyOnMenu`, so the same file committed twice adds nothing twice;
        the sample menu's dishes don't count as on the menu, and a row sharing the name of a
        sample dish still shown is added beside it, counted in `besideSample` and named in
        `sampleTwins`; a dish the file names again is added once, from its first row, the repeats
        counted in `repeatedInFile` and each such dish named once in `repeatedDishes`;
        a file whose first row has no Name or Price column is refused as a whole in `fileError`.
        Both modes answer `columns` (each column of the file in order: its `header`, the `field` it fills
        or null for none, and up to three `samples`) and `fields` (the field keys this vendor reads); the
        guess is the importer's, by header name. `columns` re-maps them (T-39.21): one field key or `skip`
        per column, comma-separated, in file order (`category,name,skip,price`); every row is then read by
        those fields alone. A choice naming a field twice, leaving out name or price, naming a field the
        vendor does not read or not one per column is refused 400 `columns_refused` with the sentence.
        A template row's Photo link is fetched once on commit (T-41.56) and kept as the dish's photo; one that cannot be
        fetched, or is not a picture, leaves the dish added without it, and the CommitReport's `picturesSkipped` names
        each such row ("Row 3: Curry was added without its picture. …"). Four are fetched at a time, a host that fails
        for now is not asked again in the same import, and fetching stops after 90 seconds: a row not reached by then is
        added without its picture and named the same way.
      parameters:
        - name: vendor
          in: query
          required: true
          schema: { type: string, enum: [lightspeed, pilot, template] }
        - name: mode
          in: query
          required: false
          schema: { type: string, enum: [preview, commit], default: preview }
        - name: columns
          in: query
          required: false
          description: One field key or `skip` per column, comma-separated, in file order. Absent means the importer's guess.
          schema: { type: string, example: "category,name,skip,price,description" }
      requestBody:
        required: true
        content:
          text/csv:
            schema: { type: string }
          text/plain:
            schema: { type: string }
      responses:
        "200":
          description: PreviewReport (mode=preview) or CommitReport (mode=commit).
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/migration/choices:
    post:
      tags: [Reports]
      summary: Import a restaurant's modifier groups, forced choices and prep stations (Manager-gated)
      description: |
        Body is the raw CSV text of Ruva's menu-choices template: one row per option, with `sku` or `product` to find
        the dish, `station` (the dish's prep station), `group`, `min` and `max` (the smallest and largest pick; `1` and
        `1` is a forced choice), `option`, `price` (what the option adds, read like every product price: a whole number
        is rands, a `price_cents` column is cents, a leading minus takes money off) and `option_station`. Dishes must
        already be in the catalogue; this never makes one. `mode=preview` (default) reads the file and counts what a
        commit would add without writing; `mode=commit` adds it. Names are matched inside the business by trimmed,
        case-folded text, a match is found and never rewritten, and a station named in the file that does not exist is
        made once, so a second commit of the same file adds nothing. A row that cannot be used is listed in `errors`
        with its row number and the rest still come in.
      parameters:
        - name: mode
          in: query
          required: false
          schema: { type: string, enum: [preview, commit], default: preview }
      requestBody:
        required: true
        content:
          text/csv:
            schema: { type: string }
          text/plain:
            schema: { type: string }
      responses:
        "200":
          description: >-
            A report of `rowsRead`, `groupsCreated`, `groupsMatched`, `optionsCreated`, `linksCreated`,
            `stationsCreated`, `productsStationed`, `errors` and `warnings`.
        "400":
          $ref: "#/components/responses/BadRequest"
        "413":
          description: The file is larger than 2 MB (`payload_too_large`), refused before it is held.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/ledgr/generate-journals:
    post:
      tags: [Reports]
      summary: Backfill Ledgr sales journals for transactions that arrived without one (MANAGE_INTEGRATIONS)
      description: |
        Ruva → Ledgr bridge. `SalesService.checkout` already posts a `POS_SALE` journal for every server-side
        sale, so this is a backfill for transactions that arrived without one (e.g. offline sales materialised
        via `/sync/push`). Transactions that already carry a `POS_SALE` journal entry are skipped, not
        re-posted, to avoid double-counting revenue. An unbalanced computed entry is also skipped (logged), not
        posted.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/JournalGenerateRequest" }
      responses:
        "200":
          description: Journals generated (with a count of entries generated vs. skipped).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/JournalGenerateResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  # ───────────────────────────── Loyalty & Vouchers ─────────────────────────────
  /api/v1/vouchers:
    get:
      tags: [Loyalty & Vouchers]
      summary: List vouchers for the tenant
      responses:
        "200":
          description: Vouchers, newest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/VoucherDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Loyalty & Vouchers]
      summary: Create a voucher
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/VoucherCreateRequest" }
      responses:
        "201":
          description: Voucher created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/vouchers/redeem:
    post:
      tags: [Loyalty & Vouchers]
      summary: Redeem a voucher against an open order (Manager-gated)
      description: Validates active/date-window/max-uses/min-spend before applying a `PERCENT` (basis points) or `FIXED` discount to the order.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/VoucherRedeemRequest" }
      responses:
        "200":
          description: Voucher redeemed; discount applied.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VoucherRedeemResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Voucher or order not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "Voucher inactive/expired/not-yet-valid/exhausted, below min spend, or order not open (`error:` one of `voucher_inactive`, `voucher_not_yet_valid`, `voucher_expired`, `voucher_exhausted`, `below_min_spend`, `order_not_open`, `vouchers_on_both` — the bill already holds a voucher, and one bill holds one)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/vouchers/{id}:
    post:
      tags: [Loyalty & Vouchers]
      summary: Edit a voucher (Manager-gated, BO-F27)
      description: "Partial update; keep-on-absent. `code` is immutable. Returns the updated voucher."
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/VoucherUpdateRequest" }
      responses:
        "200":
          description: Updated voucher.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VoucherDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/vouchers/{id}/toggle:
    post:
      tags: [Loyalty & Vouchers]
      summary: Activate / deactivate a voucher (Manager-gated, BO-F27)
      description: "Flips the voucher's `active` flag and returns the updated row."
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Updated voucher.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VoucherDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/loyalty/birthday-vouchers:
    post:
      tags: [Loyalty & Vouchers]
      summary: Issue today's birthday vouchers
      description: Issues a 20%-off voucher (valid 30 days) for every customer whose stored birthday (MM-DD) is today in the location's own time zone and whom a campaign rule allows an email (opted in and confirmed). The same job runs by itself each morning (from 07:00 local, once per location per local day; a location may change the time or switch it off); this is the manager's button for it. Once the day's run is done it issues nothing and answers `alreadyDone`. Optional `locationId` query names the location.
      responses:
        "200":
          description: Vouchers issued.
          content:
            application/json:
              schema:
                type: object
                properties:
                  issued: { type: integer }
                  voucherIds: { type: array, items: { type: string } }
                  alreadyDone: { type: boolean, description: "True when today's run was already done, so nothing was issued." }
        "401":
          $ref: "#/components/responses/Unauthorized"

  # ───────────────────────────── Gift Cards ─────────────────────────────
  /api/v1/gift-cards:
    get:
      tags: [Gift Cards]
      summary: Paginated admin browse of issued gift cards (MANAGE_PROMOTIONS)
      parameters:
        - name: status
          in: query
          description: Filter by derived state.
          schema: { type: string, enum: [ACTIVE, REDEEMED, VOIDED, EXPIRED] }
        - name: q
          in: query
          description: Case-insensitive match on code or issued-to name/email/phone.
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, default: 50, minimum: 1, maximum: 200 }
        - name: offset
          in: query
          schema: { type: integer, format: int64, default: 0 }
      responses:
        "200":
          description: Page of gift cards.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GiftCardPage" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Gift Cards]
      summary: Issue a new gift card
      description: |
        A card lasts at least three years from the day it is issued (Consumer Protection Act s63): an `expiresAt` sooner than
        that is refused `400 gift_card_expiry_too_soon` with the earliest day, and one left out is three years. When a card
        expires, what was left on it is released to Gift Card Breakage once.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GiftCardIssueRequest" }
      responses:
        "201":
          description: Gift card issued (includes the generated code).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GiftCardDto" }
        "400":
          description: >-
            Invalid amount; no `paidBy` (`error:"paid_by_required"`, with a sentence asking how the card was paid for); an unknown
            `paidBy` (`invalid_paid_by`); or `paidBy` beside `productId` (`paid_by_with_product`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/gift-cards/{code}:
    get:
      tags: [Gift Cards]
      summary: Look up a gift card's balance and metadata by code
      parameters:
        - name: code
          in: path
          required: true
          schema: { type: string }
        - name: bill
          in: query
          required: false
          description: "The bill the till is about to take this balance on; the answer's drawnForBillCents is what that bill has drawn on it already (T-21.6 review 7 follow-up F2)."
          schema: { type: string }
      responses:
        "200":
          description: Gift card.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GiftCardDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Gift card not found (`error:"gift_card_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/gift-cards/redeem:
    post:
      tags: [Gift Cards]
      summary: Redeem a gift card for a bill
      description: >-
        Draws the amount off the card for the bill `transactionId` names (the open order's id, or `WALK_IN`), once per card and
        `drawId`: send the same `drawId` on every retry of one payment, and a repeat is answered as the first was without drawing
        the card again; a new payment, even of the same bill, amount and card, sends a new one. The same `drawId` for another
        amount or bill is refused 409 `gift_card_redeemed_differently`. A request with no `drawId` claims nothing and draws every
        time. Checkout holds an order's `GIFT_CARD` legs to what was drawn for it.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GiftCardRedeemRequest" }
      responses:
        "200":
          description: Redeemed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GiftCardRedeemResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Gift card not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: Card voided, expired, or insufficient balance.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/gift-cards/{id}:
    post:
      tags: [Gift Cards]
      summary: Change who holds a gift card and its note (MANAGE_PROMOTIONS)
      description: |
        Every field is the new value; a blank one clears it. Never a figure: the balance moves only by a redemption or a void, and
        the expiry is what the card was issued with. A card is addressed by its `id`, not its code.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                issuedToName: { type: string, nullable: true }
                issuedToEmail: { type: string, nullable: true }
                issuedToPhone: { type: string, nullable: true }
                notes: { type: string, nullable: true }
      responses:
        "200":
          description: The card as it now reads.
          content: { application/json: { schema: { $ref: "#/components/schemas/GiftCardDto" } } }
        "400":
          description: An email address with no `@` (`invalid_email`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller lacks MANAGE_PROMOTIONS.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such card in this business (`gift_card_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/gift-cards/{id}/funding:
    post:
      tags: [Gift Cards]
      summary: Declare once how a gift card issued before V342 was funded (REFUND)
      description: |
        A card with no funding on record (`fundingOnRecord` false: issued before what paid for a card was kept, from the back office,
        with no product) can only be moved to a new card. The owner or a REFUND holder declares once how it was funded:
        `paidBy` SOLD_AT_TILL, CASH, CARD, EFT or COMPLIMENTARY. SOLD_AT_TILL is a card whose price was rung up at a till: that sale
        already credited sales, so the issue journal debits Sales (4000) instead of a tender, and the card keeps no tender. The card keeps the rest, its liability is booked from now by posting the issue journal it
        never had for what it still holds (Dr the tender's account, or Sales Discounts for a complimentary card; Cr Gift Cards
        Outstanding), and the declaration is audited `GIFT_CARD_FUNDING_DECLARED` with who. A card paid for by cash, card or EFT may then be
        refunded; a complimentary one never is. A second declaration, or one for a card whose funding is on record, is `409
        gift_card_funding_on_record`; a voided, expired or spent card has nothing to book (`409 gift_card_nothing_to_book`); a card that
        has paid a bill not yet closed and booked (an open bill, or a till's sale still on its way) is `409 gift_card_draw_unbooked`.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GiftCardFundingRequest" }
      responses:
        "200":
          description: The card, now with its funding on record.
          content: { application/json: { schema: { $ref: "#/components/schemas/GiftCardDto" } } }
        "400":
          description: No `paidBy` (`paid_by_required`) or one that is none of the four (`invalid_paid_by`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller lacks REFUND.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such card in this business (`gift_card_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Already declared (`gift_card_funding_on_record`), nothing left to book (`gift_card_nothing_to_book`), or a bill it paid is not booked yet (`gift_card_draw_unbooked`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/gift-cards/{id}/void:
    post:
      tags: [Gift Cards]
      summary: Void what is left on a gift card (MANAGE_PROMOTIONS)
      description: |
        Takes the card's balance to zero, records what it held as `voidedCents` with `voidedAt`, and refuses every later
        redemption (`409 gift_card_voided`). The value is the holder's until the card expires, so the body says how it goes
        back: `REFUND` pays it by a tender (`CASH`, `CARD` or `EFT`; Dr Gift Cards Outstanding, Cr that tender, recorded with who
        and which tender), `TRANSFER` opens a new card carrying it for three years (a movement on each card, no journal), or
        `WITHDRAW` takes back a complimentary card's goodwill (Dr Gift Cards Outstanding, Cr Sales Discounts; nothing paid out).
        A card goes back the way it came (`paidBy` on the card): a complimentary card is never refunded (`409
        gift_card_complimentary`), a bought one only by its own tender (`409 gift_card_other_tender`) and never withdrawn (`409
        gift_card_paid_for`); a card with no `paidBy` on record is refunded by any of the three when it was sold as a product or
        its liability was booked, and otherwise (`fundingOnRecord` false: issued before what paid for a card was kept) only moved
        to a new card (`409 gift_card_funding_unknown`) until its funding is declared (`POST /gift-cards/{id}/funding`, REFUND). A cash refund comes off the voider's open drawer, else the business's
        only one. A
        void never books breakage; a body naming neither is refused `400 hand_back_needed` (or `tender_needed`). Voiding a card
        already voided answers it as it stands. A card spent in full has nothing to void (`409 gift_card_spent`) and an
        expired one has nothing to hand back (`409 gift_card_expired`). A card is not refunded or withdrawn while a bill it, or a
        card it was moved from, paid towards is still open (`409 gift_card_on_open_bill`, naming the bill to close or void first);
        moving it is allowed.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GiftCardVoidRequest" }
      responses:
        "200":
          description: The voided card.
          content: { application/json: { schema: { $ref: "#/components/schemas/GiftCardDto" } } }
        "403":
          description: The caller lacks MANAGE_PROMOTIONS.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such card in this business (`gift_card_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Nothing is left on the card (`gift_card_spent`), or a bill it paid towards is open (`gift_card_on_open_bill`), with a sentence saying so.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }

  # ───────────────────────────── House Accounts ─────────────────────────────
  /api/v1/house-accounts:
    get:
      tags: [House Accounts]
      summary: List house accounts for the tenant
      parameters:
        - name: bill
          in: query
          required: false
          description: "The bill the till is about to take this balance on; the answer's drawnForBillCents is what that bill has drawn on it already (T-21.6 review 7 follow-up F2)."
          schema: { type: string }
      responses:
        "200":
          description: Accounts, newest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/HouseAccountDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [House Accounts]
      summary: Create a house account
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/HouseAccountCreateRequest" }
      responses:
        "201":
          description: Account created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/house-accounts/charge:
    post:
      tags: [House Accounts]
      summary: Post a charge to a house account, from a sale at the till (TILL_SELL)
      description: |
        The first half of a till's House account tender: `transactionId` names the sale it pays (an open order's id, or the id
        the till mints for a walk-in sale and then records that sale under), and the sale's own journal books the debt
        (Dr 1040 Debtors). A charge is posted once per sale: sent again for the same sale, account and amount it answers the
        posting already made (`201`, nothing charged twice); another account or amount is `409 sale_already_charged`.
        Enforces the account's credit limit. A charge naming no sale is refused (`400 sale_required`) unless the session is a
        signed-in device's — an older till — when it is posted and flagged in the audit log (`HOUSE_ACCOUNT_CHARGE_FLAGGED`).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/HouseAccountChargeRequest" }
      responses:
        "201":
          description: Charge posted.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HouseAccountPostingDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: "`exceeds_credit_limit`, `account_closed`, or `sale_already_charged` (the sale holds another account's or amount's charge)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/house-accounts/settle:
    post:
      tags: [House Accounts]
      summary: Post a settlement (payment) against a house account (TILL_SELL)
      description: Refused with `overpays_balance` (409) when it is more than is owed — the balance never goes below zero — and `invalid_method` (400) without CASH, CARD, EFT or YOCO_CARD (the till's card). Posts one balanced journal, HOUSE_ACCOUNT_PAYMENT (T-4.4).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/HouseAccountSettlementRequest" }
      responses:
        "201":
          description: Settlement posted.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HouseAccountPostingDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/house-accounts/{id}:
    post:
      tags: [House Accounts]
      summary: Change a house account's name, contact and credit limit (EDIT_CUSTOMERS)
      description: |
        Every field is the new value; a blank one clears it, but a company or a contact name must remain. A limit of 0 is no
        credit and a limit below what is owed stops further charges until the account is paid down; a negative one is refused.
        The balance is never edited. A closed account is not changed (`409 account_closed`).
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                companyName: { type: string, nullable: true }
                contactName: { type: string, nullable: true }
                contactEmail: { type: string, nullable: true }
                contactPhone: { type: string, nullable: true }
                creditLimitCents: { type: integer, format: int64, nullable: true, description: "The new limit; absent or null leaves it as it is." }
      responses:
        "200":
          description: The account as it now reads.
          content: { application/json: { schema: { $ref: "#/components/schemas/HouseAccountDto" } } }
        "400":
          description: No name, or a negative limit (`name_required`, `invalid_credit_limit`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller lacks EDIT_CUSTOMERS.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such account in this business (`account_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The account is closed (`account_closed`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/house-accounts/{id}/close:
    post:
      tags: [House Accounts]
      summary: Close a house account (EDIT_CUSTOMERS)
      description: |
        Nothing more can be charged to it; it stays listed with its statements. Refused while anything is owed
        (`409 balance_outstanding`, with a sentence naming the amount and the remedy: take a payment with Settle first). Closing
        an account already closed answers it as it stands.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The closed account.
          content: { application/json: { schema: { $ref: "#/components/schemas/HouseAccountDto" } } }
        "403":
          description: The caller lacks EDIT_CUSTOMERS.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such account in this business (`account_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Money is still owed on it (`balance_outstanding`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/house-accounts/{id}/postings:
    get:
      tags: [House Accounts]
      summary: Statement of postings for a house account
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Postings.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/HouseAccountPostingDto" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"

  # ───────────────────────────── Inventory ─────────────────────────────
  /api/v1/house-accounts/{id}/statement:
    get:
      tags: [House Accounts]
      summary: A month's statement (VIEW_CUSTOMERS)
      description: Opening balance (every charge less every payment before the month), the month's postings with the balance after each, and the closing balance — midnight to midnight in Africa/Johannesburg (T-4.4).
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: month, in: query, required: true, schema: { type: string, example: "2026-09" }, description: "YYYY-MM; anything else is 400 invalid_month." }
      responses:
        "200":
          description: The statement.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AccountStatementDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/house-accounts/{id}/statement.pdf:
    get:
      tags: [House Accounts]
      summary: A month's statement as a PDF (EXPORT_DATA)
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: month, in: query, required: true, schema: { type: string, example: "2026-09" } }
      responses:
        "200":
          description: The PDF, drawn from the same statement.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/house-accounts/{id}/statement/send:
    post:
      tags: [House Accounts]
      summary: Send a month's statement by email (with the PDF) or WhatsApp (EXPORT_DATA)
      description: "`to` defaults to the account's email or phone. A channel that is not set up answers 200 with `sent: false` and the remedy; a malformed address, month or channel is 400."
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SendStatementRequest" }
      responses:
        "200":
          description: Whether it went, and if not, why and what to do.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SendStatementResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/inventory/86:
    get:
      tags: [Inventory]
      summary: Current 86 list for a location
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Active 86 entries.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/EightySixEntry" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Inventory]
      summary: 86 a product at a location (mark it unavailable)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EightySixRequest" }
      responses:
        "201":
          description: Product 86'd.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/inventory/86/clear:
    post:
      tags: [Inventory]
      summary: Clear a product from the 86 list (restock)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ClearEightySixRequest" }
      responses:
        "204":
          description: Cleared.
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/inventory/wastage:
    post:
      tags: [Inventory]
      summary: Log wastage/spoilage
      description: |
        Open to all authenticated staff (chefs log wastage directly); the acting user is always recorded even if `byStaffId` is omitted.
        The `reason` is one of the business's own shrinkage reasons (its code; `GET /api/v1/shrinkage/reasons`); wording that
        matches none is filed as `WASTAGE` with the typed words kept in the note. A reason that needs a manager is refused 403
        `manager_required`, one that needs a note 400 `note_required_for_reason`. A product made from a recipe is written off as its
        ingredients; a product that does not track stock is refused 409 `not_stock_tracked`. The write-off is logged loss, so usage
        variance counts it in the reason's family. Sending the same `id` again writes nothing more.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WastageRequest" }
      responses:
        "201":
          description: Wastage recorded and stock decremented.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/inventory/low-stock:
    get:
      tags: [Inventory]
      summary: Products at or below their reorder point
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Low-stock entries.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/LowStockEntry" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/inventory/variant-grid:
    get:
      tags: [Inventory]
      summary: One product's variants as a grid, with stock per cell at a location
      description: >-
        The till's size-by-colour picker. Requires the TILL_SELL permission; it carries no cost,
        value or margin. Active variants only; a variant on no axis is a cell with empty coordinates.
      parameters:
        - name: productId
          in: query
          required: true
          schema: { type: string }
        - name: locationId
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: The grid.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VariantGrid" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/inventory/counted:
    get:
      tags: [Inventory]
      summary: What offline tills share of each counted product at a location
      description: >-
        The till's copy of the count (T-35.6). Requires the TILL_SELL permission. `onHand` is each stock-tracked product's units
        on hand when the server answered (`asOf`, server time), less what the location's open tickets hold; `needs` is what ONE
        portion of a sellable product takes of each of them (a dish's recipe, or a counted product sold as itself); `tills`
        lists the devices selling at the location over the trading day (each one's own check-in said it was showing the till, or
        it is pinned to the till), which cut the count between them when the cloud is out of reach; a phone or browser on the back
        office, a kitchen screen and a kiosk are not tills. With nothing counted at the location every map is empty. A till that loses the cloud refuses a sale past its share, and the
        sale a till already took is never refused when it syncs: the server's count wins and an oversell is flagged once.
        Carries no cost, value or margin.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
      x-rate-limit: "countedStock: 30/min"
      responses:
        "200":
          description: The count.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CountedStock" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429": { description: "More than the `countedStock` bucket allows from this device in a minute; see `Retry-After`." }
  /api/v1/inventory/where-is:
    get:
      tags: [Inventory]
      summary: Which location holds this SKU (needs See stock levels)
      description: >
        Answers "who has this SKU right now" across every location — the question that
        makes a transfer happen. Matches on product name, product SKU or variant SKU;
        a product match implies all of its variants. Variant-aware (V19). `productId`
        answers for that one product (a scanned item, T-4.7); one of the two is required.
        Gated by the VIEW_STOCK permission, not by rank (T-4.7).
      parameters:
        - name: query
          in: query
          required: false
          description: Product name, product SKU or variant SKU (case-insensitive, contains).
          schema: { type: string }
        - name: productId
          in: query
          required: false
          description: One product and its variants, exactly.
          schema: { type: string }
      responses:
        "200":
          description: Matching SKUs with their per-location on-hand.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/WhereIsEntry" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/inventory/replenishment:
    get:
      tags: [Inventory]
      summary: Velocity, cover days, suggested order and dead stock (MANAGE_PURCHASING)
      description: >
        Derives the rate of sale per SKU from the movement ledger and reports cover days —
        how long the shelf lasts at that observed rate — rather than tripping on a static
        reorder point. Only SALE movements count as demand; wastage and count corrections
        are excluded so they cannot inflate a reorder suggestion. `coverDays` is omitted
        when nothing sold, which is a different fact from "lasts forever" and drives the
        `deadStock` flag instead.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: days
          in: query
          description: Observation window in days (1-365).
          schema: { type: integer, default: 30 }
        - name: leadTimeDays
          in: query
          description: Supplier lead time, used to size the suggested order.
          schema: { type: integer, default: 7 }
      responses:
        "200":
          description: One entry per stocked SKU, most urgent first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReplenishmentEntry" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/inventory/usage-variance:
    get:
      tags: [Inventory]
      summary: What sales explain vs what counting found (VIEW_COST)
      description: >
        The shrinkage number. Compares consumption the sales account for (a SALE movement,
        recipe-exploded for composed dishes) against what counting the shelf corrected
        (a STOCK_COUNT movement). The gap is unexplained — over-pouring, unlogged spoilage
        or theft. Logged wastage is reported separately rather than netted off, because
        managed cost and mystery loss are different problems.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: from
          in: query
          description: Period start, epoch millis. Defaults to 30 days ago.
          schema: { type: integer, format: int64 }
        - name: until
          in: query
          description: Period end, epoch millis. Defaults to now.
          schema: { type: integer, format: int64 }
      responses:
        "200":
          description: One entry per SKU with any usage or correction, worst loss first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/UsageVarianceEntry" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  # ── Reorder engine (V46) ──
  /api/v1/reorder/rules:
    get:
      tags: [Inventory]
      summary: Par levels per SKU, with product names
      description: >
        A rule is keyed on (location, product, variant) and records the trigger, the ceiling, the
        safety stock and the review period for one SKU. A SKU with no rule is not thereby excluded
        from replenishment — it is planned from measured velocity and the supplier's lead time
        alone, which is what `GET /reorder/cover` already does for every unruled line. That is why
        `active = false` and "no rule" mean different things, and why deleting a rule is not how a
        manager says "stop ordering this". Needs VIEW_STOCK; the writes below
        are manager-gated because a par level decides how much cash sits on a shelf.
      parameters:
        - name: locationId
          in: query
          required: false
          description: Omit for every location this tenant has.
          schema: { type: string }
        - name: productId
          in: query
          required: false
          schema: { type: string }
      responses:
        "200":
          description: Rules ordered by location, then product.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReorderRule" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Inventory]
      summary: Set one SKU's par levels (MANAGE_PURCHASING)
      description: >
        Keyed on the SKU rather than on an id, because that is how a back-office grid edits: the
        row exists conceptually before it exists in the table, and making the caller discover
        whether to POST or PUT invites the duplicate V46's partial unique indexes would then
        reject. Absent fields are kept, never cleared, so editing a safety stock cannot silently
        reset a review period the form did not resend — and the *merged* result is validated
        rather than the request, or a ceiling below an unchanged trigger would slip through and
        raise a draft PO every morning forever. `humanOverride` defaults to **true** on create
        through this endpoint: someone typed these numbers, and having the next recalculation
        overwrite them is the one outcome that stops a buyer using the feature at all.
        400 codes are `locationId_required`, `productId_required`, `invalid_min_units`,
        `invalid_max_units`, `invalid_safety_stock`, `invalid_review_period`, `max_below_min`,
        `unknown_location`, `unknown_product` and `unknown_variant`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReorderRuleUpsert" }
      responses:
        "200":
          description: An existing rule was updated.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReorderRule" }
        "201":
          description: A new rule was created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReorderRule" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/reorder/rules/recalculate:
    post:
      tags: [Inventory]
      summary: Rewrite par levels from measured demand (MANAGE_PURCHASING)
      description: >
        The answer to four thousand SKUs: nobody maintains that many numbers by hand, so the engine
        maintains them and a human pins the exceptions. A rule carrying `humanOverride` is counted
        and skipped, never recalculated, and an inactive rule is skipped too because it already
        says do not reorder this — both are reported separately so the caller can see how much of
        the range the engine was allowed to touch. `createMissing` is off by default: turning it on
        writes a rule for every SKU with measured demand, which is how a shop bootstraps from
        nothing, and leaving it off means an existing set can be refreshed without the table
        growing by four thousand rows the first time somebody presses the button.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReorderRecalculateRequest" }
      responses:
        "200":
          description: What the pass scanned, wrote and left alone.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReorderRecalculateResult" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/reorder/rules/{id}:
    delete:
      tags: [Inventory]
      summary: Drop a par level (MANAGE_PURCHASING)
      description: >
        The SKU is not thereby excluded from replenishment — it falls back to being planned from
        velocity and the supplier's lead time, which is what every SKU without a rule already gets.
        Setting `active = false` is how a manager says "do not reorder this", and the two are
        deliberately different actions.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`reorder_rule_not_found` — including another tenant's rule."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/reorder/cover:
    get:
      tags: [Inventory]
      summary: Days of stock remaining per SKU, soonest to run out first
      description: >
        Supersedes `GET /inventory/replenishment` rather than replacing it: this one knows about
        par levels, supplier pack sizes and stock already on a truck. Availability is
        `onHand − reserved + inbound`, and inbound counts only SENT and PARTIAL purchase orders —
        a DRAFT has not been sent so nothing is coming, and counting one would suppress a real
        order for as long as a forgotten draft sat open. A SKU with no measured demand has **no**
        `coverDays` at all rather than a sentinel standing in for infinity, which a UI would print
        and a naive sort would rank as either the safest or the most urgent line on the screen.
        Needs VIEW_STOCK — a capability, not a manager's login: "what are we about to run out of"
        is a question a chef or a stock controller asks at four o'clock.
      parameters:
        - name: locationId
          in: query
          required: true
          description: Par levels are per location; a cover view that guessed one would answer the wrong branch's question.
          schema: { type: string }
        - name: windowDays
          in: query
          required: false
          description: >
            Demand observation window. Four weeks by default — long enough that a line selling only
            on Saturdays is measured over four of them, short enough that a genuine change shows.
            Out-of-range values are clamped, not rejected.
          schema: { type: integer, default: 28, minimum: 1, maximum: 365 }
        - name: status
          in: query
          required: false
          description: Narrow to one status. An unrecognised value matches nothing rather than erroring.
          schema: { type: string, enum: [BELOW_REORDER_POINT, COVERED, NO_SUPPLIER, NO_POLICY, RULE_INACTIVE] }
        - name: limit
          in: query
          required: false
          description: Page size, clamped rather than rejected. `totalSkus` counts the filtered set before this cap.
          schema: { type: integer, default: 200, minimum: 1, maximum: 2000 }
      responses:
        "200":
          description: One line per stocked SKU at the location, most urgent first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReorderCoverResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reorder/suggestions:
    get:
      tags: [Inventory]
      summary: Only the lines that need ordering
      description: >
        The same computation and the same response shape as `GET /reorder/cover`, pinned to
        `status = BELOW_REORDER_POINT` — the one status that produces a quantity to buy. A line
        that needs stock but has no active supplier listing it comes back as `NO_SUPPLIER` on the
        cover view and is absent here, because that is a buying decision rather than an arithmetic
        one. `suggestionCount` on the response is the unfiltered total, so a caller can tell "two
        of two hundred need ordering" from "two of two".
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: windowDays
          in: query
          required: false
          description: Clamped, not rejected.
          schema: { type: integer, default: 28, minimum: 1, maximum: 365 }
        - name: limit
          in: query
          required: false
          description: Clamped, not rejected.
          schema: { type: integer, default: 200, minimum: 1, maximum: 2000 }
      responses:
        "200":
          description: Lines that would be ordered, most urgent first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReorderCoverResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/reorder/draft-pos:
    post:
      tags: [Inventory]
      summary: Raise a DRAFT purchase order per supplier (MANAGE_PURCHASING)
      description: >
        **Nothing here sends a purchase order.** Status is DRAFT and nothing in this endpoint
        changes it; a manager reviews the quantities and presses send on the existing PO screen.
        An engine that emailed suppliers off a velocity calculation would have to be right every
        time, whereas one that fills in a form a buyer checks only has to be useful.

        Running it twice must not order twice. The guard is at most one open generated draft per
        (location, supplier), **reused rather than replaced**: a second run finds the existing
        draft and appends only the SKUs not already on it, leaving every existing line exactly as
        it is, quantity included. A buyer who trimmed a line from 40 cases to 12 must not find it
        back at 40 — that is the single behaviour that would teach them never to press the button
        again. Inbound quantities cannot serve as that guard, because a DRAFT is deliberately not
        inbound, so V46's `reorder_generated_pos` records which POs are the engine's and a
        hand-raised draft is never adopted and filled with thirty more lines.

        PO numbers are allocated between two transactions, exactly as `/purchase-orders` does, and
        only for suppliers without an open generated draft — burning a number per supplier per run
        would leave visible gaps in a bookkeeper's sequence. A supplier whose draft was sent by
        somebody else mid-run comes back in `skippedSuppliers` rather than getting a second PO:
        its stock is now inbound, so the next run will not suggest it again.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GenerateDraftPosRequest" }
      responses:
        "200":
          description: One entry per supplier a draft was created for or appended to. Empty when nothing is below its reorder point.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GenerateDraftPosResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  /api/v1/recipes:
    get:
      tags: [Inventory]
      summary: Every recipe with its ingredient lines and costs
      description: >
        Recipes drive two behaviours that have shipped since V1: selling a dish deducts its
        ingredients, and an ingredient reaching zero takes the dish off sale everywhere.
        `perSaleUnits` on each line is what one sale actually deducts, after yield and waste.
      responses:
        "200":
          description: Recipes for this tenant.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Recipe" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Inventory]
      summary: Create or replace a product's recipe (Manager-gated)
      description: >
        Replace-not-patch: send the whole recipe and the server makes it true in one
        transaction. A product has at most one recipe, so the productId is the identity.
        `costCents` is always derived server-side from ingredient costs and is ignored if sent.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RecipeUpsertRequest" }
      responses:
        "200":
          description: Existing recipe replaced.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Recipe" }
        "201":
          description: Recipe created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Recipe" }
        "400":
          description: >
            empty_recipe · invalid_yield · invalid_waste_pct · invalid_quantity ·
            duplicate_ingredient · self_referencing_ingredient · unknown_product
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/recipes/{productId}:
    delete:
      tags: [Inventory]
      summary: Remove a product's recipe (Manager-gated)
      description: >
        The dish stops deducting ingredients and stops being auto-86'd. Stock already
        recorded is unaffected.
      parameters:
        - name: productId
          in: path
          required: true
          schema: { type: string }
      responses:
        "204":
          description: Removed.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: recipe_not_found
  /api/v1/inventory/adjust:
    post:
      tags: [Inventory]
      summary: Manual stock adjustment with a reason (ADJUST_STOCK)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AdjustmentRequest" }
      responses:
        "201":
          description: Adjustment recorded.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "400":
          description: "invalid_unit_cost: a unit cost below nothing."
        "409":
          description: "second_approver_required: the write-off, with what the caller wrote off at the location in the last 24 hours, is at or over the approval figure. Send it again with another manager's PIN in approverPin. Nothing was moved."

  # ───────────────────────────── Suppliers & Purchasing ─────────────────────────────
  # ───────────────────────── Stock transfers (V18) ─────────────────────────
  /api/v1/stock-transfers:
    get:
      tags: [Inventory]
      summary: List inter-location stock transfers (V18)
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string }, description: "Either side of the move" }
        - { name: status, in: query, required: false, schema: { type: string, enum: [DRAFT, IN_TRANSIT, RECEIVED, CANCELLED] } }
      responses:
        "200":
          description: Transfers, newest first (max 100), lines included.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/StockTransferDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Inventory]
      summary: Create a DRAFT transfer (V18, ADJUST_STOCK)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StockTransferCreateRequest" }
      responses:
        "201":
          description: Draft created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string }, transferNumber: { type: string } } }
        "400":
          description: same_location / no_lines / invalid_quantity / unknown_location / unknown_product.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/stock-transfers/{id}:
    get:
      tags: [Inventory]
      summary: One transfer with lines (V18)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The transfer.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StockTransferDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/stock-transfers/{id}/send:
    post:
      tags: [Inventory]
      summary: Send a DRAFT transfer (V18, ADJUST_STOCK)
      description: |
        DRAFT → IN_TRANSIT. Writes TRANSFER_OUT movements + decrements source stock levels atomically; runs the auto-86 sweep at the source.
        A device sends a body with its `opId` (T-8.1); the same op again answers the transfer's status and moves nothing. No body is the back office's send.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StockTransferSendRequest" }
      responses:
        "200": { description: Now IN_TRANSIT. }
        "400":
          description: "`occurredAt` outside the last 7 days (`error:\"invalid_occurred_at\"`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Not a DRAFT (`error:"transfer_not_draft"`), or the op id was used for other work (`error:"op_id_conflict"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/stock-transfers/{id}/receive:
    post:
      tags: [Inventory]
      summary: Receive an IN_TRANSIT transfer (V18, ADJUST_STOCK)
      description: |
        IN_TRANSIT → RECEIVED. `receiveAll: true` (default) receives every line in full; otherwise pass
        per-line received units. Writes TRANSFER_IN movements + increments destination stock by the
        RECEIVED units — short receipts implicitly record shrinkage-in-transit. A device's `opId` (T-8.1)
        makes the same op arriving again answer the status and move nothing.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StockTransferReceiveRequest" }
      responses:
        "200": { description: Now RECEIVED. }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Not IN_TRANSIT (`error:"transfer_not_in_transit"`), or the op id was used for other work (`error:"op_id_conflict"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/stock-transfers/{id}/cancel:
    post:
      tags: [Inventory]
      summary: Cancel a DRAFT transfer (V18, ADJUST_STOCK)
      description: Only DRAFTs cancel — once sent, stock has left the source, so receive (possibly short) instead.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200": { description: Cancelled. }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Not a DRAFT (`error:"transfer_not_draft"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ─────────────────────────── Store credit (V18) ───────────────────────────
  /api/v1/customers/{id}/store-credit:
    get:
      tags: [Customers]
      summary: Store-credit balance (V18)
      parameters:
        - $ref: "#/components/parameters/PathId"
        - name: bill
          in: query
          required: false
          description: "The bill the till is about to take this balance on; the answer's drawnForBillCents is what that bill has drawn on it already (T-21.6 review 7 follow-up F2)."
          schema: { type: string }
      responses:
        "200":
          description: Current balance.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StoreCreditBalance" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Customers]
      summary: Adjust store credit (V18, Manager-gated)
      description: Positive or negative delta with a reason; every change writes an audit movement. Overdrawing returns 409 insufficient_credit.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StoreCreditAdjustRequest" }
      responses:
        "200":
          description: New balance.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StoreCreditBalance" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Overdraw (`error:"insufficient_credit"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/customers/{id}/store-credit/redeem:
    post:
      tags: [Customers]
      summary: Redeem store credit at the till (V18)
      description: Atomic decrement — the till redeems server-first, then records the STORE_CREDIT payment leg.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StoreCreditRedeemRequest" }
      responses:
        "200":
          description: New balance after redemption.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StoreCreditBalance" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: Balance can't cover it (`error:"insufficient_credit"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/customers/{id}/store-credit/movements:
    get:
      tags: [Customers]
      summary: Store-credit audit trail (V18)
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Movements, newest first (max 100).
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/StoreCreditMovementDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"

  /api/v1/suppliers:
    get:
      tags: [Suppliers & Purchasing]
      summary: List suppliers
      responses:
        "200":
          description: Suppliers, ordered by name.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/SupplierDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Suppliers & Purchasing]
      summary: Create a supplier
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SupplierCreateRequest" }
      responses:
        "201":
          description: Supplier created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/suppliers/{id}:
    post:
      tags: [Suppliers & Purchasing]
      summary: Update a supplier (MANAGE_PURCHASING, BO-F32)
      description: "Partial update incl. the `active` flag; keep-on-absent. Returns the updated supplier."
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SupplierUpdateRequest" }
      responses:
        "200":
          description: Updated supplier.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SupplierDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/purchase-orders:
    get:
      tags: [Suppliers & Purchasing]
      summary: List purchase orders
      parameters:
        - name: status
          in: query
          description: "Filter, e.g. DRAFT | SENT | RECEIVED."
          schema: { type: string }
      responses:
        "200":
          description: Purchase orders, newest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PurchaseOrderDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Suppliers & Purchasing]
      summary: Draft a new purchase order
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PoCreateRequest" }
      responses:
        "201":
          description: PO drafted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  poNumber: { type: string }
                  totalCents: { type: integer, format: int64 }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/purchase-orders/{id}:
    get:
      tags: [Suppliers & Purchasing]
      summary: Get full purchase-order detail
      description: Header (with resolved `supplierName`) plus every line (with resolved `productName`) in one call — the back-office PO screen.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: Purchase-order detail.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PurchaseOrderDetailDto" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Purchase order not found (`error:"po_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: [Suppliers & Purchasing]
      summary: Change a purchase order's expected date, notes and lines (MANAGE_PURCHASING)
      description: |
        Only while the order is DRAFT or SENT and nothing has arrived against it: no line received (`409 po_received`), no
        goods-received note in progress (`409 po_receipt_open`), no supplier invoice recorded against it (`409 po_invoiced`), and
        not cancelled (`409 po_cancelled`). Each refusal carries a sentence saying why and what to do instead. Every field is the
        new value. A line sent with its `id` is kept under that id (so a device holding the order still finds it); one without
        is added; a line left out is removed — unless a goods-received note or a supplier invoice names it (`409 po_line_in_use`). A
        line carries 1 to 9 999 of an item at a unit cost of R 0.00 to R 10 000 000, and an order at most 500 lines. The total is
        recomputed.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [lines]
              properties:
                expectedAt: { type: integer, format: int64, nullable: true }
                notes: { type: string, nullable: true }
                lines:
                  type: array
                  items:
                    type: object
                    required: [productId, quantityUnits, unitCostCents]
                    properties:
                      id: { type: string, nullable: true }
                      productId: { type: string }
                      quantityUnits: { type: integer, format: int64 }
                      unitCostCents: { type: integer, format: int64 }
      responses:
        "200":
          description: The order as it now reads.
          content: { application/json: { schema: { $ref: "#/components/schemas/PurchaseOrderDto" } } }
        "400":
          description: No lines, too many (`too_many_lines`), a line outside the bounds (`invalid_line`), an unknown product or a line not on this order.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such order in this business (`po_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The order can no longer be changed (`po_received`, `po_receipt_open`, `po_invoiced`, `po_cancelled`, `po_not_open`), or a line being removed is named by a document (`po_line_in_use`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/purchase-orders/{id}/cancel:
    post:
      tags: [Suppliers & Purchasing]
      summary: Cancel a purchase order (MANAGE_PURCHASING)
      description: |
        Only while it is DRAFT or SENT and nothing has arrived against it, with the same refusals as a change. A cancelled order
        takes no delivery: receiving against it, capturing or posting a goods-received note for it, and sending it again are
        each refused `409 po_cancelled`. Cancelling an order already cancelled answers it as it stands.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The cancelled order.
          content: { application/json: { schema: { $ref: "#/components/schemas/PurchaseOrderDto" } } }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such order in this business (`po_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Goods have arrived, a receipt or invoice stands against it (`po_received`, `po_receipt_open`, `po_invoiced`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/purchase-orders/{id}/send:
    post:
      tags: [Suppliers & Purchasing]
      summary: Mark a draft purchase order SENT
      description: Sending an order already sent changes nothing. A cancelled order is refused `409 po_cancelled`, never revived; one part- or fully received is refused `409 po_not_draft`.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "204":
          description: Marked SENT.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: No such order in this business (`po_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The order is cancelled or already received (`po_cancelled`, `po_not_draft`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/purchase-orders/{id}/receive:
    post:
      tags: [Suppliers & Purchasing]
      summary: Receive goods against a purchase order
      description: |
        With no request body (or an empty one), creates a stock-in movement for every line's full outstanding
        (not-yet-received) quantity and marks the PO `RECEIVED`. With a `PoReceiveRequest` body, receives only the
        given `{lineId, receivedQty}` pairs — each `lineId` must belong to this PO and `receivedQty` must be in
        `1..outstanding` for that line — and the PO becomes `RECEIVED` only once every line is fully received,
        otherwise `PARTIAL`. Needs `RECEIVE_STOCK`.

        A device sends its `opId` (T-8.1): the same op arriving again — a retry, or its replay from the outbox —
        receives nothing and answers `replayed: true`, so a partial receipt is never booked twice.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PoReceiveRequest" }
      responses:
        "200":
          description: Goods received.
          content:
            application/json:
              schema:
                type: object
                properties:
                  linesReceived: { type: integer }
                  lots: { type: array, items: { type: string }, description: "Lot codes created by this receipt." }
                  replayed: { type: boolean, description: "This op id had already landed; this call received nothing." }
                  grnNumber: { type: string, nullable: true, description: "The POSTED goods-received note this receipt wrote (T-8.2). Null when nothing was received, or on a replay." }
        "400":
          description: A requested `lineId` isn't on this PO, `receivedQty` is out of range, or `occurredAt` is outside the last 7 days (`error:"line_not_in_po"`, `"invalid_received_qty"` or `"invalid_occurred_at"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: Purchase order not found (`error:"po_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: The op id was already used for other work (`error:"op_id_conflict"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/receiving/invoices/{id}/image:
    put:
      tags: [Suppliers & Purchasing]
      summary: Attach a photo of the paper invoice
      description: |
        One photo per supplier invoice (T-8.2); a second replaces the first. PNG, JPEG or WebP, judged by the file's
        bytes rather than its stated type, and at most 2 MB (core `InvoicePhoto`). Manager-gated, as recording the
        invoice is. What is kept is a re-encoded JPEG, never the upload: at most 2400 px on its long side (a page of print
        stays readable; a smaller picture is not enlarged) and with none of the camera's data (T-2.14). `mime` in the answer is
        the type kept.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                imageBase64: { type: string }
                mime: { type: string, description: "image/png | image/jpeg | image/webp" }
              required: [imageBase64, mime]
      responses:
        "200":
          description: Stored.
          content:
            application/json:
              schema:
                type: object
                properties:
                  invoiceId: { type: string }
                  mime: { type: string }
                  byteSize: { type: integer }
        "400":
          description: Not a readable picture, not base64 (`error:"invalid_image"`, with the reason), or over the size cap (`error:"image_too_large"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: No such invoice for this business (`error:"invoice_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    get:
      tags: [Suppliers & Purchasing]
      summary: The photo of the paper invoice
      description: The kept (re-encoded) bytes, served with their type. An invoice header's `hasPhoto` says whether there is one. A photo attached before Ruva re-encoded invoice photos answers `404 invoice_photo_not_found` until it has been, within the hour.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The picture.
          content:
            image/jpeg: { schema: { type: string, format: binary } }
            image/png: { schema: { type: string, format: binary } }
            image/webp: { schema: { type: string, format: binary } }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: The invoice has no photo, or is not this business's (`error:"invoice_photo_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/purchase-orders/receivable:
    get:
      tags: [Suppliers & Purchasing]
      summary: Purchase orders a device can receive against at a location
      description: |
        SENT and PARTIAL orders at `locationId`, each with its lines' ordered and received units (T-8.1). What a
        device mirrors to book deliveries in offline; `receivedUnits` is the figure a receipt adds to, so what is
        outstanding on the device is exactly what the server will accept. Needs `RECEIVE_STOCK`.
      parameters:
        - { in: query, name: locationId, required: true, schema: { type: string } }
      responses:
        "200":
          description: Receivable orders, oldest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReceivableOrder" } }
        "400":
          description: No `locationId` (`error:"missing_location"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  # ───────────────────────────── Pricing ─────────────────────────────
  /api/v1/pricing/rules:
    get:
      tags: [Pricing]
      summary: List time-based pricing rules for the tenant
      responses:
        "200":
          description: Rules.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PriceRuleDto" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Pricing]
      summary: Create a pricing rule (happy hour, lunch special, day-of-week promo)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PriceRuleCreateRequest" }
      responses:
        "201":
          description: Rule created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/pricing/rules/{id}/toggle:
    post:
      tags: [Pricing]
      summary: Activate or deactivate a pricing rule
      parameters:
        - $ref: "#/components/parameters/PathId"
        - name: active
          in: query
          schema: { type: boolean, default: true }
      responses:
        "204":
          description: Toggled.
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/customer-groups/{id}/delete:
    post:
      tags: [Customers]
      summary: Remove a pricing group (Manager)
      description: |
        Removes the group (`deletedAt` set, `active` false): it leaves `GET /customer-groups`, its name is free again, and it can
        no longer be given to a customer or a price list. Refused while a customer (not removed) or a live price list uses it.
        A sale keeps the price it was charged, never the group. Removing a group already removed answers the same.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200": { description: The group is removed. }
        "403":
          description: The caller is not a manager (`manager_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such group in this business (`group_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Customers or price lists still use it (`group_in_use`); the message names how many and the remedy.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/pricing/rules/{id}/delete:
    post:
      tags: [Pricing]
      summary: Remove a price rule (EDIT_PRICES)
      description: |
        Removes the rule (`deletedAt` set, `active` false, `updated_at` moved) so a till's next pull switches it off and
        `GET /pricing/rules` no longer lists it; it cannot be switched back on. A sale keeps the price it was charged. Refused
        for a rule a markdown made, which the markdown switches by its id. Removing a rule already removed answers the same.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200": { description: The rule is removed. }
        "403":
          description: The caller lacks EDIT_PRICES (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such rule in this business (`rule_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: A markdown made it (`rule_made_by_markdown`); the message says to end the markdown instead.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/promotions/{id}/delete:
    post:
      tags: [Promotions]
      summary: Remove a promotion never given (Manager)
      description: |
        Removes a promotion no sale has been given (`deletedAt` set, `active` false, `sync_version` bumped) so tills stop
        offering it and the list no longer shows it. One given on any sale stays on record and may only be paused. Removing a
        promotion already removed answers the same.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200": { description: The promotion is removed. }
        "403":
          description: The caller is not a manager (`manager_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such promotion in this business (`promotion_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: It has been given on a sale (`promotion_used`); the message says to pause it instead.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/vouchers/{id}/delete:
    post:
      tags: [Loyalty & Vouchers]
      summary: Remove a voucher never redeemed (MANAGE_PROMOTIONS)
      description: |
        Removes a voucher nobody has redeemed (`deletedAt` set, `active` false): it leaves the list, is never accepted, and its
        code may be issued again. A redeemed voucher stays on record and may only be disabled. Removing a voucher already
        removed answers the same.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200": { description: The voucher is removed. }
        "403":
          description: The caller lacks MANAGE_PROMOTIONS (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such voucher in this business (`voucher_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: It has been redeemed (`voucher_used`); the message says to disable it instead.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/suppliers/{id}/delete:
    post:
      tags: [Suppliers]
      summary: Remove a supplier nothing was bought from (MANAGE_PURCHASING)
      description: |
        Removes a supplier with no purchase order, delivery, invoice, return, stock batch, consignment, special order or
        serial-numbered unit on record (`deletedAt` set, `active` false). A product that named them as its supplier names none
        afterwards. One with any of those records stays and may only be deactivated. Removing a supplier already removed
        answers the same.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200": { description: The supplier is removed. }
        "403":
          description: The caller lacks MANAGE_PURCHASING (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such supplier in this business (`supplier_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Buying from them is on record (`supplier_used`); the message says to deactivate them instead.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/checklists/{id}/delete:
    post:
      tags: [Checklists]
      summary: Remove a checklist never run (Manager)
      description: |
        Removes a checklist no location has run (`deletedAt` set, `active` false, `sync_version` bumped): it leaves
        `GET /checklists` and cannot be opened. One that has been run stays on record and may only be deactivated. Removing a
        checklist already removed answers the same.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200": { description: The checklist is removed. }
        "403":
          description: The caller is not a manager (`manager_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such checklist in this business (`checklist_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: It has been run (`checklist_used`); the message says to deactivate it instead.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/custom-fields/{id}:
    post:
      tags: [Catalogue]
      summary: Change a custom field (Manager)
      description: |
        Keep-on-absent: every field left out of the body keeps its stored value. A change of kind, or dropping an option, is
        refused while any stored answer would no longer fit (`existing_values_invalid`), and a key another field of the same
        kind already uses is refused too.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                key: { type: string }
                label: { type: string }
                type: { type: string, enum: [TEXT, NUMBER, BOOL, DATE, SELECT] }
                options: { type: array, items: { type: string } }
                required: { type: boolean }
                sortOrder: { type: integer }
                active: { type: boolean }
      responses:
        "200": { description: The field is changed. }
        "400":
          description: The definition is not valid; the code names what.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller is not a manager (`manager_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such field in this business.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: Stored answers would no longer fit (`existing_values_invalid`), or the key is taken.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
    delete:
      tags: [Catalogue]
      summary: Remove a custom field and every answer to it (Manager)
      description: |
        Deletes the definition and every stored answer to it; the answer says how many answers went (`valuesDiscarded`).
        A category template that named it stops asking for it. This cannot be undone.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: The field is removed.
          content:
            application/json:
              schema: { type: object, properties: { valuesDiscarded: { type: integer } } }
        "403":
          description: The caller is not a manager (`manager_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such field in this business, or it was removed already.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/pricing/effective/{productId}:
    get:
      tags: [Pricing]
      summary: Get the current effective price for a product
      description: Applies the highest-priority active rule matching now (PRODUCT scope beats CATEGORY beats ALL; ties broken by creation order).
      parameters:
        - name: productId
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Effective price.
          content:
            application/json:
              schema:
                type: object
                properties: { productId: { type: string }, priceCents: { type: string } }
        "401":
          $ref: "#/components/responses/Unauthorized"

  # ───────────────────────────── Customer QR ─────────────────────────────
  /api/v1/brand:
    get:
      tags: [Customer QR]
      summary: The venue's brand on guest surfaces
      description: |
        Any signed-in role. The accent colour (`#RRGGBB`) and the logo and cover the QR menu shows; null means the
        product's own. A colour too light to read is darkened when drawn, never when stored. `logoImageUrl` and
        `coverImageUrl` say where an uploaded picture is served from (`POST /brand/image/{kind}`) — the only logo and
        cover a guest is sent (T-41.56). `logoUrl`/`coverUrl` read back null once a link is copied in; one stored before then and not yet copied is returned to the owner's form only, and not once its kind has an upload.
      responses:
        "200":
          description: The brand.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BrandDto" }
    post:
      tags: [Customer QR]
      summary: Set the venue's brand
      description: |
        Manager roles only. `accentHex` must be `#` and six hex digits (`400 invalid_accent`); `logoUrl` and `coverUrl`
        must be a full https link of at most 500 characters (`400 invalid_logo_url`, `invalid_cover_url`). A link is
        fetched once from the public web and stored as the upload of its kind (T-41.56), then not kept; a blank or absent
        one leaves the upload as it is. `400 picture_unreachable` (We couldn't fetch that picture. Upload it instead, or
        check the link opens in a browser.) when a link cannot be fetched or redirects to an address that is not public,
        and `400 invalid_image`/`image_too_large` in the upload's words. A logo and cover given together are both fetched
        and judged before either is stored: a refusal of one changes nothing, the colour included. A link equal to the one
        already stored for its kind (saved before T-41.56, not copied in yet) is not fetched: it is left for the copy-in job,
        and the rest of the save goes ahead.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BrandDto" }
      responses:
        "200":
          description: The brand as stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BrandDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/brand/domain:
    get:
      tags: [Customer QR]
      summary: The venue's own ordering address and the DNS record that proves it (not offered)
      description: |
        **A venue's own domain is not offered (D-226)**: this answers an empty status (`host` null), and claiming or
        checking one is `409 custom_domain_not_offered`. What follows is how it works when offered.
        Manager roles only. The host is the newest domain the venue named (`POST /brand/domain`) and has not yet
        proved, else its newest proved one, else the host of an ordering address stored before table codes stopped
        taking typed addresses (D-204); `host` is null when there is none. Publish a TXT record named `recordName`
        with the value `recordValue`, then call verify. Once verified, that host's "/" is the venue's menu page and
        its `/?loc=` codes open guest ordering — for the venue's own locations only. `inUse` is whether new table
        codes are printed on it; a proved domain is chosen for them through `/qr-ordering/site`. A certificate for
        the host is set up by Ruva's hosting.
      responses:
        "200":
          description: Where the address stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DomainStatusDto" }
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Customer QR]
      summary: Name the domain the venue wants guests to order at (refused, not offered)
      description: |
        **Refused while a venue's own domain is not offered (D-226)**: `409 custom_domain_not_offered`, before the body is read.
        Manager roles only. A claim, which moves no table code: the codes change only once the domain is proved
        (verify) and chosen. Lets go of every other host but the one new codes are printed on now, so a domain with
        codes on the tables keeps answering. `400 invalid_domain` for anything that is not a domain name; `400 domain_is_ruvas` for Ruva's own name or one under it.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [host]
              properties:
                host: { type: string, example: "order.example.co.za" }
      responses:
        "200":
          description: Where the address stands now, with the record to publish.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DomainStatusDto" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: "`custom_domain_not_offered`: a venue's own domain is not offered (D-226)."
  /api/v1/brand/domain/verify:
    post:
      tags: [Customer QR]
      summary: Check the DNS record and route the host to this venue (refused, not offered)
      description: |
        **Refused while a venue's own domain is not offered (D-226)**: `409 custom_domain_not_offered`, and no host routes to a venue.
        Manager roles only. `409 no_custom_domain` with no domain named; `422 domain_record_not_found` until
        the TXT record carries this venue's value; `409 domain_taken` when another account has already proved the host.
      responses:
        "200":
          description: Verified.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DomainStatusDto" }
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: "`custom_domain_not_offered` (D-226); otherwise no domain named, or the host belongs to another account."
        "422":
          description: The TXT record is not there yet.
  /api/v1/brand/image/{kind}:
    parameters:
      - name: kind
        in: path
        required: true
        description: "`logo` or `cover` (the header picture). Anything else is `400 invalid_image_kind`."
        schema: { type: string, enum: [logo, cover] }
    post:
      tags: [Customer QR]
      summary: Upload the venue's logo or header picture
      description: |
        Manager roles only; a DEVICE never (`403 manager_required`). One of each per business (business-wide, D-84): a new
        upload replaces the old. The type is read from the bytes (PNG, JPEG or WebP), never `mime`. A logo may be up to 5 MB and
        must be at least 128 px on its long edge; a header picture up to 10 MB and at least 1200 px. A file over a limit, not a
        picture, or over 50 megapixels is refused with a sentence saying what to do (`400 invalid_image`, `400 image_too_large`).
        A WebP is accepted only when lossy, small (a logo up to 512 px and 200 KB, a header up to 1600 px and 700 KB), still and
        free of EXIF/XMP/ICC. Every picture, a WebP included, is decoded and stored as a re-encoded derivative with no
        metadata — a PNG for a logo with transparency, otherwise a JPEG — at most 512 px (logo) or 1600 px (header picture)
        on its long edge; no WebP is served as it came. An uploaded picture is what guests see, in place of the https
        address of the same name, which stays as the fallback.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BrandImageUpload" }
      responses:
        "200":
          description: Stored; `url` is where guests are served it from.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BrandImageStored" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "413":
          description: The body is larger than any picture may be (`image_too_large`).
    delete:
      tags: [Customer QR]
      summary: Remove the venue's logo or header picture
      description: Manager roles only. Guests fall back to the https address, if one is set. Removing nothing is not an error.
      responses:
        "200":
          description: Removed; `url` is null.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BrandImageStored" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/brand-images/{tenant}/{kind}:
    get:
      tags: [Customer QR]
      summary: A venue's uploaded logo or header picture (Public)
      description: "Public (no JWT) — the guest menu page's `<img>` tags fetch this directly, at the address the menu's `brand` block carries. Served with `Cache-Control: public, max-age=300`."
      security: []
      parameters:
        - name: tenant
          in: path
          required: true
          schema: { type: string }
        - name: kind
          in: path
          required: true
          schema: { type: string, enum: [logo, cover] }
        - $ref: "#/components/parameters/PictureSize"
      responses:
        "200":
          description: Raw image bytes in the stored type.
          content:
            image/png: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/webp: { schema: { type: string, format: binary } }
        "404":
          description: No such picture (`error:"no_image"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/qr/menu:
    get:
      tags: [Customer QR]
      summary: Get the public menu for a location (self-order)
      description: |
        Public — no JWT required. Rate limit bucket `qr`: 600 requests/min. Hides products currently 86'd at
        the location. Requires the venue's licence to include the **QR Ordering** product (V72), switched on and not lapsed past its grace
        period — otherwise `403 qr_not_licensed`. The response's `features` block tells the guest UI what this venue supports:
        hosted card checkout (Yoco or PayFast), SnapScan (false while it is not offered), and whether "add to my table's bill" exists at all (it needs
        the Restaurant product; standalone QR always pays immediately).
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - name: loc
          in: query
          required: true
          description: Location id (from the table's QR code).
          schema: { type: string }
        - name: table
          in: query
          required: false
          description: The guest's table label (T-3.4). Its zone's price list, when it has one, prices the menu, as it prices the order.
          schema: { type: string }
        - name: scan
          in: query
          required: false
          description: |
            `1` on the guest session's first menu load from a code (T-4.8): counted once for the venue's QR insights, per table
            per day. The phone keeps the flag, so nothing that names it is sent; any other load leaves it out.
          schema: { type: string, enum: ["1"] }
      responses:
        "200":
          description: Menu.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrMenuResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: The venue's licence has no QR Ordering product, it is switched off, or whose licence ended longer ago than its grace period (help centre, Products and licensing) (`error:"qr_not_licensed"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Location not found (`error:"location_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders:
    post:
      tags: [Customer QR]
      summary: Place a self-order from a table QR code
      description: |
        Public — no JWT required. Rate limit bucket `qr`: 600 requests/min. Server re-prices every line from
        the catalogue (client prices are never trusted); an unknown or 86'd product is a `400`. Fires the
        order to the kitchen immediately after creation (same path as the POS "fire course" button).

        `fulfilmentType` (V10) selects eat-in vs takeaway/click-and-collect. `DINE_IN` (default) requires a
        `tableLabel` (a kiosk's eat-in, `channel` `KIOSK` at a location whose kiosk asks eat in or take away, is the exception: its guest sits where they like and is called by number, T-39.11; never for `ADD_TO_TAB`); `TAKEAWAY` makes the table optional and accepts `scheduledForMillis` (order-for-later)
        plus `pickupName`/`pickupPhone`. Takeaway kitchen tickets are badged so the KDS can show "TAKEAWAY"
        and the scheduled pickup time. `DELIVERY` (T-13.3) is a takeaway brought to the guest: it needs
        `pickupName`, `pickupPhone`, `deliveryAddress` and `deliveryPostcode`, pays now, and is quoted as
        `/qr/delivery` quotes — the zone's fee product is added as a line.

        Slots and throttle (T-13.3): a TAKEAWAY or DELIVERY order is placed in a slot of the location's window, as
        `/qr/slots` lists them. A null `scheduledForMillis` is given the first slot with room; a time between two slot
        starts is given the next. The response's `scheduledForMillis` is the slot given. A time not offered is
        `409 slot_closed`, a full slot `409 slot_full`, nothing left `409 no_slot_left`; the `message` is the first
        slot with room (epoch millis) when there is one. Orders racing for the last place are serialised on the
        location's window row, so a slot never takes more than its capacity. Where the location has kitchen hours
        (T-41.42), a time the window offers but the kitchen cannot have ready (after it closes, or sooner after it
        opens than the notice) is `409 kitchen_closed`, `message` the sentence a guest reads naming the first time
        that can be chosen; an order for a later time inside the hours is taken while the kitchen is closed, and
        reaches the kitchen no earlier than it opens.

        `paymentMode` (V72) selects settlement. `PAY_NOW` (default): the order settles online — when Yoco is
        configured the response carries `checkoutUrl` (hosted card checkout, tip included) and the payment
        webhook settles the order the moment it captures. Where the guest must pay on their phone (no till, not
        an order to be paid at the counter, not a phone tab, a total above zero — judged per order, whatever the
        location's counter switch, T-41.100) the order is placed and held from the kitchen,
        and the capture that pays it sends it there, once (D-195); one whose payment is never made is closed
        unpaid and never reaches the kitchen. A till, a counter order, a phone tab and a free order fire at placement;
        a held order sent to the counter because no rail answered fires then.
        `ADD_TO_TAB` (dine-in only, requires the venue's
        licence to include the Restaurant product): the items append to the table's open bill if one exists
        (response `orderId` is that bill, `settlement:"TABLE_BILL"`, `billTotalCents` is the whole bill) or
        become the table's bill otherwise; the till settles it later.

        **A phone tab (T-30.14).** At a venue with no till whose manager switched phone tabs on (menu
        `features.phoneTab`), `ADD_TO_TAB` is the guest's own tab, settled on their phone. Opening one needs
        `tabName` and `tabPhone` (`400 tab_name_required`, `tab_phone_invalid`) and a payment rail (`503
        online_payment_unavailable`); the order's key (`X-Ruva-Order-Key`) is the tab's. A round on it sends
        `tabOrderId` with that same key — an id alone, another tab's key or none answers `404 order_not_found`,
        a tab already paid or voided `409 tab_closed`, one opened at another table `409 tab_elsewhere`. One tab may be
        open per phone number and per table at a location: a second is `409 tab_already_open`, its `message` the remedy
        (pay it, or ask staff). No more than a few tabs may be opened from one connection, and a few dozen at a location,
        within an hour (core `PhoneTabPolicy` `MAX_OPENS_PER_CLIENT`, `MAX_OPENS_PER_LOCATION`): past either, `409
        tab_opens_limited`, its `message` the remedy. A tab with nothing paid and no round for six hours is voided by the
        server itself (`PhoneTabPolicy.UNATTENDED_AFTER_MS`), freeing its table and number. A round — the one that opens the tab included — that would take what the tab owes past
        the location's limit (`features.phoneTabLimitCents`; 0 is no credit, and no tab is offered) is `409
        tab_limit_reached`, its `message` the amount to pay first; nothing is written, cooked or charged. A tab is paid
        only through its shares: `GET /qr/orders/{id}/payment` answers `BILL` for one. The tab is
        paid through `/qr/bills/{orderId}/shares` with the same key, and is never the table's bill (`GET /qr/bill`
        does not find it). With the switch off, or at a venue with a till, `403 tab_not_available` as before.

        **The table's code (T-39.9).** At a location whose manager switched on `tableCodesRequired` (off until then; nothing
        changes for a venue that does not), an order that is not paid now — `ADD_TO_TAB`, a pay-at-the-counter order, or a
        `PAY_NOW` order at a venue with no online payment, from a table — must carry `tableCode`, the 4 characters printed on
        that table. A photographed table QR therefore cannot open a tab or place an order to be paid later from somewhere
        else; a `PAY_NOW` order the venue can take online is not asked, and goes to the kitchen when it is placed, as it always
        has. Without the code `403 table_code_required`; a wrong one `403 table_code_wrong`. The answer is the same for a
        table that does not exist. Every code is counted before it is compared, per address and venue (`qrTableCode`) and
        per table (`qrTableCodeTable`, shared by every server), and a right one is given back; past either,
        `429 table_code_paused` with a `Retry-After`, for unpaid orders only. A takeaway or delivery order (a kiosk's
        included), the sample café and a round on a phone tab the caller holds the key of are never asked, nor is a kiosk's
        order held offline and replayed through `/sync/push` (`kiosk_order`, a signed-in device). The code travels in this
        body only: it is not in the QR's link, and it is not logged or audited.

        `clientOrderId` (T-6.7, optional, 8–64 of `[A-Za-z0-9_-]`): the order's id, minted by the device before
        the first attempt. With it the device sends the order's key, minted by the device too (24+ random bytes,
        32–128 of `[A-Za-z0-9_-]`, else `400 invalid_order_key`), in the `X-Ruva-Order-Key` header on the first attempt
        and every retry (T-2.12 review). The key's hash is stored as the order's (or the round's) key; a client that sends
        none is given one minted by the server. An id this route has already placed is answered again unchanged — with
        nothing inserted or fired a second time, a round added to an existing bill included (T-13.2) — ONLY when the
        request carries the key that opens that order or round: an id is not a secret, so a replay without its key is
        answered exactly as an id clash, a `409 id_conflict` with nothing read, fired, settled or charged and no checkout
        opened. An id another business's row holds is the same `409 id_conflict`. A round fires only its own lines;
        dishes the till has not sent stay unsent. The answer carries `receiptToken` (an order that opens its own bill)
        and `roundToken`, the key it opens with (T-2.9, T-2.12) — the device's own when it sent one.
        `callNumber`, `kitchenFired`, `placedAt` and `payments` are ignored here. They are honoured only when a signed-in
        device's held order arrives by sync (`kiosk_order`). There, past the licence grace, an order is refused
        `qr_not_licensed` unless `payments` carries the kiosk terminal's own card approval (D-45).
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/QrOrderKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QrOrderRequest" }
      responses:
        "201":
          description: Order placed, and fired to the kitchen unless it waits for its payment (D-195) or its time.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrOrderResponse" }
        "400":
          description: "Invalid order (identical lines are merged first; at most 50 different lines and 50 of one item — a guest's takeaway (click-and-collect) order, the venue's own `collectMaxQuantity` of one item (T-2.54), a kiosk's takeaway the lower of that and 50 (T-39.18), a table order and a delivery stay at 50 — `too_many_lines`, `invalid_quantity`, each with a sentence naming the remedy; `error:` one of `empty_order`, `too_many_lines`, `notes_too_long`, `table_label_too_long`, `missing_table`, `invalid_fulfilment_type`, `invalid_payment_mode`, `tab_requires_table`, `delivery_details_required`, `delivery_address_too_long`, `postcode_too_long`, `dropoff_notes_too_long`, `dropoff_notes_too_many_lines`, `dropoff_notes_invalid`, `pickup_name_too_long`, `pickup_phone_too_long`, `scheduled_in_past`, `scheduled_too_far`, `invalid_quantity`, `line_note_too_long`, `too_many_modifiers`, `unknown_product`, `product_unavailable`, `unknown_modifier`, `modifier_not_allowed`, `single_select_group`, `invalid_tip` (a negative tip), or `tip_above_bill` (T-41.28): a tip above what it is on — the order after its offers, a round's own lines on a table's bill, never above R10 000 on any bill — with the most the tip may be, in cents, as `message`; nothing is written)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`qr_not_licensed` (no QR Ordering on the licence, switched off, or whose licence ended longer ago than its grace period (help centre, Products and licensing)) or `tab_not_available` (ADD_TO_TAB without the Restaurant product), or — where the location asks for the table's code — `table_code_required` or `table_code_wrong` (T-39.9)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Location or table not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "A collected or delivered order with no room (`slot_full`, `slot_closed`, `no_slot_left`; `message` is the soonest slot with room), or a delivery refused (`delivery_not_offered`, `outside_delivery_area`, `below_delivery_minimum` with the cents short in `message`), or `outside_service_hours` (T-25.7): a NEW line is in a category that is not served at this time of day at this location — `message` is the sentence a guest reads (\"Breakfast is served 06:00–11:00, every day. It is not on the menu just now.\"); a line already on an open order is never refused, and nothing is written, or `ordering_paused` (T-1.15): the kitchen has paused guest ordering at this location — refused before anything is written, fired or charged, `message` the resume time (epoch millis) when one was set. A retry of an order placed before the pause is answered again, not refused. Or `kitchen_closed` (T-41.40): the location has kitchen hours and the order came outside them, read in the location's own time zone at the moment it is placed — refused the same way, before anything is written, fired or charged, `message` the sentence a guest reads, naming when orders are taken again (\"We aren't taking orders right now. We take orders again at 12:00 tomorrow.\"). An order wholly from categories kept taking orders after the kitchen closes (`afterHours`, T-41.51) is taken whatever the hours; one that mixes them with anything else is refused, the message naming what waits and the remedy (\"Burger isn't available until 12:00 — remove it to order the rest now.\"), read from the server's own catalogue whatever the client sent. A takeaway or delivery (not from a kiosk) is judged by its slot instead (T-41.42, T-41.51) — \"as soon as possible\" while closed is given the first time after the kitchen opens and held until then; a later time (`scheduledForMillis`) is taken while the kitchen is closed when the time is inside its hours, refused `kitchen_closed` when it is not, `message` naming the first time that can be chosen (\"The kitchen can't have an order ready at 23:30. The first time it can is 12:15 tomorrow.\"). A location with no hours is never refused; a retry of an order already placed is answered again; a kiosk's order held offline and sent later through sync was judged when taken and is not refused."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: "`online_payment_unavailable` (T-1.6, D-22): the business has no till to take payment at a counter, its location has not switched on paying at the counter (T-1.20), and no online rail is set up, so a `PAY_NOW` order could never be paid. Refused before anything is written — no sale, kitchen ticket or payment row. At such a business an order that comes to nothing settles itself on placing (`PAID`, no payment row). Also `busy` (T-2.35): the venue's order desk was taken — its turn taken (two orders in flight there, or its business or the server at its share) and no turn within two seconds, a lock held by another order for longer than two seconds, or the placement past its five-second bound — so nothing was written and no order number taken; try again in a moment."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "413":
          description: "`payload_too_large`: the body is over 256 KB, refused before it is read (T-2.35)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "408":
          description: "`body_too_slow`: the body did not arrive within ten seconds (T-2.35); nothing was read or written — send it again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: "Too many requests (`Retry-After` set): the `qr` bucket, or `table_code_paused` once wrong table codes pass `qrTableCode` or `qrTableCodeTable` (T-39.9)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/qr/slots:
    get:
      tags: [Customer QR]
      summary: The pickup or delivery times a guest may choose (T-13.3)
      description: |
        Public — no JWT required. Rate limit bucket `qr`: 600 requests/min. Every slot from now to the end of the last
        day the location takes orders for, from the location's own window (`/qr-ordering/windows`; a location that has
        set none gets whole-day 15-minute slots from 15 minutes out, unthrottled). A full slot is listed with
        `booked == capacity` rather than left out. `soonest` is what an "as soon as possible" order is given. These are
        exactly the slots `POST /qr/orders` accepts — both read core `OrderSlots`. Where the location has kitchen hours
        (T-41.42) only times inside them are listed: none after the kitchen closes, and the first after it opens is
        opening plus the notice (and the drive, for a delivery). While the kitchen is open `soonest` is a time in the sitting
        open now; once no time is left before it closes (about the notice before closing), and while the kitchen is closed,
        `soonest` is the next sitting's first time with room (T-41.51, D-183), and an "as soon as possible" order placed then
        is given that time and held until the kitchen opens; its answer's `later` says the order waits. A `channel=KIOSK`
        order, which shows its guest no time, is only ever given a time in the sitting open now: `409 no_slot_left`
        otherwise, with the first later time in `message`, or `null` when there is none (T-41.51). The channel is the caller's word here, so it only
        refuses more: a KIOSK order is judged for slots and room as a phone's (T-41.44). Sittings that run on into each other (one
        closes as the next opens) count as one. With `afterHours=true` (a basket wholly from categories kept taking orders
        after the kitchen closes) `soonest` is the windows' own, whatever the kitchen's hours; the listed times stay inside
        them. A delivery needs the location's delivery time on top of its notice, and is `409 delivery_not_offered` where the
        location does not deliver.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: loc, in: query, required: true, schema: { type: string } }
        - { name: fulfilment, in: query, required: false, schema: { type: string, enum: [TAKEAWAY, DELIVERY], default: TAKEAWAY } }
        - { name: afterHours, in: query, required: false, description: "T-41.51 - the basket is drinks alone from categories kept taking orders after the kitchen closes: `soonest` is not held to the kitchen's hours.", schema: { type: boolean, default: false } }
      responses:
        "200":
          description: The slots.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderSlotsResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: The venue's licence has no QR Ordering product, it is switched off, or whose licence ended longer ago than its grace period (help centre, Products and licensing) (`error:"qr_not_licensed"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`delivery_not_offered` — this location does not deliver."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/delivery:
    get:
      tags: [Customer QR]
      summary: What a delivery to a postcode costs, or why it cannot be made (T-13.3)
      description: |
        Public — no JWT required. Rate limit bucket `qr`: 600 requests/min. The zone is the one with the longest
        postcode prefix matching. `basketCents` is the dishes' total before any fee; under the zone's minimum the answer
        is `delivers:false`, `refusal:"below_delivery_minimum"` and `shortByCents`; outside every zone it is
        `refusal:"outside_delivery_area"`. The fee is the zone's fee product's price, nil at or over `freeOverCents`.
        The order route quotes the same way and refuses with the same codes.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: loc, in: query, required: true, schema: { type: string } }
        - { name: postcode, in: query, required: true, schema: { type: string, maxLength: 12 } }
        - { name: basketCents, in: query, required: false, schema: { type: integer, format: int64, default: 0 } }
      responses:
        "200":
          description: The quote.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryQuoteResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          description: The venue's licence has no QR Ordering product, it is switched off, or whose licence ended longer ago than its grace period (help centre, Products and licensing) (`error:"qr_not_licensed"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`delivery_not_offered` — this location does not deliver."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr-ordering/windows:
    get:
      tags: [Customer QR]
      summary: A location's pickup and delivery windows, kitchen throttle and delivery zones (T-13.3)
      description: Manager roles only. `saved:false` means the location has set nothing and the window shown is the default.
      parameters:
        - { name: loc, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The settings, each zone's `feeCents` priced from its fee product.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderWindowsSettings" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
    put:
      tags: [Customer QR]
      summary: Replace a location's windows, throttle and delivery zones (T-13.3)
      description: |
        Manager roles only. Takes effect at once: slots are derived, never stored. Zones are replaced as a set (each is
        given a new id). Refusals (`400`, `error:` one of `slot_minutes_out_of_range`, `capacity_out_of_range`,
        `lead_minutes_out_of_range`, `delivery_minutes_out_of_range`, `hours_out_of_range`,
        `hours_shorter_than_a_slot`, `days_ahead_out_of_range`, `zone_name_required`, `zone_postcodes_required`,
        `zone_postcode_invalid`, `zone_amount_negative`, `zone_postcode_in_two_zones`, `fee_product_not_found`,
        `location_mismatch`) carry the zone, postcode or product concerned in `message`.
      parameters:
        - { name: loc, in: query, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OrderWindowsSettings" }
      responses:
        "200":
          description: What was kept.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrderWindowsSettings" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/qr/orders/{id}:
    get:
      tags: [Customer QR]
      summary: Get order + kitchen + payment status for the thank-you screen
      description: |
        Public — no JWT required, `qr` rate limit (600 requests/min). Opens only with the order's key — the
        `receiptToken` the first answer to `POST /api/v1/qr/orders` carried — in the `X-Ruva-Order-Key` header, never the
        order id alone, which the client chose, and never in the URL. A missing or wrong key, another order's key, a till
        sale and an order placed before keys existed all answer exactly as an unknown order (404 `order_not_found`).
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: Order status.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrOrderStatusResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/rounds/{id}:
    get:
      tags: [Customer QR]
      summary: Follow a guest's round from placed to served
      description: |
        Public — no JWT required. A round is one basket a guest's phone sent (T-13.2); its id is the
        `clientOrderId` the phone minted (or the `roundId` the order answer carried), which is NOT a credential: the round
        opens only with its own key in the `X-Ruva-Order-Key` header (T-2.12) — the `roundToken` the first answer carried
        (for the round that opened an order, the order's own `receiptToken`). Another guest's round on the same tab, the
        tab's key and a till sale's id do not open it; each answers exactly as an unknown round (404 `round_not_found`).
        It is followed on any tab, a till's included: placed, sent to the kitchen, ready and
        served, each with its time, read from the kitchen tickets that carry the round's own lines — sent at
        the first of them, ready and served at the last. `lines` are the round's lines still on the bill, with
        their options: what "order this again" rebuilds the basket from. Rate limit bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: The round.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrRoundResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders/{id}/receipt:
    get:
      tags: [Customer QR]
      summary: The order's receipt, once it is paid
      description: |
        Public — no JWT required, `qr` rate limit (T-6.8). What a self-order kiosk prints when the guest asks for a
        receipt: the server's own receipt, the same assembly as the public receipt page, without the buyer's details.
        It opens with the `receiptToken` the first answer to `POST /api/v1/qr/orders` carried (T-2.9), in the
        `X-Ruva-Order-Key` header (T-2.12; the `?token=` query this route and the status poll briefly took was never
        released, and is gone) — a 192-bit key the server minted and keeps only as a hash — never with the order id, which the client chose. A
        missing or wrong key, an order placed before keys existed, and a sale that is not a guest QR order all answer
        exactly as an unknown order: `404 order_not_found`. Paid means settled — an order that came to nothing and
        settled itself (`PAID`, no payment row) has a receipt too. The guest app reads it for its "View your receipt" /
        "View your tax invoice" link (T-1.9). The venue's signed receipt link (`/receipts/{number}`) is separate.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: The receipt.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Receipt" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`order_not_paid` — the order has no receipt until it is paid; `order_cancelled` — the order was voided or paid back, so it has none."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders/{id}/receipt/link:
    get:
      tags: [Customer QR]
      summary: The public page of the order's receipt, once it is paid
      description: |
        Public — no JWT required, `qr` rate limit (T-39.4). What a self-order kiosk with no printer draws as a QR code, so
        the guest's own phone carries the receipt away: the signed `/receipts/{number}` link of the order, the page that
        shows the VAT receipt (a tax invoice over R50, with the supplier's details) without the sale's buyer. It opens with the order's
        `X-Ruva-Order-Key`, like the receipt; a missing or wrong key answers exactly as an unknown order.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: The link.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrReceiptLink" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`order_not_paid` — the order has no receipt until it is paid."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders/{id}/receipt/email:
    get:
      tags: [Customer QR]
      summary: Where the order's receipt email stands
      description: |
        Public — no JWT required, `qr` rate limit (T-39.4). `NONE` when no address was given for this order, `WAITING`
        while an address waits for payment, `SENT` once emailed, `NOT_SET_UP` when email is not configured on this server
        (the guest keeps the receipt link instead), `FAILED` when the mail provider would not take it or a daily cap
        refused it, and `UNSURE` when the mail service never answered (it may have gone; it is never sent again). Never the
        address. Opened with the order's `X-Ruva-Order-Key`.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: The status.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrReceiptEmailAnswer" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
    put:
      tags: [Customer QR]
      summary: Email the order's receipt
      description: |
        Public — no JWT required, its own `qrReceiptEmail` rate limit (T-39.4). Asks for the order's receipt to be emailed
        to the address in the body — what a kiosk's "Email my receipt" sends after paying. The receipt is the order's own,
        headed "TAX INVOICE" over R50 or "RECEIPT"; its link opens the receipt page without the buyer. Asked before the
        order is paid, it waits and goes when the order settles. Each send is claimed once (a row in
        `guest_receipt_requests`, not a flag), so a repeated call, a double tap or a settlement replayed sends nothing more
        while a send is waiting, under way, done (`SENT`) or of unknown outcome (`UNSURE`: the mail service never answered,
        so it may have gone). After a definite refusal (`FAILED`) or `NOT_SET_UP`, the order may ask again — up to three
        sends in all. One business sends one address at most 10 receipts a day, and 2 000 receipts a day in all; past a cap
        the answer is `FAILED` and nothing is sent. A free (R0) order is never emailed. The address is held only until the
        send, then erased, and is never logged or returned. Opened with the order's `X-Ruva-Order-Key`.
      x-rate-limit: "qrReceiptEmail: 10/hour"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QrReceiptEmailRequest" }
      responses:
        "200":
          description: Where the request stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrReceiptEmailAnswer" }
        "400":
          description: "`invalid_email` — not an address."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`free_order` — a free order has no receipt to email; `receipt_email_may_have_gone` — an earlier send's outcome is unknown, so no other address is taken; `sample_venue` — the public sample café keeps nobody's address."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: "`receipt_email_limit` — this order's receipt has been tried three times; or the `qrReceiptEmail` bucket is spent (with `Retry-After`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/qr/buzzer/key:
    get:
      tags: [Customer QR]
      summary: The key a guest's page subscribes to push with
      description: |
        Public — no JWT required, `qr` rate limit (T-5.2). The server's VAPID public key (RFC 8292), base64url: the
        `applicationServerKey` a guest's page passes to `PushManager.subscribe`. `publicKey` is absent when this server
        sends no push — the page then rings only while it is open.
      x-rate-limit: "qr: 600/min"
      security: []
      responses:
        "200":
          description: The key, or no key.
          content:
            application/json:
              schema:
                type: object
                properties:
                  publicKey: { type: string, nullable: true, description: "A 65-byte uncompressed P-256 point, base64url." }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders/{id}/buzzer:
    put:
      tags: [Customer QR]
      summary: Buzz this phone when the order is ready
      description: |
        Public — no JWT required, `qr` rate limit (T-5.2). Keeps the guest's Web Push subscription for the order, so the
        kitchen marking it ready sends one push (through `OrderReady`, the one owner of "ready, and told once"). It opens
        only with `key`, the `receiptToken` the first answer to `POST /api/v1/qr/orders` carried — never the order id; a
        missing or wrong key answers exactly as an unknown order. One subscription per order: the last one wins. The
        endpoint must be https on a push service the server sends to (Google FCM, Mozilla, Apple, Microsoft WNS); any
        other address is refused before anything is stored. The subscription is deleted once its push is sent, when the
        push service says it is gone, and 24 hours after it was given whatever happened. The push carries the order id,
        its pickup number and the venue's name — nothing about the guest.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [key, endpoint, p256dh, auth]
              properties:
                key: { type: string, description: "The order's `receiptToken`." }
                endpoint: { type: string, maxLength: 1024, description: "The subscription's endpoint (https, a push service's host)." }
                p256dh: { type: string, description: "The subscription's P-256 public key, base64url (65 bytes)." }
                auth: { type: string, description: "The subscription's auth secret, base64url (16 bytes)." }
      responses:
        "204":
          description: Kept; the phone is buzzed when the order is ready.
        "400":
          description: "`push_endpoint_not_allowed` — not an https address on a known push service; `push_keys_invalid` — the keys are not a Web Push key pair."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`order_ready` — the order is ready already, so nothing would be sent; `push_not_configured` — this server sends no push."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "411":
          description: "`length_required` — send the subscription with a Content-Length."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "413":
          description: "`buzzer_too_large` — a subscription is at most 4 KB."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders/{id}/cancel:
    post:
      tags: [Customer QR]
      summary: Cancel your own order before the kitchen starts it
      description: |
        Public — no JWT required, on the `qr` rate limit (T-39.7). A guest who ordered by mistake cancels their own order for
        90 seconds after it was placed (or after its first kitchen ticket fired, when that is sooner; never counted from payment),
        measured in the server's time — the round's `cancelMsLeft` says how long is left — and only while no kitchen ticket of the
        order has started: none cooking, plating, ready, bumped or served, no line ticked off, and none printed at a station whose
        print mode is not `SCREEN_ONLY`. A kitchen screen showing the ticket does not count as started. An order a provider charged
        twice (`PAID_TWICE`) is sent to the counter. It opens only with the order's key (`receiptToken`) in the `X-Ruva-Order-Key`
        header; a missing or wrong key answers exactly as an unknown order.

        What it does, once: for an order paid on a Yoco card or PayFast, the kitchen's lines are struck and the kitchen told first,
        under the order's lock, then the order is paid back in full through the refund path that already exists (one refund, one
        REFUND journal, never more than was paid; a declined attempt beside the paid one is never refunded); an order nobody has paid
        is voided, with no refund, and struck. Sending it again answers the same and refunds nothing more. A payment Ruva cannot pay
        back itself (SnapScan, a card machine, cash) is refused with a sentence that sends the guest to the counter, and the order
        stands. A refund the provider refuses cancels nothing (`502 refund_refused`), and the strike is taken back. Only a guest's
        own whole order can be cancelled this way: not a delivery, nor a bill shared with a table or a phone tab.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: The order is cancelled. `refundedCents` is what went back to the guest's card (0 for an order nobody had paid).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrOrderCancelResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: |
            Refused, with a sentence for the guest: `cancel_window_over`, `cancel_kitchen_started`, `cancel_ask_at_counter`,
            `cancel_payment_open` (a payment is still going through), `cancel_not_here` (a delivery, a shared bill or the sample
            café), `cancel_not_open` (already finished).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "502":
          description: "`refund_refused` — the provider would not pay it back; nothing was cancelled."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/qr/orders/{id}/arrived:
    post:
      tags: [Customer QR]
      summary: Tell the pass a takeaway guest has arrived
      description: |
        Public — no JWT required, its own `qrArrival` rate limit, 6 a minute per order (T-36.23). A guest collecting a
        TAKEAWAY order taps "I'm here" and may leave a note of where to find them ("blue Polo, bay 4"): plain text on
        one line, at most 60 characters once control characters and runs of spaces are collapsed (a longer one is
        `400 arrival_note_too_long`, never cut; the note is optional, and an empty one is no note). The kitchen's Expo and
        Ready screens then show an "Arrived" chip with how long ago and the note. **The first tap wins**: it stamps the
        order's `arrivedAt` and note, and a later tap — from this phone or another holding the key — changes nothing and
        is answered with what was stamped (`first: false`), so a retry after a lost answer is safe. It opens only with
        the order's key (`receiptToken`) in the `X-Ruva-Order-Key` header; a missing, wrong or another order's key
        answers exactly as an unknown order: `404 order_not_found`. Offered once the order is placed and until it is
        collected. The note is the guest's words and is never logged; the sample café keeps no guest's details, so
        there it is `409 sample_venue`.
      x-rate-limit: "qrArrival: 6/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                note: { type: string, nullable: true, maxLength: 60, description: "Where to find the guest. Optional; one line of plain text." }
      responses:
        "200":
          description: What the order holds — the first tap's time and note.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrArrival" }
        "400":
          description: "`arrival_note_too_long` — a note is at most 60 characters."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`arrival_not_offered` — only a takeaway tells the pass it has arrived; `order_collected` — the order is collected or closed already; `sample_venue` — the sample café keeps no guest's details."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders/{id}/call:
    post:
      tags: [Customer QR]
      summary: Call a waiter, or ask for the bill
      description: |
        Public — no JWT required (T-41.85). A guest at a table taps "Call a waiter" or "Ask for the bill" on their order
        screen. It opens only with the order's key (`receiptToken`) in the `X-Ruva-Order-Key` header, or the bill's share
        code in `X-Ruva-Bill-Code` for a guest who joined the bill; anything else answers exactly as an unknown order:
        `404 order_not_found`. **A table holds one open call**, shared by every order at it: a second tap, from this phone
        or another at the table, is answered with the same call, and asking for the bill turns a waiter call into a bill
        call. The floor's phones are told the table — never the guest — and the till's floor and the kitchen display's
        Service view show it until somebody answers "On my way". Its own `qrCall` bucket, 60 an hour per client, and
        `qrCallOrder`, 10 an hour per order, spent only once the order's key has opened it. The sample café has nobody
        waiting on its tables: `409 sample_venue`.
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [kind]
              properties:
                kind: { type: string, enum: [WAITER, BILL] }
      responses:
        "200":
          description: The table's open call, and the sentence the guest is shown ("A waiter is on the way.").
          content:
            application/json:
              schema:
                type: object
                properties:
                  callId: { type: string }
                  kind: { type: string, enum: [WAITER, BILL] }
                  calledAt: { type: integer, format: int64 }
                  sentence: { type: string }
        "400":
          description: "`invalid_call` — the kind is neither WAITER nor BILL."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`no_table` — the order is not at a table; `order_closed` — the order was cancelled; `sample_venue` — nobody waits on the sample café's tables; `calls_closed` — the venue's account is suspended, so nobody would hear the call."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/table-calls:
    get:
      tags: [Floor & Tables]
      summary: A location's open table calls
      description: |
        The calls guests have made and nobody has answered yet (T-41.85), drawn on the till's floor and the kitchen display's
        Service view. MANAGE_TABLES, TILL_SELL or KDS_VIEW; a kitchen screen paired as itself reads them too. A call names
        the table, never the guest.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: The open calls, oldest first.
          content:
            application/json:
              schema:
                type: object
                properties:
                  calls:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        locationId: { type: string }
                        tableLabel: { type: string }
                        kind: { type: string, enum: [WAITER, BILL] }
                        calledAt: { type: integer, format: int64 }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/table-calls/{id}/dismiss:
    post:
      tags: [Floor & Tables]
      summary: Answer a table call ("On my way")
      description: |
        Closes the call (T-41.85). MANAGE_TABLES, TILL_SELL or KDS_BUMP; a kitchen screen paired as itself closes it as the
        business's `system` person. Closing a call already closed changes nothing (two waiters tapping at once).
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "204":
          description: Closed.
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/push/devices:
    post:
      tags: [Devices]
      summary: Register this phone or browser for staff notifications
      description: |
        The one staff push system (T-41.85; a browser since T-37.21). The Ruva app on an Android phone or iPhone registers its FCM
        token after the person allows notifications; a browser (the back office opened in a phone's or a computer's browser)
        registers its Web Push subscription with `platform: web`, the subscription's endpoint as `token` and its two keys
        (`p256dh`, `auth`). Either is kept under the session the request is signed in with, and deleted when that session ends — a
        sign-out, a manager's remote sign-out, a deactivation, a change of role, a password reset — or when the push service says
        it is gone. Every device of a person hears the same kinds: each kind's audience is the role's permissions
        (`PushKind.heardWith`), read again at every send, and the person's one switch per kind. A browser's endpoint must be https
        on a push service the server sends to (Google FCM, Mozilla, Apple, Microsoft WNS) and is refused before anything is stored;
        a person may have at most 10 browsers registered. Any person; a screen paired as itself is refused (`403`), and a token
        with no session is `401 session_required`. Registering the same address again moves it to this session (and person).
        Audited by method, path and status; the body is never logged.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token, platform]
              properties:
                token: { type: string, maxLength: 4096, description: "An app's FCM token, or a browser's push endpoint (https, at most 1024 characters)." }
                platform: { type: string, enum: [android, ios, web] }
                locationId: { type: string, nullable: true, description: "The location this device works at; none hears every location." }
                p256dh: { type: string, nullable: true, description: "A browser's P-256 public key, base64url (65 bytes); required for `web`, absent otherwise." }
                auth: { type: string, nullable: true, description: "A browser's auth secret, base64url (16 bytes); required for `web`, absent otherwise." }
      responses:
        "204":
          description: Registered.
        "400":
          description: "`invalid_platform`, `invalid_push_token`, `unknown_location`, `push_endpoint_not_allowed` or `push_keys_invalid`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: "`push_not_configured` — a browser, on a server that sends no browser push; `too_many_browsers` — the person already has 10 browsers on."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/push/devices/current:
    delete:
      tags: [Devices]
      summary: Stop notifications to this phone or browser
      description: The app calls it as it signs out, and the back office as a browser is turned off or signs out (T-41.85, T-37.21); the session's end deletes it anyway. Any person.
      responses:
        "204":
          description: This session's phone or browser is told nothing more.
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/push/preferences:
    get:
      tags: [Devices]
      summary: Which notifications the signed-in person is sent
      description: |
        One entry per kind the person's role may hear (T-41.85), each with whether they switched it off — one switch for every
        device of theirs, app or browser (T-37.21) — how many phones and browsers of theirs are registered, and the key a browser
        subscribes under (`webPushKey`, the server's VAPID public key, base64url; absent when this server sends no browser push).
        Any person.
      responses:
        "200":
          description: The person's kinds.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PushPreferences" }
        "403":
          $ref: "#/components/responses/Forbidden"
    put:
      tags: [Devices]
      summary: Switch one of the person's notification kinds on or off
      description: Only a kind the person's role hears (`400 unknown_push_kind` otherwise). Any person.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PushKindChange" }
      responses:
        "200":
          description: The person's kinds, after the change.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PushPreferences" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/locations/{id}/push-kinds:
    get:
      tags: [Locations]
      summary: Which notification kinds a location's staff are sent
      description: Every kind, each on unless a manager switched it off for this location (T-41.85). EDIT_SETTINGS.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The location's kinds.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LocationPushKinds" }
        "403":
          $ref: "#/components/responses/Forbidden"
    put:
      tags: [Locations]
      summary: Switch a notification kind on or off for everyone at a location
      description: Switched off, nobody at the location is sent that kind (T-41.85). EDIT_SETTINGS.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PushKindChange" }
      responses:
        "200":
          description: The location's kinds, after the change.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LocationPushKinds" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/qr/orders/{id}/feedback:
    post:
      tags: [Customer QR]
      summary: Rate the order
      description: |
        Public — no JWT required, its own `qrFeedback` rate limit (T-1.17). After the order is paid, or once the
        kitchen has finished it, the guest rates it from 1 to 5 stars with an optional comment of up to 500 characters
        (control and format characters are dropped). A free order (a total of nothing) is not rated. It opens only with
        `key`, the `receiptToken` the first answer to `POST /api/v1/qr/orders` carried; a missing or wrong key answers
        exactly as an unknown order. One rating per order: sending again within 24 hours of the first replaces it, and
        after that it stands. A rating of 2 or below emails the venue's managers once per order, with the order number
        and nothing of the guest's — at most 5 such emails per business in any hour; past that the rating is stored and
        counted on the dashboard, and nobody is emailed.
      x-rate-limit: "qrFeedback: 30/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [key, rating]
              properties:
                key: { type: string, description: "The order's `receiptToken`." }
                rating: { type: integer, minimum: 1, maximum: 5 }
                comment: { type: string, maxLength: 500, description: "Optional, in the guest's own words." }
      responses:
        "200":
          description: The rating as stored, and until when it may change (epoch milliseconds).
          content:
            application/json:
              schema:
                type: object
                required: [rating, changeableUntil]
                properties:
                  rating: { type: integer, minimum: 1, maximum: 5 }
                  comment: { type: string }
                  changeableUntil: { type: integer, format: int64 }
        "400":
          description: "`invalid_rating` — not 1 to 5; `comment_too_long` — over 500 characters."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`order_not_finished` — not paid and not ready yet; `order_free` — a free order is not rated; `feedback_closed` — rated more than 24 hours ago."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/guest/email-code:
    post:
      tags: [Customer QR]
      summary: Email a guest a one-time code to confirm their email
      description: |
        Public — no JWT required, its own `qrEmailCode` rate limit (T-1.24, D-80: email first, WhatsApp later). Emails a
        6-digit code, in English, valid for 10 minutes and good once, to the address the guest typed at checkout. Only a
        hash of the code is kept, and the address only as a keyed hash (HMAC under the server's key). The answer is `{"status":"sent"}` for every
        address — a customer's, a stranger's, one the mail provider refused — and the work done is the same, so the route
        cannot be used to find out whether someone is a customer. `{"status":"unavailable"}` — no mail is set up, or the
        provider could not be reached — means the order carries on under the unverified rule. At most 3 codes an hour per
        address at one business, 5 an hour and 10 a day per address at every business together, 40 an hour per location and
        60 an hour per business (`429 code_limit`), besides the client's bucket. A newer code retires the older.
      x-rate-limit: "qrEmailCode: 30/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [locationId, email]
              properties:
                locationId: { type: string }
                email: { type: string, maxLength: 254 }
      responses:
        "200":
          description: "`sent` or `unavailable`."
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string, enum: [sent, unavailable] }
        "400":
          description: "`invalid_email` — not an address, or it holds a character that cannot be used."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`qr_not_licensed` — the business does not run QR Ordering, so it sends no mail."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Location not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`sample_venue` — the public sample café mails nobody (T-2.48)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: "`code_limit` — too many codes for this address or this business in the hour; or the client's bucket, with `Retry-After`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/qr/guest/email-code/check:
    post:
      tags: [Customer QR]
      summary: Type the emailed code back and receive a one-time proof
      description: |
        Public — no JWT required, `qrEmailCode` rate limit (T-1.24). The right code answers a one-time `proof`, good for
        30 minutes, that the order's `guest.emailProof` carries (`POST /api/v1/qr/orders`); the order spends it once, for
        this address at this business only. Five wrong tries burn the code — the sixth is refused though its digits are
        right. A wrong, expired, used, retired or never-sent code is the same `400 code_invalid`, so a refusal says nothing
        about the address.
      x-rate-limit: "qrEmailCode: 30/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [locationId, email, code]
              properties:
                locationId: { type: string }
                email: { type: string, maxLength: 254 }
                code: { type: string, description: "The six digits; spaces and dashes between them are ignored." }
      responses:
        "200":
          description: The one-time proof.
          content:
            application/json:
              schema:
                type: object
                required: [proof]
                properties:
                  proof: { type: string }
        "400":
          description: "`code_invalid` — wrong, expired, used, burned or never sent; or `invalid_email`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`qr_not_licensed`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Location not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/qr/orders/{id}/payment:
    get:
      tags: [Customer QR]
      summary: Get the payment surface for an unpaid self-order
      description: |
        Public — no JWT required. Opens only with the order's key (`receiptToken`) in the `X-Ruva-Order-Key` header
        (T-2.12): without it, with a wrong or another order's key, or for a till sale, it answers exactly as an unknown
        order (404 `order_not_found`) — the hosted checkout it hands out is the guest's alone. Rails in preference order (V72): `YOCO` — a hosted card checkout link
        (idempotency-keyed on the order, so refetching returns the SAME checkout); `SNAPSCAN` — the static
        QR + server-rendered PNG, only for a SnapScan payment started before SnapScan was hidden (it is not offered right
        now, so no new one is started); `PAY_AT_COUNTER` — nothing configured or a zero total, only at a business with a
        till, or one with no till whose location has switched on counter payments (T-1.20; the order is then a counter
        order, and a counter order always answers `PAY_AT_COUNTER` and never starts a checkout): otherwise no rail
        answering is `503 online_payment_unavailable` (try again), never the counter, and a
        free order settles itself through checkout (`PAID`, no payment row; `503 settlement_unavailable` if that fails) (T-1.6). A settled order
        answers `PAID`. The payment is claimed under the order's lock before any provider is asked, so a slow provider
        never lets the counter take the same bill; a declined card's next fetch gets a fresh checkout. A bill that guests have started paying in shares (T-13.1) answers `BILL` with what is
        left in `amountCents`: it is paid through `/api/v1/qr/bills/{orderId}/shares`, never as a whole order
        again. Idempotent — repeated calls never stack up new PENDING payment rows. Rate limit
        bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - $ref: "#/components/parameters/PathId"
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: Payment surface (mode `YOCO`, `PAYFAST`, `SNAPSCAN`, `PAY_AT_COUNTER`, `PAID` or `BILL`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QrPaymentResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`order_closed`: the order was voided or refunded, so there is nothing to pay. `sample_venue`: the order is the sample café's that the public site links to (T-6.5), which never charges — no provider is asked and no payment is written."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: "`online_payment_unavailable`: no online rail answered and nobody takes payment at the counter (no till, and counter payments not switched on); `settlement_unavailable`: a free order at such a business could not be settled just now."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"

  /api/v1/qr/bill:
    get:
      tags: [Customer QR]
      summary: The bill open on a table, as its guests see it
      description: |
        Public — no JWT required (T-13.1). Licence-gated on QR Ordering like the menu. The table's open bill
        (the till's or a guest's), opened with the bill's share code in `X-Ruva-Bill-Code` (T-2.50): its live lines with
        each line's part of the bill, what is paid, what is being paid right now, what is left, and how it is already being
        split. Without a code the table's details say only whether a bill is open: `404 no_open_bill` when the table has
        none, `403 bill_code_required` when it has one. A bill that is a counter order (T-1.20) is paid at the counter and
        nowhere else, so with a code or without one it answers `409 pay_at_counter` (T-41.100). A wrong code, or a code at a
        table with no bill, answers exactly as an unknown order (404 `order_not_found`) and is counted;
        `429 too_many_code_tries` once the bill or the caller's address has spent its tries, with `Retry-After` (seconds until its 15-minute window ends). Rate limit bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: loc, in: query, required: true, schema: { type: string } }
        - { name: table, in: query, required: true, description: "The table's label, as on its QR code.", schema: { type: string } }
        - $ref: "#/components/parameters/QrBillCode"
      responses:
        "200":
          description: The bill.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestBillResponse" }
        "409":
          description: The table's open bill is a counter order (`pay_at_counter`), paid at the counter only.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: >-
            The venue is not running QR Ordering (`qr_not_licensed`) — a lapsed licence does not close this door, a bill
            already placed stays payable — or a bill is open and no code was given (`bill_code_required`).
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"

  /api/v1/qr/bills/{orderId}:
    get:
      tags: [Customer QR]
      summary: A bill by its order id
      description: |
        Public — no JWT required (T-13.1). The order id is not a credential (T-2.12): the bill opens with the order's key
        in `X-Ruva-Order-Key`, or with the bill's share code in `X-Ruva-Bill-Code` (T-2.50), which is how a diner who did
        not place the order splits it; the table's details open nothing. Opened with the key, the answer carries the bill's
        `shareCode` to show the table. An order id with neither, a wrong or another order's key, and a wrong or another
        bill's code all answer exactly as an unknown order (404 `order_not_found`); wrong codes are counted, and past the
        tries a code is not tried (429 `too_many_code_tries`). Rate limit bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: string } }
        - $ref: "#/components/parameters/QrOrderKey"
        - $ref: "#/components/parameters/QrBillCode"
      responses:
        "200":
          description: The bill.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestBillResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"

  /api/v1/qr/bills/{orderId}/tab-code:
    post:
      tags: [Customer QR]
      summary: Share a phone tab with friends at the table (its owner shows the tab's code)
      description: |
        Public — no JWT required (T-39.29, D-188). The owner of a guest's phone tab (the phone that opened it and holds its key
        in `X-Ruva-Order-Key`) asks to show the tab's share code, to tell friends at the same table. The answer is the tab's
        bill with its `shareCode` (`XXXX-XXXX`, the same code every time: minted once) and `phoneTab: true`. **Only the tab's
        key opens this** — a share code never does, so a friend cannot show it on — and until the owner asks, no code exists:
        a tab nobody shared opens to no code, whoever tries one. A friend who types the code at the table's door
        (`GET /qr/bill?loc&table` with `X-Ruva-Bill-Code`) finds the tab (`phoneTab: true`), reads it and pays a share with the
        code, and adds rounds with `POST /qr/orders` (`tabOrderId`, the code in `X-Ruva-Bill-Code` and a key of their own in
        `X-Ruva-Order-Key`); the location's tab limit holds over every phone's rounds, and the friend is never given the
        tab's key, so only its owner cancels, reads the receipt or the payment screen. Wrong codes are the unknown-order
        answer and counted (429 `too_many_code_tries`). A bill that is not a phone tab answers `409 not_a_phone_tab`; an unknown
        order, no key or another order's key answers `404 order_not_found`. Rate limit bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: string } }
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: The tab's bill, with the code to show friends.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestBillResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The order is not a phone tab (`not_a_phone_tab`).
        "429":
          $ref: "#/components/responses/TooManyRequests"
    delete:
      tags: [Customer QR]
      summary: Stop sharing a phone tab (its owner)
      description: |
        Public — no JWT required (T-39.29 review). The owner of a shared phone tab (the tab's own key in `X-Ruva-Order-Key`; a share
        code never opens this) stops sharing it: the code friends were told opens nothing from then on — at the table's door, by id,
        or for a round, each the unknown-order `404` — and sharing again (`POST`) shows a NEW code. Rounds friends already added stay
        on the tab. The answer is the tab's bill with no `shareCode` and `phoneTab: true`. A bill that is not a phone tab answers
        `409 not_a_phone_tab`; an unknown order, no key or another order's key answers `404 order_not_found`. Rate limit bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: string } }
        - $ref: "#/components/parameters/QrOrderKey"
      responses:
        "200":
          description: The tab's bill, no longer shared.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestBillResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: The order is not a phone tab (`not_a_phone_tab`).
        "429":
          $ref: "#/components/responses/TooManyRequests"

  /api/v1/qr/bills/{orderId}/shares:
    post:
      tags: [Customer QR]
      summary: Pay a share of a table's bill from a guest's phone
      description: |
        Public — no JWT required (T-13.1), opened as the bill is (`X-Ruva-Order-Key`, or the bill's code in
        `X-Ruva-Bill-Code`; otherwise 404 as an unknown order, T-2.12, T-2.50). `REST` pays what is left; `EVEN` an even share of what is left over the
        ways still open (the first even share sets `ways` for the table); `ITEMS` the chosen lines at their part of
        the bill. The server decides the amount under a lock on the bill (core `GuestShares`) and never takes more
        than is left; the phone's `shareId` makes a retry the same share. Answered with the venue's one rail —
        `YOCO` or `PAYFAST` (a hosted page `url`), `SNAPSCAN` (`url` and a PNG; only for a share started on SnapScan
        before it was hidden, as it is not offered right now), or `PAY_AT_COUNTER` when it has none. Refusals are `409 share_<reason>` (`share_nothing_left`, `share_split_by_item`, `share_split_evenly`,
        `share_other_ways`, `share_all_shares_taken`, `share_no_items`, `share_item_taken`, `share_unknown_item`,
        `share_bad_ways`, `share_tip_too_large` with the most the tip may be on that share, in cents, as `message`), `409 bill_closed`, or `409 pay_at_counter` for an order to be paid at the
        counter (T-1.20), which is paid there and nowhere else. With no rail at all the answer is `PAY_AT_COUNTER` only where
        somebody takes it there (a till, or the back office — the order then becomes a counter order), else 503
        `online_payment_unavailable`. The bill settles on the till by itself once
        captured shares cover it to the cent. Rate limit bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: string } }
        - $ref: "#/components/parameters/QrOrderKey"
        - $ref: "#/components/parameters/QrBillCode"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GuestShareRequest" }
      responses:
        "201":
          description: The share, and how to pay it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestShareResponse" }
        "200":
          description: The same share asked for again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestShareResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "503":
          description: The card rail could not open a checkout (`payment_unavailable`); the share is released.

  /api/v1/qr/bills/{orderId}/shares/{shareId}:
    get:
      tags: [Customer QR]
      summary: A share's payment, and the bill as it stands
      description: >-
        Public — no JWT required (T-13.1), opened as the bill is (`X-Ruva-Order-Key`, or `X-Ruva-Bill-Code`; otherwise 404 as
        an unknown order, T-2.12, T-2.50). `status` is the share's payment's — PENDING, PAID or FAILED. Rate limit bucket `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: string } }
        - { name: shareId, in: path, required: true, schema: { type: string } }
        - $ref: "#/components/parameters/QrOrderKey"
        - $ref: "#/components/parameters/QrBillCode"
      responses:
        "200":
          description: The share.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestShareResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"

  /api/v1/qr/bills/{orderId}/shares/{shareId}/cancel:
    post:
      tags: [Customer QR]
      summary: Give a share back
      description: |
        Public — no JWT required (T-13.1), opened as the bill is (`X-Ruva-Order-Key`, or `X-Ruva-Bill-Code`; otherwise 404 as
        an unknown order, T-2.12, T-2.50). A guest who backed out of the checkout releases their share so the rest of
        the table is not held up by it: its PENDING payment fails. A paid share is never cancelled. Rate limit bucket
        `qr`: 600 requests/min.
      x-rate-limit: "qr: 600/min"
      security: []
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: string } }
        - { name: shareId, in: path, required: true, schema: { type: string } }
        - $ref: "#/components/parameters/QrOrderKey"
        - $ref: "#/components/parameters/QrBillCode"
      responses:
        "200":
          description: The share as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GuestShareResponse" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"

  # ───────────────────────────── Checklists ─────────────────────────────
  /api/v1/checklists:
    get:
      tags: [Checklists]
      summary: List checklist templates (with items)
      parameters:
        - name: locationId
          in: query
          required: false
          description: Filter to templates scoped to this location (templates with a null location apply everywhere).
          schema: { type: string }
      responses:
        "200":
          description: Templates for the tenant.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ChecklistDto" } }
    post:
      tags: [Checklists]
      summary: Create a checklist template
      description: Manager-gated. Creates a template and its items.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ChecklistUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdResponse" }
        "400":
          description: "Invalid input (`error:` one of `title_required`, `title_too_long`, `invalid_recurrence`, `too_many_items`, `item_label_required`, `item_label_too_long`, `invalid_location`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/checklists/{id}:
    post:
      tags: [Checklists]
      summary: Edit a checklist template (metadata + replace items)
      description: |
        Manager-gated. Updates title/recurrence/active/location and replaces the item set: items present by
        id are updated, new items (no id) are inserted, and dropped items are removed (which also removes their
        run-item ticks — editing a template reshapes its runs).
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ChecklistUpsertRequest" }
      responses:
        "200":
          description: Updated.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdResponse" }
        "400":
          description: Invalid input (same codes as create).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/checklists/{id}/runs:
    post:
      tags: [Checklists]
      summary: Open (idempotent) today's run for a checklist
      description: |
        Any person signed in (never a device). Opens a run for the checklist on a business date (default: today,
        Africa/Johannesburg; override with `?date=yyyy-MM-dd`). Idempotent — re-opening returns the existing
        run (`200`) rather than duplicating it. On first open, snapshots the current template items as
        unticked run items.
      parameters:
        - $ref: "#/components/parameters/PathId"
        - name: date
          in: query
          required: false
          description: Business date `yyyy-MM-dd` (defaults to today).
          schema: { type: string }
      responses:
        "201":
          description: New run opened.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ChecklistRunDto" }
        "200":
          description: Existing run for that date.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ChecklistRunDto" }
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/checklists/runs:
    get:
      tags: [Checklists]
      summary: List runs for a business date (with progress)
      parameters:
        - name: date
          in: query
          required: false
          description: Business date `yyyy-MM-dd` (defaults to today).
          schema: { type: string }
        - name: locationId
          in: query
          required: false
          description: Filter to runs whose parent checklist is scoped to this location.
          schema: { type: string }
      responses:
        "200":
          description: Runs for the date.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ChecklistRunDto" } }
  /api/v1/checklists/runs/{runId}/items/{itemId}:
    post:
      tags: [Checklists]
      summary: Mark a run item done/undone
      description: |
        Any person signed in (never a device). Toggles a run item's `done` flag; when done, records the acting staff
        (`byStaffId` if supplied + valid, else the caller) and a timestamp. Recomputes the run's status
        (`COMPLETE` when every item is done, else `OPEN`).
      parameters:
        - name: runId
          in: path
          required: true
          schema: { type: string }
        - name: itemId
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ChecklistItemMarkRequest" }
      responses:
        "200":
          description: Updated item + run progress.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ChecklistItemMarkResponse" }
        "400":
          description: "Invalid input (`error:` one of `note_too_long`, `unknown_staff`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "Run or run item not found (`error:` `run_not_found` | `run_item_not_found`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/close-of-day:
    get:
      tags: [Reports]
      summary: Where the trading day stands at a location (needs CLOSE_SHIFT)
      description: Open checks and tabs, staff still on shift, registers without a Z, the Z's run today, the day's totals, and `blockers` — in words, what is still in the way of closing (T-3.9). `closed` is set once the day is closed.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: date
          in: query
          required: false
          description: Trading date `YYYY-MM-DD` (Africa/Johannesburg); today when absent. Anything else is 400 `invalid_trading_date`.
          schema: { type: string }
      responses:
        "200":
          description: The day.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CloseOfDayStatusDto" }
        "403":
          description: The role does not have CLOSE_SHIFT (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/close-of-day/summary:
    get:
      tags: [Reports]
      summary: The day at a location with no till (needs VIEW_FINANCIALS)
      description: "T-41.106 (D-207). The trading day's sales, VAT, net sales, tips, refunds and orders (the reports' own figures), its takings by payment method online and at the counter (tips included), and what stands open now whatever day it began: paid orders not settled, orders and phone tabs waiting at the counter, counter cash not yet banked. `mayBank` is whether the reader may mark the cash banked (`POST /sales/counter/banked`). There is no close: a venue with no till has no shift, Z or count to lock. `format=csv|pdf` is the same day as a file."
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: date
          in: query
          required: false
          description: Trading date `YYYY-MM-DD` (Africa/Johannesburg); today when absent. Anything else is 400 `invalid_trading_date`.
          schema: { type: string }
        - name: format
          in: query
          required: false
          description: "`csv` or `pdf` for the day as a file; absent is the JSON. Anything else is 400 `invalid_format`."
          schema: { type: string, enum: [csv, pdf] }
      responses:
        "200":
          description: The day.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DaySummaryDto" }
            text/csv:
              schema: { type: string }
            application/pdf:
              schema: { type: string, format: binary }
        "400":
          description: "`missing_locationId`, `invalid_trading_date` or `invalid_format`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: The role does not have VIEW_FINANCIALS (`permission_required`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Not one of this tenant's locations (`location_not_found`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/close-of-day/close:
    post:
      tags: [Reports]
      summary: Close the trading day (needs CLOSE_SHIFT)
      description: Records the day and its totals (V97). Refused while anything is in the way; a second close of the same day answers with the first. It does not stop a sale queued offline that day from landing later.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CloseDayRequest" }
      responses:
        "200":
          description: The closed day.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DayCloseDto" }
        "409":
          description: "`day_not_ready` — the message names the open checks, the people still clocked in, the registers without a Z and the tills still holding the day's sales (each with when it last checked in; T-35.5)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: The role does not have CLOSE_SHIFT.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/close-of-day/send:
    post:
      tags: [Reports]
      summary: Send the day's summary by email or WhatsApp (needs CLOSE_SHIFT)
      description: "`sent` false with `status` email_not_configured, whatsapp_not_configured or provider_refused when it did not go, or provider_no_answer when the email service never answered (it may have gone) — never reported as sent. WhatsApp free-form messages reach only a number that wrote to the business in the last 24 hours."
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SendDayReportRequest" }
      responses:
        "200":
          description: What happened.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SendDayReportResponse" }
        "400":
          description: "`invalid_email`, `invalid_phone` or `invalid_channel`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/checklists/summary/send:
    post:
      tags: [Checklists]
      summary: Build + email the day's checklist summary
      description: |
        Manager-gated. The same digest is emailed by itself each morning (from 07:00 in each location's own time zone, about the day before; a
        location may change the time, name its recipients or switch it off). Without `date` this is that morning job, claimed once per location per
        local day: when the day's digest has already gone it sends nothing and answers `already_done_today`. With `date` it builds and sends that day's
        summary now, unclaimed. Aggregates the business date's checklist runs — which checklists are COMPLETE vs OPEN,
        per-item done counts, who completed items, and the still-outstanding items — into a plain-text and
        HTML summary, then emails it to the location's own list of up to five addresses — each one of the business's own people (a sign-in or a
        person on its People page; any other is left out) — or to the business's active managers when it names none. Spends `checklistDigest`
        (5/hour per business).

        Dev-safe: when email is not set up on the server or the recipient is blank it
        does NOT fail — it returns `200` with `status: email_not_configured` (or
        `no_recipient`) plus the rendered `textBody`/`htmlBody`, so the aggregation is testable without a live
        mail account. A send that
        is refused or fails is reported as `send_failed` (also `200`). A successful send returns `202`.
      parameters:
        - name: date
          in: query
          required: false
          description: Business date `yyyy-MM-dd` (defaults to today, Africa/Johannesburg).
          schema: { type: string }
        - name: locationId
          in: query
          required: false
          description: Filter to runs whose parent checklist is scoped to this location.
          schema: { type: string }
      responses:
        "202":
          description: "Summary built and emailed (status `sent`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ChecklistSummarySendResponse" }
        "200":
          description: >-
            Summary built; not emailed (status one of `already_done_today`, `email_not_configured`, `no_recipient`,
            `send_failed`). The rendered body is still returned.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ChecklistSummarySendResponse" }
        "400":
          description: "Invalid `date` (`error:` `invalid_date`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "Caller is not a manager (`error:` `manager_required`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`location_not_found` — `locationId` is not one of this business's locations."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: "More than the `checklistDigest` bucket allows (5 an hour per business); see `Retry-After`."
        "409":
          description: "`digest_in_hand` — the day's digest could not be claimed or sent just now; it is tried again within the day."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ───────────────────────────── Booking ─────────────────────────────
  /api/v1/booking/availability:
    get:
      tags: [Booking]
      summary: Suggested reservation time slots for a date + party size
      description: |
        Public — no JWT required. Rate limit bucket `booking`: 60 requests/min. Returns the slots of the
        location's booking schedules for that weekday (with none set up, every 30 minutes from 11:00 to a last
        seating at 21:00, Africa/Johannesburg); none on a closed date. A slot is `available` when (T-12.1) a
        reservable table, or a table group, is free for the party's whole stay — the venue's turn time for that
        party size, returned as `durationMinutes` — the slot has pacing room, and any covers cap holds. Past
        slots for today are omitted.
      x-rate-limit: "booking: 60/min"
      security: []
      parameters:
        - name: loc
          in: query
          required: true
          description: Location id.
          schema: { type: string }
        - name: date
          in: query
          required: true
          description: Booking date, `yyyy-MM-dd` (Africa/Johannesburg).
          schema: { type: string, example: "2026-07-20" }
        - name: partySize
          in: query
          required: true
          description: Number of guests (1..20).
          schema: { type: integer }
      responses:
        "200":
          description: Available/unavailable slots for the date.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingAvailabilityResponse" }
        "400":
          description: "Invalid input (`error:` one of `missing_loc`, `missing_date`, `invalid_date`, `missing_party_size`, `invalid_party_size`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: |
            The venue is not taking online bookings (`error: booking_not_available`) — the tenant's licence
            does not include the Restaurant product, the product is switched off, the branch is retired, or
            the manager has turned the booking widget off. One code for all four on purpose: to the guest
            they are the same fact, and which one it is belongs in the back office.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/availability/days:
    get:
      tags: [Booking]
      summary: Availability for up to 90 days at once
      description: |
        Public — no JWT required, same `booking` rate limit. The same engine as `/booking/availability`, for
        `days` consecutive days from `from` (default 30, at most 90) — what a booking partner needs to show
        real-time availability ahead. A closed date (a blackout, or a weekday with no bookable hours) is
        `closed: true` with no slots. Answered from one load of the location's tables, schedules, closed dates,
        turn times and bookings.
      x-rate-limit: "booking: 60/min"
      security: []
      parameters:
        - { name: loc, in: query, required: true, schema: { type: string } }
        - { name: from, in: query, required: true, schema: { type: string, format: date } }
        - { name: days, in: query, schema: { type: integer, minimum: 1, maximum: 90, default: 30 } }
        - { name: partySize, in: query, required: true, schema: { type: integer, minimum: 1, maximum: 20 } }
      responses:
        "200":
          description: One entry per day.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AvailabilityRangeResponse" }
        "400":
          description: "`missing_loc`, `missing_from`, `invalid_date`, `invalid_days`, `missing_party_size`, `invalid_party_size`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: The venue is not taking online bookings (`booking_not_available`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking-blackouts:
    get:
      tags: [Booking]
      summary: A location's closed dates
      description: Dates the location takes no online bookings (V111), soonest first. Manager-only.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The closed dates.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/BookingBlackout" } }
        "400":
          description: "`locationId_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
    post:
      tags: [Booking]
      summary: Close a date to online bookings
      description: |
        Closes a date at a location for the widget, the range and the guest's own booking. Closing a date already
        closed updates its note. The note is the venue's and never reaches a guest. Manager-only; a past date is refused.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [locationId, date]
              properties:
                locationId: { type: string }
                date: { type: string, format: date }
                reason: { type: string, nullable: true, maxLength: 200 }
      responses:
        "200":
          description: The closed date.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingBlackout" }
        "400":
          description: "`invalid_date`, `date_in_past`, `reason_too_long`, `invalid_location`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/booking-blackouts/{id}:
    delete:
      tags: [Booking]
      summary: Open a closed date again
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Opened.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`blackout_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/booking/reservations:
    post:
      tags: [Booking]
      summary: Create a guest reservation (PENDING)
      description: |
        Public — no JWT required. Rate limit bucket `booking`: 60 requests/min. Creates a `PENDING`
        reservation (no table assigned — staff confirm + seat later). Validates hard: `partySize` 1..20,
        a future `reservedForAt` within 90 days, at least one contact (`phone` or `email`), and re-runs the
        pacing + capacity gate — a full window returns `409 booking_unavailable`.
      x-rate-limit: "booking: 60/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BookingReservationRequest" }
      responses:
        "201":
          description: Reservation created (PENDING).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingReservationResponse" }
        "400":
          description: "Invalid input (`error:` one of `guest_name_required`, `guest_name_too_long`, `invalid_party_size`, `contact_required`, `phone_too_long`, `email_too_long`, `notes_too_long`, `invalid_allergy`, `reservation_in_past`, `reservation_too_far`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "The venue is not taking online bookings (`error: booking_not_available`) — see GET /api/v1/booking/availability."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "No capacity at that time (`error: booking_unavailable`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/enquiries:
    post:
      tags: [Booking]
      summary: A party too large to book online asks (an enquiry, not a booking)
      description: |
        Public — no JWT required. Rate limit buckets `booking` (60 requests/min) and `bookingEnquiry` (5 an hour per client, spent
        before the body is read; the body is read within 8 KB, else `413`). A party above what the booking page books
        (21 to 200 guests) sends a request instead of being told it cannot book: a `date` (`yyyy-MM-dd`) and a `time` as typed
        (`19:30`) in South African time, the party, a name, a `phone` or an `email`, and a note. It lands in the venue's guest
        inbox for a host to accept or decline. **It is not a booking**: it holds no table, counts towards no covers cap and is
        never offered to Reserve with Google until a host accepts it. `requestId` is minted once for a submit and sent again on
        its every retry: the same id at the same location is the one enquiry, answered with its first copy's details. One client
        network (an IPv4 /24, an IPv6 /56, kept only as a keyed hash) holds at most 3 unanswered enquiries at a location, and a venue
        at most 100; past either the door answers `429 rate_limited`. An enquiry nobody answered lapses once its time passes, and
        a closed one keeps the guest's details for 30 days; erasing the guest withdraws an open one and clears it at once.
      x-rate-limit: "booking: 60/min"
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [locationId, guestName, partySize, date, time, requestId]
              properties:
                locationId: { type: string }
                guestName: { type: string, maxLength: 100 }
                partySize: { type: integer, minimum: 21, maximum: 200 }
                date: { type: string, format: date }
                time: { type: string, example: "19:30" }
                phone: { type: string, maxLength: 60, nullable: true }
                email: { type: string, maxLength: 60, nullable: true }
                notes: { type: string, maxLength: 500, nullable: true }
                requestId: { type: string, minLength: 16, maxLength: 128 }
      responses:
        "201":
          description: The enquiry as it was taken (a retry answers with the first copy's details).
          content:
            application/json:
              schema:
                type: object
                required: [guestName, partySize, wantedAt]
                properties:
                  guestName: { type: string }
                  partySize: { type: integer }
                  wantedAt: { type: integer, format: int64 }
        "400":
          description: "Invalid input (`error:` one of `guest_name_required`, `guest_name_too_long`, `invalid_party_size`, `contact_required`, `phone_too_long`, `email_too_long`, `notes_too_long`, `request_id_required`, `invalid_enquiry_time`, `reservation_in_past`, `reservation_too_far`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "The venue is not taking online bookings (`error: booking_not_available`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/manage:
    get:
      tags: [Booking]
      summary: A guest's own booking, by the link they were given
      description: |
        Public — the key in the `X-Ruva-Booking-Key` header is the only key, and it names one booking. A header, not the
        address: an address is written down by every request log on its way (T-2.32 review). Returned once, as
        `manageToken`, when the booking is made and shown to the guest as `/book?loc=…#manage=…`; the server keeps only its hash, so a wrong,
        missing or retired key answers `404 booking_not_found`, exactly as an unknown booking does. Says what cancelling now would cost under
        the venue's policy (`cancelRefundCents`, `cancelKeptCents`), whether the guest may still change it
        (`changeRefusal`, `moveRefusal`), and an unpaid deposit's `payUrl` (Yoco's checkout, keyed on the deposit, or
        the PayFast page). Rate limit bucket `booking`.
      x-rate-limit: "booking: 60/min"
      security: []
      parameters:
        - { name: X-Ruva-Booking-Key, in: header, required: true, schema: { type: string }, description: "The guest's booking key." }
      responses:
        "200":
          description: The booking as its guest sees it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingManageView" }
        "404":
          description: "`error: booking_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/manage/cancel:
    post:
      tags: [Booking]
      summary: The guest cancels their booking
      description: |
        Public, by the booking key in the `X-Ruva-Booking-Key` header. The booking is released; a paid deposit is settled by the venue's policy — all of
        it back inside the free-cancellation window, otherwise the late fee kept (never more than was paid) and the
        rest returned through the rail it came in on, Yoco's or PayFast's refund API (`refundByHand` once that refund turned
        out to need the venue, e.g. a PayFast refund only payable into the guest's bank account).
        A second cancel answers what the first did and changes nothing. Refused (`409 booking_change_refused`, the
        sentence in `message`) once the booking's time has passed or it is seated, completed or a no-show.
      x-rate-limit: "booking: 60/min"
      security: []
      parameters:
        - { name: X-Ruva-Booking-Key, in: header, required: true, schema: { type: string }, description: "The guest's booking key." }
      responses:
        "200":
          description: What happened to the deposit.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingCancelResult" }
        "404":
          description: "`error: booking_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`error: booking_change_refused`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/manage/move:
    post:
      tags: [Booking]
      summary: The guest moves their booking to another time
      description: |
        Public, by the booking key in the `X-Ruva-Booking-Key` header. Same party, same deposit; the availability engine decides, as it does for a new
        booking, and the table it held is released for the host to place again. Only while cancelling is still free —
        a later move would restart the free window — so inside the window it is `409 booking_change_refused`.
      x-rate-limit: "booking: 60/min"
      security: []
      parameters:
        - { name: X-Ruva-Booking-Key, in: header, required: true, schema: { type: string }, description: "The guest's booking key." }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BookingMoveRequest" }
      responses:
        "200":
          description: The moved booking.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingManageView" }
        "400":
          description: "`error: booking_in_past`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`error: booking_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`error: booking_unavailable` (no table then) or `booking_change_refused`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/manage/{token}:
    get:
      tags: [Booking]
      summary: A guest's own booking, by the link they were given
      description: |
        A link sent before the key moved to a header (T-2.32 review) still opens here; new callers send the key in
        `X-Ruva-Booking-Key` to `/api/v1/booking/manage`. **Sunset 2027-03-01 00:00 SAST (2027-02-28 22:00 UTC): from then this door answers `410 Gone`
        (`booking_link_retired`) for every key, right or wrong.** Public — the token in the path is the only key, and it names one booking. Returned once, as `manageToken`, when
        the booking is made and shown to the guest as `/book?loc=…&manage=…`; the server keeps only its hash, so a wrong,
        missing or retired key answers `404 booking_not_found`, exactly as an unknown booking does. Says what cancelling now would cost under
        the venue's policy (`cancelRefundCents`, `cancelKeptCents`), whether the guest may still change it
        (`changeRefusal`, `moveRefusal`), and an unpaid deposit's `payUrl` (Yoco's checkout, keyed on the deposit, or
        the PayFast page). Rate limit bucket `booking`.
      x-rate-limit: "booking: 60/min"
      security: []
      deprecated: true
      x-sunset: "2027-02-28T22:00:00Z"
      parameters:
        - { name: token, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The booking as its guest sees it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingManageView" }
        "404":
          description: "`error: booking_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "410":
          description: "`error: booking_link_retired` — this path door is retired from 2027-03-01 00:00 SAST (2027-02-28 22:00 UTC); send the key in `X-Ruva-Booking-Key` to `/api/v1/booking/manage`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/manage/{token}/cancel:
    post:
      tags: [Booking]
      summary: The guest cancels their booking
      description: |
        **Sunset 2027-03-01 00:00 SAST (2027-02-28 22:00 UTC): from then this door answers `410 Gone` (`booking_link_retired`); use `/api/v1/booking/manage/cancel`
        with the key in `X-Ruva-Booking-Key`.** Public, by the manage token. The booking is released; a paid deposit is settled by the venue's policy — all of
        it back inside the free-cancellation window, otherwise the late fee kept (never more than was paid) and the
        rest returned through the rail it came in on, Yoco's or PayFast's refund API (`refundByHand` once that refund turned
        out to need the venue, e.g. a PayFast refund only payable into the guest's bank account).
        A second cancel answers what the first did and changes nothing. Refused (`409 booking_change_refused`, the
        sentence in `message`) once the booking's time has passed or it is seated, completed or a no-show.
      x-rate-limit: "booking: 60/min"
      security: []
      deprecated: true
      x-sunset: "2027-02-28T22:00:00Z"
      parameters:
        - { name: token, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: What happened to the deposit.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingCancelResult" }
        "404":
          description: "`error: booking_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`error: booking_change_refused`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "410":
          description: "`error: booking_link_retired` — this path door is retired from 2027-03-01 00:00 SAST (2027-02-28 22:00 UTC); send the key in `X-Ruva-Booking-Key` to `/api/v1/booking/manage`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/booking/manage/{token}/move:
    post:
      tags: [Booking]
      summary: The guest moves their booking to another time
      description: |
        **Sunset 2027-03-01 00:00 SAST (2027-02-28 22:00 UTC): from then this door answers `410 Gone` (`booking_link_retired`); use `/api/v1/booking/manage/move`
        with the key in `X-Ruva-Booking-Key`.** Public, by the manage token. Same party, same deposit; the availability engine decides, as it does for a new
        booking, and the table it held is released for the host to place again. Only while cancelling is still free —
        a later move would restart the free window — so inside the window it is `409 booking_change_refused`.
      x-rate-limit: "booking: 60/min"
      security: []
      deprecated: true
      x-sunset: "2027-02-28T22:00:00Z"
      parameters:
        - { name: token, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BookingMoveRequest" }
      responses:
        "200":
          description: The moved booking.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingManageView" }
        "400":
          description: "`error: booking_in_past`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`error: booking_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`error: booking_unavailable` (no table then) or `booking_change_refused`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "410":
          description: "`error: booking_link_retired` — this path door is retired from 2027-03-01 00:00 SAST (2027-02-28 22:00 UTC); send the key in `X-Ruva-Booking-Key` to `/api/v1/booking/manage`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /api/v1/reservations/policy:
    get:
      tags: [Booking]
      summary: This branch's booking deposit and no-show policy
      description: |
        Any signed-in staff member may read it. `depositRail` is the online rail a deposit is taken on (`YOCO`, else
        `PAYFAST`), or absent when none is set up — and then no deposit can be asked for.
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The policy (defaults when none is saved — no deposit).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingPolicyView" }
        "400":
          description: "`error: missing_location_id`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
    put:
      tags: [Booking]
      summary: Save this branch's booking deposit and no-show policy
      description: |
        Manager-gated. Refused (`400 invalid_booking_policy`, the remedy in `message`) when the late fee is more than
        the deposit it comes out of, the hold is outside 5 minutes to a day, free cancellation is beyond 14 days or the
        grace beyond 180 minutes; `409 no_deposit_rail` when a deposit is set and no online payment is.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BookingPolicyView" }
      responses:
        "200":
          description: The saved policy.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingPolicyView" }
        "400":
          description: "`error: invalid_booking_policy`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`error: manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`error: no_deposit_rail`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/guest-messages:
    get:
      tags: [Booking]
      summary: The venue's WhatsApp inbox — guests' replies and what was sent them
      description: |
        Needs `MANAGE_RESERVATIONS`. The latest 200 messages either way, newest first, with how many from guests are
        unread. A guest's number is given by its last four digits only (`phoneEnding`). A Cancel or a "yes" listed here
        has already been applied to the booking.
      responses:
        "200":
          description: The inbox.
          content:
            application/json:
              schema:
                type: object
                properties:
                  unread: { type: integer }
                  messages:
                    type: array
                    items:
                      type: object
                      required: [id, direction, kind, status, createdAt]
                      properties:
                        id: { type: string }
                        reservationId: { type: string, nullable: true }
                        guestName: { type: string, nullable: true }
                        reservedForAt: { type: integer, format: int64, nullable: true }
                        direction: { type: string, enum: [IN, OUT] }
                        kind: { type: string, enum: [CONFIRMATION, REMINDER_DAY_BEFORE, REMINDER_TWO_HOURS, REPLY, STAFF_REPLY] }
                        status: { type: string, enum: [SENDING, SENT, FAILED, RECEIVED] }
                        body: { type: string, nullable: true }
                        phoneEnding: { type: string }
                        readAt: { type: integer, format: int64, nullable: true }
                        createdAt: { type: integer, format: int64 }
                        channel: { type: string, enum: [WHATSAPP, EMAIL], description: "The way an outgoing confirmation or reminder went (T-27.7); an email row has no number." }
                  enquiries:
                    type: array
                    description: "The large-party enquiries waiting for a host, oldest first (T-27.9). Requests, not bookings: no table is held."
                    items:
                      type: object
                      required: [id, locationId, guestName, partySize, wantedAt, createdAt]
                      properties:
                        id: { type: string }
                        locationId: { type: string }
                        guestName: { type: string }
                        partySize: { type: integer }
                        wantedAt: { type: integer, format: int64 }
                        phone: { type: string, nullable: true }
                        email: { type: string, nullable: true }
                        notes: { type: string, nullable: true }
                        createdAt: { type: integer, format: int64 }
                  awaitingDeposit:
                    type: array
                    description: "Accepted large-party bookings still PENDING on an unpaid deposit, soonest first (T-27.9): the pay link and when its hold ends, for the host to copy and send. While the link has reached nobody (`guestToldBy` null) the hold has not started; it ends at most a day after the deposit was asked."
                    items:
                      type: object
                      required: [enquiryId, reservationId, guestName, partySize, reservedForAt, deposit]
                      properties:
                        enquiryId: { type: string }
                        reservationId: { type: string }
                        guestName: { type: string }
                        partySize: { type: integer }
                        reservedForAt: { type: integer, format: int64 }
                        phone: { type: string, nullable: true }
                        email: { type: string, nullable: true }
                        deposit:
                          type: object
                          required: [amountCents, holdUntil, status]
                          properties:
                            amountCents: { type: integer, format: int64 }
                            payUrl: { type: string, nullable: true }
                            holdUntil: { type: integer, format: int64 }
                            status: { type: string }
                        guestToldBy: { type: string, enum: [WHATSAPP, EMAIL], nullable: true }
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/booking-enquiries/{id}/accept:
    post:
      tags: [Booking]
      summary: Accept a large party's enquiry — makes the booking
      description: |
        Needs `MANAGE_RESERVATIONS`. Makes one booking through the host desk's own writers: the best-fitting table or join is set
        aside if one is free (`noTableFree` says none was, and the host seats it by hand — the host chose to take the party), the
        venue's deposit policy is applied (a deposit is asked and its `deposit.payUrl` is sent to the guest once, by WhatsApp where
        the venue has it on, else email — `guestToldBy` says which, null when nothing could be sent and the host sends it; the
        deposit's hold runs from that send (until it, at most a day from the accept), and the booking stays `PENDING` until it is paid), and with no deposit owed the booking
        is `CONFIRMED` and the guest told as for any confirmation. Accepting twice answers the first booking and its link, makes no
        second and sends nothing again. An enquiry already declined is `409 enquiry_answered`; one withdrawn with its erased guest,
        lapsed, past its time or at a closed location is `409` (`enquiry_closed`, `enquiry_past`, `location_closed`).
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The booking the enquiry made.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingEnquiryAnswered" }
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`error: enquiry_not_found` (another business's enquiry answers the same)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`error: enquiry_answered`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/booking-enquiries/{id}/decline:
    post:
      tags: [Booking]
      summary: Decline a large party's enquiry
      description: |
        Needs `MANAGE_RESERVATIONS`. Closes the enquiry; no booking is made, and the guest is told once, as for an accept
        (`guestToldBy`). Declining twice is the same answer and sends nothing again; an accepted enquiry is
        `409 enquiry_answered` (cancel its booking instead).
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Declined.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingEnquiryAnswered" }
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`error: enquiry_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`error: enquiry_answered`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/guest-messages/{id}/read:
    post:
      tags: [Booking]
      summary: Mark a guest's message read
      description: Needs `MANAGE_RESERVATIONS`. Only a message from a guest can be marked.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204": { description: Marked. }
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
  /api/v1/reservations/{id}/messages:
    post:
      tags: [Booking]
      summary: Answer a booking's guest on WhatsApp
      description: |
        Needs `MANAGE_RESERVATIONS`. WhatsApp lets a business send free text only within 24 hours of the guest's own
        last message: outside it the answer is `409 outside_service_window` with the reason, and the host calls instead.
        `400 no_phone` when the booking has no mobile number; `502 whatsapp_send_failed` when WhatsApp refused it
        (the attempt is kept in the inbox as not delivered); `502 whatsapp_send_unconfirmed` when there was no answer, so the
        guest may have it (kept in the inbox as not confirmed: check before sending again).
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [text]
              properties:
                text: { type: string, minLength: 1, maxLength: 1000 }
      responses:
        "201": { description: Sent and recorded. }
        "400":
          description: "`error: invalid_text` or `no_phone`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`error: outside_service_window`, or `whatsapp_switched_off` (the booking's location turned WhatsApp off, T-5.5)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/whatsapp/webhook:
    get:
      tags: [Booking]
      summary: Meta's webhook address check (public)
      description: "Answers `hub.challenge` when `hub.mode=subscribe` and `hub.verify_token` is this server's verify token; 403 otherwise. Rate limit bucket `whatsapp`: 6000 requests/min."
      x-rate-limit: "whatsapp: 6000/min"
      security: []
      parameters:
        - { name: hub.mode, in: query, required: true, schema: { type: string } }
        - { name: hub.verify_token, in: query, required: true, schema: { type: string } }
        - { name: hub.challenge, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The challenge, as plain text.
          content:
            text/plain:
              schema: { type: string }
        "403": { description: "`error: verify_token_mismatch`." }
    post:
      tags: [Booking]
      summary: A guest's WhatsApp messages, posted by Meta (public, signed)
      description: |
        Public — no JWT. What authorises it is `X-Hub-Signature-256: sha256=<hex>`, an HMAC-SHA256 of the **raw** body
        under the Meta app's App Secret; unsigned or mis-signed is `401 bad_signature` before anything is read, and with
        no App Secret configured every post is `503`. Each message acts once by its id: a quick reply (I'm coming,
        Change, Cancel) acts on the booking it names when the sender is that booking's phone; a typed reply belongs to
        the booking of the message of ours it quotes, sent to that phone. The number is shared with another application,
        so Meta posts every event on the account here: an event for another phone number id, a delivery status, and a
        typed message that quotes nothing of ours are acknowledged and acted on not at all. Only on a number of Ruva's
        own (`WHATSAPP_NUMBER_SHARED=false`) does a typed reply fall back to the venue's last message to that phone
        within 24 hours. Rate limit bucket `whatsapp`: 6000 requests/min, its own, so that traffic spends no other
        webhook's budget.
      x-rate-limit: "whatsapp: 6000/min"
      security: []
      parameters:
        - { name: X-Hub-Signature-256, in: header, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, description: "Meta's webhook body (`object: whatsapp_business_account`), signed as sent." }
      responses:
        "200": { description: Read; every message in it handled once. }
        "401": { description: "`error: bad_signature`." }
        "503": { description: "`error: whatsapp_inbound_not_configured`." }
  /api/v1/inbound/mail:
    post:
      tags: [Webhooks]
      summary: A message sent to the support address, posted by the mail provider (public, signed)
      description: |
        Public — no JWT, and no business: support mail belongs to Ruva, not to a venue. What authorises it is the provider's
        signature headers (the Svix scheme: `svix-id`, `svix-timestamp`, `svix-signature`), an HMAC-SHA256 of `id.timestamp.body`
        over the **raw** body under the webhook's signing secret, with a timestamp within five minutes of now; unsigned, mis-signed
        or stale is `401 bad_signature` and nothing is read back or stored. Without the signing secret the route does not exist
        (`404`); with it but the other inbound settings unset every post is `503`.
        The body is at most 256 KB (`413`) and must arrive within ten seconds (`408 body_too_slow`).
        The notice carries no message: the body and the receiving server's SPF, DKIM and DMARC verdicts are read back from the
        provider. A message to the support address (or its `+billing` / `+security` form) becomes one ticket, once, and joins its
        sender's own thread when it replies and DMARC vouches for the sender (an unverified reply is a flagged ticket of its own);
        a recipient that is not ours, mail from Ruva's own address or the inbound domain, and any other event are acknowledged
        and stored nowhere. Every signed call that is understood is `200 {"ok":true}` whatever became of the message. A
        read-back the provider cannot give is `503 mail_unavailable`, and a message that could not be stored `503
        mail_not_stored`, so the delivery is made again. Text only: attachments are counted and dropped. Rate limit bucket
        `inboundMail`: 600 requests/min.
      x-rate-limit: "inboundMail: 600/min"
      security: []
      parameters:
        - { name: svix-id, in: header, required: true, schema: { type: string } }
        - { name: svix-timestamp, in: header, required: true, schema: { type: string } }
        - { name: svix-signature, in: header, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, description: "The provider's `email.received` notice, signed as sent (at most 256 KB)." }
      responses:
        "200": { description: "Understood; `{\"ok\":true}` whatever became of the message." }
        "401": { description: "`error: bad_signature`." }
        "408": { description: "`error: body_too_slow` (the body took more than ten seconds to arrive)." }
        "413": { description: "`error: payload_too_large`." }
        "503": { description: "`error: inbound_mail_not_configured`; `mail_unavailable` (the message could not be read back) or `mail_not_stored` (it could not be stored): deliver again." }
  /api/v1/reservations/widget:
    get:
      tags: [Booking]
      summary: This branch's booking link, embed code and on/off state
      description: |
        The back office's setup surface for the public booking widget. The URL and the `<iframe>` are built
        **server-side** from the deployment's public base URL: a client that assembled them would hand a
        venue a link that resolves on one environment and 404s on the next, printed on a menu by the time
        anyone noticed. Needs the "Manage bookings" permission, which a host holds — reading the booking
        link out over the phone is not a management act.
      parameters:
        - name: locationId
          in: query
          required: true
          description: Location id. Must belong to the caller's tenant, or 404.
          schema: { type: string }
      responses:
        "200":
          description: "The widget's link, embed snippet and state. When the location has no address yet and the business already holds 25 across its locations (deleted ones included), nothing is made: `slug` is absent, `bookingUrl` is the `/book?loc=` link, which still opens the page, and `addressNote` says why."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BookingWidgetDto" }
        "400":
          description: "`error: missing_location_id`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
    post:
      tags: [Booking]
      summary: Open or close this branch's public booking surface
      description: |
        Manager-gated. Off is not "hide the button": `/api/v1/booking/*` refuses with `booking_not_available`,
        so a link already printed on a flyer or already live on a Google Business Profile stops taking
        bookings rather than quietly filling a list nobody is reading. Scoped by tenant in the update itself,
        so another tenant's location id changes nothing and 404s. A `slug` moves the page to `/book/<slug>`; the
        address it leaves 301s to the new one for good, so a page holds at most five addresses and a sixth is
        `409 booking_slug_limit` (any of the five may be taken back); so is a new address while the business holds 25
        across its locations, deleted ones included. Spends `bookingPage`.
      x-rate-limit: "bookingPage: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BookingWidgetUpdateRequest" }
      responses:
        "200":
          description: The new state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  locationId: { type: string }
                  enabled: { type: string, example: "true" }
        "403":
          description: "`error: manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: "`error: booking_slug_taken` (another venue holds or held it) or `booking_slug_limit` (the page has held five addresses, or the business holds 25)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: "More than the `bookingPage` bucket allows for this business in a minute; see `Retry-After`."
  /book:
    get:
      tags: [Booking]
      summary: The public "Reserve a table" widget page
      description: |
        Public, **not** under `/api/v1`, and HTML rather than JSON. This is the page a venue links from its
        Google Business Profile and embeds in an `<iframe>` on its own website; it boots the same guest
        booking journey the QR app uses and calls `/api/v1/booking/*` from the browser.

        Sent with `Content-Security-Policy: frame-ancestors *` and **no** `X-Frame-Options`, so any
        customer's domain can embed it — the only path on the server for which that is true.

        It reads nothing. The response is byte-identical for a real location, an unknown one and no `loc` at
        all, so publishing the link reveals nothing about which venues are on the platform.
      x-rate-limit: "booking: 60/min"
      security: []
      parameters:
        - name: loc
          in: query
          required: false
          description: Location id. Absent or unknown still renders; the page itself fails closed.
          schema: { type: string }
      responses:
        "200":
          description: The widget page.
          content:
            text/html:
              schema: { type: string }
        "429":
          $ref: "#/components/responses/TooManyRequests"

  # ───────────────────────────── Receipts ─────────────────────────────
  /receipts/{number}:
    get:
      tags: [Receipts]
      summary: View a digital receipt (public, signed-token link)
      description: |
        Public — no JWT required, and **not** under `/api/v1`. The signed token `t` (HMAC, minted server-side
        at checkout) authorises access to exactly `tenantId|number`; an absent, tampered, expired, or
        mismatched token all 404 so sequential receipt numbers can't be probed for existence. Returns
        rendered HTML, not JSON.
      security: []
      parameters:
        - name: number
          in: path
          required: true
          description: Transaction number (e.g. `POS-000123`).
          schema: { type: string }
        - name: t
          in: query
          required: true
          description: Signed token minted by the server at checkout time.
          schema: { type: string }
      responses:
        "200":
          description: Rendered HTML receipt.
          content:
            text/html:
              schema: { type: string }
        "404":
          description: Receipt not found, or token missing/invalid/expired/mismatched (`error:"receipt_not_found"`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ── Stocktake sessions (V20) ──
  /accounting/connection:
    get:
      tags: [Accounting]
      summary: "The accounting connection (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: >
        Which system is connected, how far the push has got, and what failed.
        `credentialsPresent` says whether this server actually holds credentials for the
        provider — the difference between "nobody connected it" and "the token expired".
      responses:
        "200":
          description: 'The connection. `provider: NONE` when nothing is connected.' 
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AccountingConnection" }
    post:
      tags: [Accounting]
      summary: "Connect, pause, or set the earliest period (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: >
        Credentials are NEVER accepted here — they come from the environment, so a
        compromised session cannot exfiltrate or replace the keys to a venue's ledger.
        `provider: "NONE"` or `active: false` pauses the push without forgetting the settings.
        Pausing never asks for more; switching a paused connection back on does: where the owner requires two-factor
        sign-in, a session that has not proved it is refused `403 second_factor_required` (T-41.58).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AccountingConnectionRequest" }
      responses:
        "200":
          description: Saved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AccountingConnection" }
        "400":
          description: '`unknown_provider` or `invalid_date`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: '`permission_required`, or `second_factor_required` — a paused connection switched back on by a session that has not typed its code.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/ledgr/key:
    post:
      tags: [Accounting]
      summary: "Keep this business's own Ledgr API key (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: >
        Ledgr checks the key before anything is kept: a key Ledgr refuses, or one that may not post journals, is not
        saved. A key that reaches more than one company answers `saved: false` with the companies to choose from; send
        it again with `companyId`. The key is kept sealed and never returned — the connection shows only its last four
        characters. Rate-limited per client by the `ledgrKey` bucket. Where the owner requires two-factor sign-in, a session
        that has not proved it is refused `403 second_factor_required` before anything is checked, as authorising another
        package (`POST /accounting/oauth/start`) is (T-41.58).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [apiKey]
              properties:
                apiKey: { type: string, description: "The key Ledgr showed when it was made." }
                companyId: { type: string, description: "The Ledgr company to post into, when the key reaches several." }
      responses:
        "200":
          description: Kept, with the connection as it now stands; or not yet, with the companies to choose from.
          content:
            application/json:
              schema:
                type: object
                required: [saved]
                properties:
                  saved: { type: boolean }
                  connection: { $ref: "#/components/schemas/AccountingConnection" }
                  companies:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        name: { type: string }
        "400":
          description: '`ledgr_key_missing` or `ledgr_key_malformed`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: '`permission_required`, or `second_factor_required` — the business requires two-factor sign-in and this session has not typed its code.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`ledgr_not_on_this_server`: this server does not post to Ledgr.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "422":
          description: '`ledgr_key_refused`, `ledgr_postings_refused`, `ledgr_no_company` or `ledgr_company_unknown`, in a sentence that says what to do.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429":
          description: Too many key checks from this client; try again later.
        "502":
          description: '`ledgr_unreachable`: Ledgr could not check the key just now, so nothing was kept.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: '`credentials_unstorable`: this server cannot keep a key safely, so nothing was kept.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: [Accounting]
      summary: "Forget this business's Ledgr key (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: Nothing more posts to Ledgr until a key is kept again; what was posted stays posted.
      responses:
        "200":
          description: The connection as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AccountingConnection" }
        "409":
          description: '`ledgr_no_key`: no Ledgr key is kept for this business.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /accounting/sync:
    post:
      tags: [Accounting]
      summary: "Push unposted journals now (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: >
        Oldest first. Each entry is claimed before the request goes out (unique on
        tenant+entry) and carries a derived idempotency key, so a retry after a timeout
        re-sends the same document rather than duplicating revenue. `inFlight` counts
        entries whose outcome is unknown and which stay claimed for the next run.
      parameters:
        - { name: limit, in: query, required: false, schema: { type: integer, default: 100, minimum: 1, maximum: 500 } }
      responses:
        "200":
          description: What the batch did. `notConfigured` when there is nothing to push to.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AccountingSyncResult" }
  /api/v1/costing/shipments/{id}:
    get:
      tags: [Inventory]
      summary: A landed-cost shipment with its charges and lines (VIEW_COST)
      description: The header, every charge, every line (with its product's name and the last apportionment's figures) and `mayChange`, false once posted.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200":
          description: The shipment and what is on it.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  reference: { type: string }
                  status: { type: string, enum: [DRAFT, APPORTIONED, POSTED] }
                  currency: { type: string }
                  fxRateMicros: { type: integer, format: int64, nullable: true }
                  arrivedAt: { type: integer, format: int64, nullable: true }
                  notes: { type: string, nullable: true }
                  charges: { type: array, items: { type: object } }
                  lines: { type: array, items: { type: object } }
                  mayChange: { type: boolean }
        "403":
          description: The caller lacks VIEW_COST.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such shipment in this business, or it was removed (`unknown_shipment`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
    post:
      tags: [Inventory]
      summary: Change a landed-cost shipment's reference, currency, rate, arrival and notes (MANAGE_PURCHASING)
      description: |
        Refused once the shipment is posted (`409 shipment_posted`, with the remedy: a revaluation). A costed shipment goes back
        to DRAFT and its lines' apportioned figures are cleared, to be apportioned again. Every field is the new value.
      parameters:
        - $ref: "#/components/parameters/PathId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reference]
              properties:
                reference: { type: string }
                currency: { type: string }
                fxRateMicros: { type: integer, format: int64, nullable: true }
                arrivedAt: { type: integer, format: int64, nullable: true }
                notes: { type: string, nullable: true }
      responses:
        "200": { description: Changed. }
        "400":
          description: No reference, or a rate of 0 or less.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such shipment in this business (`unknown_shipment`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The shipment is posted (`shipment_posted`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/costing/shipments/{id}/delete:
    post:
      tags: [Inventory]
      summary: Remove a landed-cost shipment (MANAGE_PURCHASING)
      description: Refused once posted (`409 shipment_posted`). Removing one already removed answers the same.
      parameters:
        - $ref: "#/components/parameters/PathId"
      responses:
        "200": { description: Removed. }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such shipment in this business (`unknown_shipment`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The shipment is posted (`shipment_posted`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/costing/shipments/{id}/charges/{chargeId}:
    post:
      tags: [Inventory]
      summary: Change a charge on a landed-cost shipment (MANAGE_PURCHASING)
      description: The same checks as adding one; refused once the shipment is posted (`409 shipment_posted`). A costed shipment goes back to DRAFT.
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: chargeId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [kind, amountCents]
              properties:
                kind: { type: string, enum: [FREIGHT, DUTY, CLEARING, INSURANCE, HANDLING, OTHER] }
                amountCents: { type: integer, format: int64 }
                basis: { type: string, enum: [BY_VALUE, BY_WEIGHT, BY_QUANTITY] }
                description: { type: string, nullable: true }
      responses:
        "200": { description: Changed. }
        "400":
          description: An unknown kind or basis, or a negative amount.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such shipment or charge (`unknown_shipment`, `unknown_charge`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The shipment is posted (`shipment_posted`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/costing/shipments/{id}/charges/{chargeId}/delete:
    post:
      tags: [Inventory]
      summary: Remove a charge from a landed-cost shipment (MANAGE_PURCHASING)
      description: Refused once the shipment is posted (`409 shipment_posted`). Removing one already gone answers the same.
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: chargeId, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: Removed. }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such shipment in this business (`unknown_shipment`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The shipment is posted (`shipment_posted`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/costing/shipments/{id}/lines/{lineId}:
    post:
      tags: [Inventory]
      summary: Change a goods line on a landed-cost shipment (MANAGE_PURCHASING)
      description: The same checks as adding one; refused once the shipment is posted (`409 shipment_posted`). A costed shipment goes back to DRAFT.
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: lineId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [productId, quantityUnits, goodsCostCents]
              properties:
                productId: { type: string }
                quantityUnits: { type: integer, format: int64 }
                goodsCostCents: { type: integer, format: int64 }
                weightGrams: { type: integer, format: int64, nullable: true }
      responses:
        "200": { description: Changed. }
        "400":
          description: No units, a negative cost, or an unknown product.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such shipment or line (`unknown_shipment`, `unknown_line`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The shipment is posted (`shipment_posted`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/costing/shipments/{id}/lines/{lineId}/delete:
    post:
      tags: [Inventory]
      summary: Remove a goods line from a landed-cost shipment (MANAGE_PURCHASING)
      description: Refused once the shipment is posted (`409 shipment_posted`). Removing one already gone answers the same.
      parameters:
        - $ref: "#/components/parameters/PathId"
        - { name: lineId, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: Removed. }
        "403":
          description: The caller lacks MANAGE_PURCHASING.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such shipment in this business (`unknown_shipment`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: The shipment is posted (`shipment_posted`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/costing/products/{id}/method:
    get:
      tags: [Inventory]
      summary: How a product's stock is costed (T-8.5)
      description: MOVING_AVERAGE (the default) or FIFO. Manager-only.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The product's method.
          content:
            application/json:
              schema: { type: object, required: [method], properties: { method: { type: string, enum: [MOVING_AVERAGE, FIFO] } } }
        "404":
          description: Unknown product, or another tenant's.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    put:
      tags: [Inventory]
      summary: Set a product's costing method (T-8.5)
      description: >-
        Applies to every issue from then on. Switching to FIFO opens what each location holds as its oldest cost
        layer at its current value; switching back drops the layers. No value changes either way. Manager-only.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [method], properties: { method: { type: string, enum: [MOVING_AVERAGE, FIFO] } } }
      responses:
        "200":
          description: The method now in force.
          content:
            application/json:
              schema: { type: object, required: [method], properties: { method: { type: string } } }
        "400":
          description: '`unknown_costing_method`, or `standard_costing_not_supported` — no ledger path applies standard costing.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: Unknown product, or another tenant's.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /service-orders/{id}/costing:
    get:
      tags: [Shipping]
      summary: The costing sheet on a workshop job (V70)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The sheet, or exists=false when the job has none yet.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceCosting" }
        "404":
          description: Unknown job, or another tenant's.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /service-orders/{id}/costing/lines:
    post:
      tags: [Shipping]
      summary: Replace the labour and parts lines
      description: >-
        Labour is hours x rate; parts are catalogue products. The two are never conflated —
        a part billed in hours is refused, as is labour holding a product, because the split is
        the only margin question a service desk runs on. A part at a price that is not the
        catalogue's for this customer and quantity, or any labour rate, needs management: the
        caller, or the manager named in `approverStaffId`.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [lines]
              properties:
                lines:
                  type: array
                  items: { $ref: "#/components/schemas/ServiceCostingLine" }
                approverStaffId: { type: string, nullable: true, description: "A manager of this business standing for a part's own price or a labour rate." }
      responses:
        "200":
          description: The updated sheet.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceCosting" }
        "400":
          description: '`a_part_is_not_billed_in_hours`, `labour_cannot_hold_a_product`, `labour_needs_hours_and_rate`, `unknown_product`, `already_closed`, `quote_needs_manager`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`quote_exceeded` — the message names both exits (re-approve, or a manager write-off).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /service-orders/{id}/costing/quote:
    post:
      tags: [Shipping]
      summary: Record the quoted figure
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties: { cents: { type: integer, format: int64, minimum: 0 } }
      responses:
        "200":
          description: The updated sheet.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceCosting" }
  /service-orders/{id}/costing/approve:
    post:
      tags: [Shipping]
      summary: Record what the customer agreed to
      description: >-
        Ordinary counter work, not manager-gated — phoning a customer for a bigger number is not
        a manager task. The job may never bill more than this, less any write-off.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties: { cents: { type: integer, format: int64, minimum: 0 } }
      responses:
        "200":
          description: The updated sheet.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceCosting" }
        "409":
          description: '`approval_below_work_done`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /service-orders/{id}/costing/write-off:
    post:
      tags: [Shipping]
      summary: Absorb an overrun (Manager-gated)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties: { cents: { type: integer, format: int64, minimum: 0 } }
      responses:
        "200":
          description: The updated sheet.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceCosting" }
        "403":
          description: '`manager_required` — money leaving the business is a manager decision.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`write_off_exceeds_work`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/service-orders/{id}/deposit-refund:
    post:
      tags: [Shipping]
      summary: Refund or keep the deposit an abandoned repair still holds (REFUND; never a screen paired as itself)
      description: >-
        An abandoned repair whose deposit was left HELD keeps that money in Customer Deposits Held (2330) until a person ends it.
        `outcome` `REFUND` pays the whole of it back by `tender` (`CASH` out of the open register `shiftId`, or the caller's own;
        or `STORE_CREDIT` to the customer) and books Dr 2330 / Cr 1000 or 2300. Any other tender is a 400 `invalid_refund_method`:
        this door calls no card provider or bank, so a card deposit is refunded through the provider's own refund or the till's card refund.
        `FORFEIT` keeps the whole of it as income and books Dr 2330 / Cr fee income / Cr output VAT — a standard-rated supply on the
        day it is kept, declared on that day's VAT return. `amountCents` must be the whole deposit held. Once: the same call again
        answers the first result (its `tender` included) with `replayed` true and writes nothing; another outcome, amount or tender is
        409 `deposit_already_released`. The audit log carries who, the outcome and the amount.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [outcome, amountCents]
              properties:
                outcome: { type: string, enum: [REFUND, FORFEIT] }
                amountCents: { type: integer, format: int64, minimum: 1 }
                tender: { type: string, enum: [CASH, STORE_CREDIT], description: A REFUND only. }
                shiftId: { type: string, description: The open register a CASH refund is paid out of. }
      responses:
        "200":
          description: The job as it now reads, and what was done.
          content:
            application/json:
              schema:
                type: object
                properties:
                  order: { type: object, description: "The service order, with `depositAwaitingCents`, `depositReleasedAt` and `depositOutcome` (`REFUNDED` or `FORFEITED`)." }
                  outcome: { type: string, enum: [REFUNDED, FORFEITED] }
                  amountCents: { type: integer, format: int64 }
                  vatCents: { type: integer, format: int64, description: The output VAT in a forfeiture; 0 for a refund. }
                  tender: { type: string, nullable: true }
                  shiftId: { type: string, nullable: true }
                  releasedAt: { type: integer, format: int64 }
                  replayed: { type: boolean }
        "400":
          description: '`invalid_outcome`, `invalid_amount`, `invalid_refund_method` (a tender other than CASH or STORE_CREDIT), or `refund_method_required`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: Needs the REFUND permission.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: '`service_order_not_found`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`deposit_not_held` (not abandoned with the deposit held, or nothing held), `deposit_exceeds_held`, `deposit_amount_differs` (the whole deposit or nothing), `deposit_already_released` (ended another way).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /room-charge/connection:
    get:
      tags: [Accounting]
      summary: Which PMS, and whether this server can reach it (V71)
      description: >-
        Room charge is switched off until a hotel system is proven end to end on its own test system (T-37.8): `offered` is false
        for every system and `notOfferedBecause` says so in words to read. Nothing already charged is hidden by it: the worklist,
        reports and refunds of a posted charge keep working.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Not connected is a first-class answer, not an error.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RoomChargeConnection" }
    post:
      tags: [Accounting]
      summary: "Connect, pause, or set the property reference (MANAGE_INTEGRATIONS: the owner or an admin)"
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RoomChargeConnectionRequest" }
      responses:
        "200":
          description: Saved. Credentials are never accepted here — they are environment-only.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RoomChargeConnection" }
        "403":
          description: '`permission_required`: MANAGE_INTEGRATIONS, which a manager does not hold (T-1.27 review).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`room_charge_not_offered`: no hotel system has been proven to work with Ruva yet, so none can be connected (T-37.8). `NONE` still saves, so a venue may disconnect one.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /room-charge/availability:
    get:
      tags: [Accounting]
      summary: May the till offer the tender at all?
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Deliberately not manager-gated — a cashier's till asks this.
          content:
            application/json:
              schema:
                type: object
                properties:
                  connected: { type: boolean, description: "True only for a connected, credentialed hotel system that has been proven (T-37.8); false for every venue until one is." }
                  overrideAllowed: { type: boolean }
                  notOfferedBecause: { type: string, nullable: true, description: "Why room charge is switched off, in words to read; absent while it is offered." }
  /room-charge/lookup:
    post:
      tags: [Accounting]
      summary: Confirm room and guest before charging
      description: >-
        An empty room is refused and cannot be overridden — charging room 302 because somebody
        said "302" is how a hotel loses money. An unreachable PMS is refused unless the property
        has opted into unverified charges. While no hotel system is proven (T-37.8) the answer is
        `available: false` with the reason, and the hotel is not asked.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [room]
              properties: { room: { type: string } }
      responses:
        "200":
          description: The guest to read back, or a refusal with its reason.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RoomChargeLookup" }
  /room-charge/charge:
    post:
      tags: [Accounting]
      summary: Post a sale to the folio
      description: >-
        Switched off until a hotel system is proven (T-37.8): a new charge is answered `REFUSED` with the reason, nothing is
        claimed and the hotel is not asked; a charge already on record under the sale answers as it stands, from the row. A
        checkout carrying a `ROOM_CHARGE` leg for a sale the folio does not hold is 409 `room_charge_not_offered`.
        The posting row is claimed in Ruva BEFORE the request leaves, unique on
        (tenant, transaction) — so a double-press, two tills or a manual re-send collapse onto one
        folio line. The key is derived, never generated, so a retry re-sends the identical
        document. An Unknown outcome stays claimed and is retried by the sweep; a 4xx is terminal.
        The transactionId must be the sale's own id (the server's order id, or the id the till minted for a
        walk-in sale and records the sale under): it IS the charge, so a made-up value shared by several
        sales, such as the retired literal "WALK_IN", is answered REFUSED with a sentence and nothing is
        claimed; an id that is not a UUID (a QR order's phone-minted id) is a sale's only when the business
        holds that order. A retry of a claimed id to another room or with another amount is REFUSED, worded
        by what the folio holds and naming the room it is on, never answered as the first's POSTED. A FAILED
        claim (nothing on the folio) is charged afresh under a new key; a PENDING one asked again is sent once
        more under its own key once no send can still be in flight (30 s after the last). The key sent to the
        hotel is a SHA-256 of (tenant, transaction) shaped as a UUID.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RoomChargeRequest" }
      responses:
        "200":
          description: Outcome, including alreadyPosted for a repeat.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RoomChargePosting" }
  /room-charge/reverse:
    post:
      tags: [Accounting]
      summary: Reverse a posting (REFUND, held to the second factor)
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [transactionId]
              properties: { transactionId: { type: string } }
      responses:
        "200":
          description: The reversed posting.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RoomChargePosting" }
  /api/v1/room-charge/release:
    post:
      tags: [Accounting]
      summary: Release a room charge the hotel never answered (REFUND, held to the second factor)
      description: >-
        A charge sent without an answer may be on the guest's folio and is never sent again (Opera keeps every line it is
        sent). Reception checks the folio for its reference; a manager then releases it: RELEASED, never sent again, and
        checkout stops refusing other tenders for its bill. Idempotent. 409 `room_charge_on_folio` for a confirmed charge
        (refund it instead), `room_charge_not_sent` for one the hotel rejected, 404 `room_charge_not_found`.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [transactionId]
              properties: { transactionId: { type: string } }
      responses:
        "200":
          description: The released charge (status RELEASED, mayHaveLanded true, idempotencyKey the folio reference).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RoomChargePosting" }
        "403":
          description: '`manager_required`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`room_charge_on_folio`, `room_charge_not_sent` or `room_charge_changed`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /room-charge/postings:
    get:
      tags: [Accounting]
      summary: Per-sale outcome — reception's worklist (REFUND, held to the second factor)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: status, in: query, required: false, schema: { type: string, enum: [PENDING, POSTED, FAILED, RELEASED] } }
        - { name: limit, in: query, required: false, schema: { type: integer, default: 100, minimum: 1, maximum: 500 } }
      responses:
        "200":
          description: Newest first.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/RoomChargePosting" }
  /feeds/{tenantId}/{storeId}/products.xml:
    get:
      tags: [Shipping]
      summary: Product feed for Google Merchant / Meta Commerce (public, token-gated)
      description: >-
        RSS 2.0 with the `g:` namespace. The token is derived by HMAC from the ids in the path and
        checked in constant time BEFORE any database query, so an unauthenticated caller cannot
        make this endpoint do work. A missing, wrong or other-tenant token is 404 rather than 403 —
        a public URL should not confirm that something exists. Cached for 15 minutes and served
        with an ETag, so a daily crawl usually costs a 304. Never contains cost prices, supplier
        names or stock quantities.
      parameters:
        - { name: tenantId, in: path, required: true, schema: { type: string } }
        - { name: storeId, in: path, required: true, schema: { type: string } }
        - { name: t, in: query, required: true, description: The feed token from /api/v1/feeds/stores., schema: { type: string } }
        - { name: If-None-Match, in: header, required: false, schema: { type: string } }
      responses:
        "200":
          description: The feed.
          content:
            application/xml:
              schema: { type: string }
        "304":
          description: Unchanged since the ETag the caller presented.
        "404":
          description: '`feed_not_found` — unknown store, or a token that does not match.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /feeds/stores:
    get:
      tags: [Shipping]
      summary: "Connected stores and their feed URLs (MANAGE_INTEGRATIONS: the owner or an admin)"
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: One row per connected storefront, each with a ready-to-paste URL.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/ProductFeedStore" }
        "403":
          description: '`permission_required`: MANAGE_INTEGRATIONS, which a manager does not hold (T-1.27 review).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /shipping/methods:
    get:
      tags: [Shipping]
      summary: The delivery price list
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: includeInactive, in: query, required: false, schema: { type: boolean, default: false } }
      responses:
        "200":
          description: Each method with its bands.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/ShippingMethod" }
    post:
      tags: [Shipping]
      summary: Create or replace a delivery option (Manager-gated)
      description: >-
        Replaces the method AND all of its bands. A price list is edited as one table, so a
        merge would leave a removed row still pricing parcels.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ShippingMethodRequest" }
      responses:
        "200":
          description: Saved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdResponse" }
        "400":
          description: '`name_required`, `unknown_kind`, `negative_price`, `bands_required`, `invalid_band`, `duplicate_band`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: '`manager_required`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /shipping/methods/{id}:
    delete:
      tags: [Shipping]
      summary: Retire a delivery option (Manager-gated)
      description: Soft — parcels already raised keep the service name they were sent with.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Retired.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdResponse" }
        "404":
          description: '`not_found`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /shipping/zones:
    get:
      tags: [Shipping]
      summary: Postcode prefix to zone
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: The zone table.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/ShippingZone" }
    post:
      tags: [Shipping]
      summary: Replace the zone table (Manager-gated)
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [zones]
              properties:
                zones:
                  type: array
                  items: { $ref: "#/components/schemas/ShippingZone" }
      responses:
        "200":
          description: How many rules were stored.
          content:
            application/json:
              schema:
                type: object
                properties: { saved: { type: integer } }
        "400":
          description: '`blank_zone`, `duplicate_prefix` (one prefix cannot map to two zones).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /shipping/quote:
    post:
      tags: [Shipping]
      summary: What would delivery cost?
      description: >-
        Send `weightG` for a parcel somebody has weighed, or `lines` to have the server weigh the
        basket from the catalogue. An option with `available: false` carries a `reason`:
        `needs_weight` (something in the basket is unweighed), `no_band` (heavier than every band),
        or `zone_not_served`.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ShippingQuoteRequest" }
      responses:
        "200":
          description: One option per method, deliverable ones cheapest first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ShippingQuoteResponse" }
  /shipping/shipments:
    get:
      tags: [Shipping]
      summary: Parcels, newest first
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: status, in: query, required: false, schema: { type: string, enum: [PENDING, PACKED, SHIPPED, DELIVERED, CANCELLED] } }
        - { name: limit, in: query, required: false, schema: { type: integer, default: 100, minimum: 1, maximum: 500 } }
      responses:
        "200":
          description: Parcels.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Shipment" }
    post:
      tags: [Shipping]
      summary: Raise a parcel
      description: >-
        Allocates a waybill number, unique for the life of the account. The address, weight and
        price are copied onto the parcel: a customer moving house must not rewrite where last
        month's parcel went, and a later rate rise must not rewrite what this one cost.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ShipmentRequest" }
      responses:
        "201":
          description: Raised, status PENDING.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Shipment" }
        "400":
          description: '`recipient_required`, `address_required`, `city_required`, `postcode_required`, `negative_price`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /shipping/shipments/{id}/status:
    post:
      tags: [Shipping]
      summary: Move a parcel along
      description: >-
        `PENDING -> PACKED -> SHIPPED -> DELIVERED`, with `CANCELLED` available from the first
        three. A delivered parcel cannot be un-packed. `CANCELLED` is manager-only, because a
        parcel already on a van means a refund or a recall.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [status]
              properties:
                status: { type: string, enum: [PENDING, PACKED, SHIPPED, DELIVERED, CANCELLED] }
                trackingRef: { type: string, nullable: true, description: From the courier's slip, or a carrier integration later. }
      responses:
        "200":
          description: The parcel.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Shipment" }
        "403":
          description: '`manager_required` (cancelling only).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`illegal_transition` — the message names the move that was refused.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /shipping/shipments/{id}/waybill:
    get:
      tags: [Shipping]
      summary: The A4 sheet for the parcel
      description: >-
        Address at the largest size the page allows, sender block, the waybill number as a Code 128
        barcode and as readable digits, service, weight, notes and a signature block. Generated from
        the parcel, so it can be reprinted at any time.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: PDF.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        "404":
          description: '`not_found`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /accounting/postings:
    get:
      tags: [Accounting]
      summary: "Per-entry posting outcomes (MANAGE_INTEGRATIONS: the owner or an admin)"
      parameters:
        - { name: status, in: query, required: false, schema: { type: string, enum: [PENDING, POSTED, FAILED, SKIPPED] } }
        - { name: limit, in: query, required: false, schema: { type: integer, default: 100, minimum: 1, maximum: 500 } }
      responses:
        "200":
          description: Newest first.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/AccountingPosting" }
        "400":
          description: '`unknown_status`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/payouts:
    get:
      tags: [Accounting]
      summary: Imported settlement reports, newest first (MANAGE_INTEGRATIONS, T-10.5)
      description: |
        Each acquirer report imported, with its totals over the **matched** rows only — what the payout journal posted
        (Dr 1050 bank net, Dr 6000/6010 fees VAT-inclusive, Cr 1010/1020 clearing gross). `feeVatCents` is the VAT inside
        those fees at each row's own date.
      parameters:
        - { name: limit, in: query, required: false, schema: { type: integer, default: 50, minimum: 1, maximum: 200 } }
      responses:
        "200":
          description: Newest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PayoutImportSummary" } }
        "400":
          description: '`bad_limit`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/payouts/{id}:
    get:
      tags: [Accounting]
      summary: One imported report — every row, what it matched, and payments still unsettled (MANAGE_INTEGRATIONS)
      description: |
        `notSettled` is derived when read: the provider's captured payments inside the report's days that no imported
        row has settled, so a payment a later report pays out drops off it.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The import.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PayoutImportDetail" }
        "404":
          description: '`payout_import_not_found`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/payouts/import:
    post:
      tags: [Accounting]
      summary: Import a settlement report as a file (MANAGE_INTEGRATIONS)
      description: |
        `PAYFAST` reads PayFast's transaction history as its API answers it (`Date,Type,Sign,…,Gross,Fee,Net,…,"M Payment ID",
        "PF Payment ID",…`). Every provider also takes Ruva's settlement template: `date,reference,type,gross,fee,net`, one
        row per payment, `type` PAYMENT for a payment. Each payment is matched once, ever; the same file twice changes
        nothing (`alreadyImported`), and a row an earlier overlapping report brought is skipped. The matched rows are posted
        as one journal in the same transaction.
      parameters:
        - { name: provider, in: query, required: true, schema: { type: string, enum: [PAYFAST, YOCO, SNAPSCAN, ZAPPER] } }
      requestBody:
        required: true
        content:
          text/csv:
            schema: { type: string }
      responses:
        "200":
          description: The import as stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PayoutImportDetail" }
        "400":
          description: '`missing_provider`, `unknown_provider`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "413":
          description: '`report_too_large` (5 MB).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "422":
          description: '`report_refused` — not a report this reads, or a row whose figures do not add up; the message names the row.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/payouts/payfast:
    post:
      tags: [Accounting]
      summary: Fetch PayFast's transaction history for a period and import it (MANAGE_INTEGRATIONS)
      description: Uses the PayFast account this server is configured for, against its sandbox unless configured live.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PayFastPayoutFetch" }
      responses:
        "200":
          description: The import as stored.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PayoutImportDetail" }
        "400":
          description: '`bad_from`, `bad_to`, `bad_period`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: '`payfast_not_configured`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "422":
          description: '`report_refused`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "502":
          description: '`payfast_refused` — PayFast answered with an error; its words are in the message.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/status:
    get:
      tags: [Accounting]
      summary: Whether the accounting package is connected and what waits to post (MANAGE_INTEGRATIONS or VIEW_FINANCIALS, T-21.12)
      description: |
        The connection reduced to a state and three counts, for the books' reader: an accountant, a manager (both hold
        VIEW_FINANCIALS) and the owner or an admin (MANAGE_INTEGRATIONS). It carries no organisation, key hint, error text or
        date range; the connection itself, with those, is `GET /api/v1/accounting/connection` (MANAGE_INTEGRATIONS).
      responses:
        "200":
          description: The connection's state and counts.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AccountingStatus" }
        "403": { description: The caller holds neither MANAGE_INTEGRATIONS nor VIEW_FINANCIALS. }
  /api/v1/accounting/health:
    get:
      tags: [Accounting]
      summary: The accounting connection checked live (MANAGE_INTEGRATIONS, T-11.1)
      description: |
        One identity call to the package — Xero `GET /Organisation`, QuickBooks `GET /companyinfo/{realm}`, Sage
        `GET Company/Current` — answering whether the credentials reach the company they name. `REAUTHORISE` means the
        package refused the credentials; `NOT_CONNECTED` names what is missing.
      responses:
        "200":
          description: The connection's state, in a manager's words.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AccountingHealth" }
  /api/v1/accounting/items/sync:
    post:
      tags: [Accounting]
      summary: Push products as the package's items (MANAGE_INTEGRATIONS, T-11.1)
      description: |
        Each active product as an item: its SKU (else barcode, else id) as the code, its name, its VAT-inclusive price,
        its category's revenue account (else the sales account) and its VAT type's tax code. Claimed before the call and
        sent again only when one of those changes, so an unchanged menu costs no calls. Refused, with `blocked` saying
        why, while the sales account or a VAT type in use is unmapped.
      parameters:
        - { name: limit, in: query, required: false, schema: { type: integer, default: 100, minimum: 1, maximum: 500 } }
        - { name: retryFailed, in: query, required: false, schema: { type: boolean, default: false }, description: "A person's Retry: items the package refused are sent again." }
      responses:
        "200":
          description: What was sent.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ItemSyncResult" }
        "400":
          description: '`invalid_limit`, `invalid_retry_failed`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/location-map:
    get:
      tags: [Accounting]
      summary: Each location and where its documents land in the package (MANAGE_INTEGRATIONS, T-11.1)
      description: A Xero tracking category and option, a QuickBooks location (department) id, or a Sage analysis category id.
      responses:
        "200":
          description: Every location, mapped or not.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LocationTrackingMap" }
        "400":
          description: '`not_connected`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/location-map/{locationId}:
    put:
      tags: [Accounting]
      summary: Map a location, or remove its mapping with a null option (MANAGE_INTEGRATIONS, T-11.1)
      parameters:
        - { name: locationId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LocationTrackingRequest" }
      responses:
        "200":
          description: The map as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LocationTrackingMap" }
        "400":
          description: '`not_connected`; `invalid_tracking` — Xero needs the category name too, a Sage analysis category is a number.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: '`location_not_found`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/category-map:
    get:
      tags: [Accounting]
      summary: Each product category and the revenue account its sales go to (MANAGE_INTEGRATIONS, T-11.1)
      description: |
        A sale's revenue line is split across its categories' accounts when it is pushed, in proportion to each category's
        net, summing to the line to the cent. Ruva's own ledger keeps one revenue line; an unmapped category stays on the
        sales account.
      responses:
        "200":
          description: Every category, mapped or not.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CategoryAccountRow" } }
        "400":
          description: '`not_connected`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/category-map/{categoryId}:
    put:
      tags: [Accounting]
      summary: Send a category's sales to an account, or back to the sales account with a null code (MANAGE_INTEGRATIONS, T-11.1)
      parameters:
        - { name: categoryId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CategoryAccountRequest" }
      responses:
        "200":
          description: The map as it now stands.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CategoryAccountRow" } }
        "400":
          description: '`not_connected`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: '`category_not_found`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/reconcile/days:
    get:
      tags: [Accounting]
      summary: Day by day — what Ruva raised, what is in the package and under which reference (MANAGE_INTEGRATIONS, T-11.5)
      description: |
        Each trading day of the range that had anything: its journals, how many are in the package (posted on their own,
        or inside a daily summary that posted), waiting, failed or never sent, the package's references, and the
        difference. A day before the push-from date is marked and never counted as missing. `lockedThrough` is the
        package's lock date read live (Xero's period and year-end lock, QuickBooks' closing date); Sage does not report
        one (`lockUnknown`).
      parameters:
        - { name: from, in: query, required: true, schema: { type: string, format: date } }
        - { name: to, in: query, required: true, schema: { type: string, format: date } }
      responses:
        "200":
          description: The days, oldest first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReconcileDaysView" }
        "400":
          description: '`invalid_date`, `invalid_range`, `range_too_long` (at most 92 days), `not_connected`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/reconcile/days/{day}/repost:
    post:
      tags: [Accounting]
      summary: Re-post a day's failures under their first references (MANAGE_INTEGRATIONS, T-11.5)
      description: |
        The day's failed journals and documents, including a failed daily summary, go back in the queue with their
        unanswered-send count afresh and are sent now. The lock date is read live, so a period locked a minute ago counts.
      parameters:
        - { name: day, in: path, required: true, schema: { type: string, format: date } }
      responses:
        "200":
          description: What went back and what landed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RepostResult" }
        "400":
          description: '`invalid_date`, `not_connected`.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: |
            `period_locked` — inside the package's locked period; `before_sync_from`; `not_connected` — the connection is off;
            `closed_period` — the day's only failures are inventory journals dated more than 35 days back, which no door puts
            back in the queue (a period the books may have closed): the message names each held journal's narration and
            amount and what the reconciliation's late movements count to post by hand for each class (cost of sales,
            write-offs, adjustments) with its direction and the narration to post it under, if the journal is found and if
            not, or that a class now nets to nothing. Every part to post by hand is first to be looked for under the same
            amount and narration, and posted only if it is not there, so following the message again posts nothing twice;
            while a send for the day is still waiting for its answer, the message says to read it again in a few minutes.
            A day that also re-posted something answers 200 with `heldClosedPeriod`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/late/{day}/{class}/posted-by-hand:
    post:
      tags: [Accounting]
      summary: Say a late-list day and class was posted into the accounting system by hand (MANAGE_INTEGRATIONS, T-43.5)
      description: |
        Only a day more than 35 days back (`closed_period`, `closed_period_sent`) closes: Ruva posts the others itself. The row
        leaves the reconciliation's late list and is recorded with who closed it, when, the list's figure and the part the person
        says they posted; one `ACCOUNTING_POSTED_BY_HAND` audit row names the person, the day, the class and the figures. The
        closing covers exactly what the list showed: a movement written to the day later is listed again, to be closed as the
        day's next revision. A journal Ruva sent for the day that never confirmed is the person's from then: never sent again.
        An empty body is `{"part": "ALL"}` at the list's figure now.
      parameters:
        - { name: day, in: path, required: true, schema: { type: string, format: date } }
        - { name: class, in: path, required: true, schema: { type: string, enum: [COGS, WRITE_OFF, ADJUSTMENT] } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PostedByHandRequest" }
      responses:
        "200":
          description: The closed row, with who closed it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HandPostedDay" }
        "400":
          description: '`invalid_date`, `invalid_class`, `invalid_body`, `invalid_part` (BEYOND_HELD of a row with no held journal).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: '`not_late` — that day and class is on no late list.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: |
            `already_posted_by_hand` (nothing listed since); `not_closable` — Ruva posts it itself, or its journals cannot be read
            from Ruva (`older_revision`, `xids_went_backwards`); `not_yet` — its send is waiting for an answer, or a movement on it
            is still being written; `changed_meanwhile` — the figure or its journals moved since it was read (`expectedCents`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/accounting/queue/retry:
    post:
      tags: [Accounting]
      summary: Put a failed item back in the queue under its first reference (MANAGE_INTEGRATIONS)
      description: |
        A retry re-sends the same document with the same idempotency key, never a new one: the original may have landed
        despite its error. Only a FAILED item can be retried; a PENDING one is already re-sent by the next run. `all` puts
        back everything failed at once (after a mapping is fixed or a token renewed) and answers how many went back. An
        inventory journal dated more than 35 days back is never put back (a period the books may have closed): `all`
        leaves it failed and counts it in `heldClosedPeriod`; a retry of that one answers 409.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                kind: { type: string, enum: [JOURNAL, DOCUMENT, CONTACT], description: "Ignored when `all` is set." }
                entryId: { type: string, nullable: true, description: "JOURNAL: the journal entry's id." }
                docType: { type: string, nullable: true, description: "DOCUMENT: BILL, INVOICE, INVOICE_PAYMENT, SETTLEMENT, INVENTORY or SALES." }
                sourceId: { type: string, nullable: true, description: "DOCUMENT: Ruva's id of it; an inventory journal's is `<day>:<class>[:r<n>]`." }
                entityType: { type: string, nullable: true, description: "CONTACT: the entity whose contact link is retried." }
                entityId: { type: string, nullable: true }
                all: { type: boolean, default: false, description: "Everything currently FAILED." }
      responses:
        "200":
          description: How many went back; with `all`, also how many closed-period inventory journals were left failed.
          content:
            application/json:
              schema:
                type: object
                required: [retrying]
                properties:
                  retrying: { type: integer }
                  heldClosedPeriod: { type: integer, description: "`all` only: inventory journals more than 35 days back, left failed for a person to post by hand." }
        "400":
          description: '`unknown_kind`; `not_connected` (with `all`).'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: |
            `nothing_to_retry` — it is no longer FAILED (retried by someone else, or posted); `closed_period` — an inventory
            journal dated more than 35 days back, never sent again: the message names its narration and amount and what the
            reconciliation's late movements count to post by hand, or that its day now nets to nothing; `before_sync_from` —
            the journal's day is before the connection's push-from date, so Ruva sends and counts nothing there.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/quotes/convertible:
    get:
      tags: ["Quotes & Special Orders"]
      summary: Quotes the till can ring up (T-4.6)
      description: |
        Every quote `QuoteMath.canConvert` allows — SENT or ACCEPTED, its price still holding (its date, and never past
        30 SA days from when it was written, T-2.56) — and not yet converted, at
        `locationId` when given, soonest to expire first. Not `/quotes/open`, the back office's chase list, which leaves
        accepted quotes out on purpose.
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string } }
      responses:
        "200":
          description: Convertible quotes.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Quote" } }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /inventory/counts:
    get:
      tags: [Inventory]
      summary: Stocktake history
      description: Newest first, capped at 100. Progress and variance totals per session.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: locationId, schema: { type: string }, description: "Omit for every location." }
        - { in: query, name: status, schema: { type: string, enum: [DRAFT, COUNTING, REVIEW, APPROVED, CANCELLED] } }
      responses:
        "200":
          description: Sessions.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/StockCountSummary" } }
    post:
      tags: [Inventory]
      summary: Open a stocktake session (Manager)
      description: |
        Snapshots every in-scope SKU with what the books say now — that snapshot is
        the variance baseline. One open session per location at a time.

        Only `track_stock` products are included, and a product with variants
        contributes one line per variant (never a parent roll-up), matching
        `GET /inventory/stock`.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OpenCountRequest" }
      responses:
        "201":
          description: Session opened.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OpenCountResponse" }
        "400":
          description: "`invalid_scope_type`, `scope_ids_required`, `empty_scope` or `unknown_location`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`count_already_open` — another session at this location is still open."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/counts/{id}:
    get:
      tags: [Inventory]
      summary: One stocktake with its lines
      description: |
        On a **blind** session that is still `COUNTING`, `expectedUnits` and
        `varianceUnits` are omitted from every line. This is enforced server-side,
        not in the UI. They appear once the session reaches `REVIEW`.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: Session with lines.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StockCountSession" }
        "404":
          description: "`count_not_found` — including another tenant's session."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/counts/{id}/lines:
    post:
      tags: [Inventory]
      summary: Submit counted quantities
      description: |
        Needs the "Run stocktakes" permission — counting is floor work. Partial submissions are
        expected and re-submitting a line overwrites it, so a mis-keyed figure is
        corrected by sending it again. "Later" is by when the line was counted
        (`countedAt`), not when it arrived: a count queued offline that syncs after
        a recount leaves the recount standing.

        A counted `0` is a real count and posts a variance; a line never submitted
        stays uncounted and posts nothing.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SubmitCountRequest" }
      responses:
        "200":
          description: The updated session.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StockCountSession" }
        "400":
          description: "`empty_counts`, `invalid_counted_qty`, `line_not_in_session` or `invalid_occurred_at`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`count_not_counting` — the session has moved on."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/counts/{id}/review:
    post:
      tags: [Inventory]
      summary: Send a stocktake for review
      description: "COUNTING → REVIEW. Expected quantities become visible even on a blind count."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: The session, now in REVIEW.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StockCountSession" }
        "400":
          description: "`nothing_counted`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`count_not_counting`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/counts/{id}/approve:
    post:
      tags: [Inventory]
      summary: Approve and post the variance (STOCKTAKE)
      description: |
        Posts each counted line's variance as a stock **movement**, not as an absolute
        on-hand: `counted - expected - traded`, where *traded* is what moved between the
        snapshot and the count. This matters: stock that sold between counting and approval is
        preserved rather than silently re-created. Count 10 against a book figure
        of 12, sell 2 while it sits in review, and on-hand lands on 8.

        Uncounted lines post nothing. Approval is terminal and posts **one adjustment per
        item, once**: a second call, a retry, or two taps racing each other get a 409
        (`count_not_approvable`) and post nothing more. Runs the auto-86 sweep afterwards.

        This is the same approval as `POST /counting/sessions/{id}/approve` and holds the same
        discipline, with the session in COUNTING or REVIEW: a flagged line needs a second
        counter first, and a write-off at or over the approval figure needs the body's
        `confirmWriteOffValueCents` to name it, to the cent, from somebody who did not count or
        recount it. The body is optional, and may be left out where nothing is flagged.
        `varianceValueCents` is a cost figure: absent for a role without `VIEW_COST`.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ApproveVarianceRequest" }
      responses:
        "200":
          description: What was posted.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApproveCountResponse" }
        "403":
          description: "The caller does not hold the stocktake permission."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: >
            `count_not_approvable` — already approved or cancelled (also the answer to a second
            approval of the same count) · `recount_required` — a flagged line still needs a second
            counter · `second_approver_required` — the write-off is at or over the approval figure
            and the approver counted or recounted a line of it · `write_off_confirmation_required` —
            the figure was not named · `write_off_value_changed` — it was named and is no longer
            that figure.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/counts/{id}/cancel:
    post:
      tags: [Inventory]
      summary: Abandon a stocktake (Manager)
      description: "Refused once APPROVED — those movements cannot be taken back."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: Cancelled.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  status: { type: string }
        "409":
          description: "`count_terminal`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ── Counting discipline & bin locations (V52) ──
  #
  # The V20 session endpoints above are untouched and still the way a count is opened, counted and
  # reviewed. These extend them: ABC classification, a cycle schedule, walk order, a second
  # counter's recount, and an approval that reconciles trading out of the variance. The two
  # approvals are mutually exclusive per session — whichever runs first leaves it APPROVED.
  /api/v1/counting/policy:
    get:
      tags: [Inventory]
      summary: The counting thresholds in force, and where they came from
      description: >
        Resolution is the location's own row, else the tenant default, else the built-in defaults —
        **one row or the other, never a merge**, because a partially inherited policy cannot be read
        off a screen and a manager who cannot see the thresholds will not trust the variance they
        produced. `source` says which of the three answered: `DEFAULT` until a tenant saves anything
        of its own. Every `*ShareBp` field is **basis points**, so 8000 means 80% — kept as integers
        so a threshold can never drift by a rounding error between the screen and the gate.
        Needs VIEW_STOCK, which every counter holds: a policy is the rules of the game, and telling a
        counter "a variance over ten units gets recounted" is the point of having one.
      parameters:
        - name: locationId
          in: query
          required: false
          description: Omit to read the tenant default directly.
          schema: { type: string }
      responses:
        "200":
          description: The effective policy.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CountingPolicy" }
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Inventory]
      summary: Set the thresholds, per location or as the tenant default (EDIT_SETTINGS)
      description: >
        Omitting `locationId` upserts the tenant default; naming one upserts that location's
        override. Absent fields are kept rather than cleared, so editing a recount threshold does
        not silently reset the cycle intervals the form did not resend — and the *merged* result is
        validated, not the request, or a class B share below an unchanged class A share would slip
        past and V52's CHECK would reject it at the worst moment. Zero is legal in all three recount
        thresholds and means "recount every variance", which is a reasonable policy for a shop that
        has just found a problem; negative is not.
        400 codes are `invalid_basis`, `invalid_window_days`, `invalid_class_a_share`,
        `invalid_class_b_share`, `class_b_share_below_class_a`, `invalid_interval_days`,
        `invalid_recount_units`, `invalid_recount_value`, `invalid_recount_share`,
        `invalid_approval_value`, `freeze_mode_unsupported` and `unknown_location`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CountingPolicyUpsert" }
      responses:
        "200":
          description: The policy as it now resolves for the location (or the tenant) that was written.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CountingPolicy" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/counting/abc:
    get:
      tags: [Inventory]
      summary: ABC classification by value (VIEW_COST)
      description: >
        A line's class is decided by the value ranked **above** it, not including its own, so class
        A is never empty — classing on the cumulative share including the line would put a
        single-SKU shop's only line in C and count the whole business once a year. Two SKUs of
        identical value always take the same class, and a tie takes the higher one, which is the
        direction that counts more often. A window in which nothing moved classifies everything as
        C: not A, because there is no evidence anything is valuable, and not "unclassified",
        because a SKU with no class never appears on a schedule and therefore never gets counted.

        Manager-gated because every row carries a value per SKU, which on the `STOCK_VALUE` basis
        is on-hand times cost — hand that to a counter mid-blind-count and V20's blind mechanism is
        one division away from defeated.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: basis
          in: query
          required: false
          description: >
            Overrides the policy for this call. `MOVEMENT` is consumption value over the window —
            the textbook basis. `STOCK_VALUE` is what is sitting there now, the honest basis for a
            shop three weeks old, and for the expensive machine in the stockroom that has never
            moved and would classify as C on movement alone.
          schema: { type: string, enum: [MOVEMENT, STOCK_VALUE] }
        - name: windowDays
          in: query
          required: false
          description: Overrides `abcWindowDays` from the policy (90 by default). Must be at least 1.
          schema: { type: integer, minimum: 1 }
        - name: abcClass
          in: query
          required: false
          description: Narrow to one class. `totalSkus` then counts the narrowed set; `classSummary` and `totalValueCents` always cover the whole range.
          schema: { type: string, enum: [A, B, C] }
        - name: limit
          in: query
          required: false
          description: Clamped, not rejected.
          schema: { type: integer, default: 200, minimum: 1, maximum: 5000 }
        # Wastage counts as consumption alongside sales: a line losing a case a month to breakage
        # is exactly a line worth counting often.
      responses:
        "200":
          description: Classified SKUs, most valuable first, with a per-class summary.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AbcResponse" }
        "400":
          description: "`locationId_required`, `invalid_basis`, `invalid_window_days` or `unknown_location`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/counting/cycle-due:
    get:
      tags: [Inventory]
      summary: What to count today, most neglected first (VIEW_COST)
      description: >
        A never-counted SKU is due immediately and sorts ahead of everything else. It is the only
        line about which the books hold no evidence at all, and giving it a fabricated
        last-counted date would either bury it or make it look a thousand years overdue — one
        hides it, the other makes the column meaningless. `lastCountedAtMs` is drawn from two
        sources, because there are two ways to count in Ruva and using one would make the other
        look like neglect: approved V20 sessions, and one-shot `STOCK_COUNT` movements from
        `/inventory/stock-count`. Manager-gated for the same disclosure reason as `/counting/abc`.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: abcClass
          in: query
          required: false
          schema: { type: string, enum: [A, B, C] }
        - name: dueOnly
          in: query
          required: false
          description: >
            Defaults to true, because the question this answers is "what do we count today". Pass
            `false` to see the whole range with its next due date, which is how a manager checks
            the intervals are survivable before committing to them.
          schema: { type: boolean, default: true }
        - name: limit
          in: query
          required: false
          description: Clamped, not rejected.
          schema: { type: integer, default: 200, minimum: 1, maximum: 5000 }
      responses:
        "200":
          description: The queue. `dueCount` and `neverCountedCount` always cover the whole schedule, not the filtered page.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CycleDueResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/counting/scope:
    get:
      tags: [Inventory]
      summary: The SKUs to open a count over, in walk order (STOCKTAKE)
      description: >
        Resolves a zone, an aisle, one bin, one ABC class, or what is due, into `scopeIds` to hand
        straight to `POST /inventory/counts` with `scopeType = "PRODUCTS"`. With no filter at all
        it returns the whole location, which `scopeType = ALL` already does — the reason to route
        a full count through here is the walk order, which ALL does not carry.

        One caveat, stated rather than hidden: V20 scopes by **product**, so a zone holding a
        single variant produces a sheet carrying all of that product's variants. Fixing it means a
        BIN scope type in the V20 route, which this endpoint cannot do on its own.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: zone
          in: query
          required: false
          schema: { type: string }
        - name: aisle
          in: query
          required: false
          schema: { type: string }
        - name: binId
          in: query
          required: false
          schema: { type: string }
        - name: abcClass
          in: query
          required: false
          schema: { type: string, enum: [A, B, C] }
        - name: dueOnly
          in: query
          required: false
          description: Defaults to false here, unlike `/counting/cycle-due` — this endpoint is normally asked "what is in aisle B", not "what is late".
          schema: { type: boolean, default: false }
        - name: limit
          in: query
          required: false
          description: Clamped, not rejected.
          schema: { type: integer, default: 200, minimum: 1, maximum: 5000 }
      responses:
        "200":
          description: Stops in walking order, plus the distinct product ids to open the session with.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CountScopeResponse" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/counting/sessions/{id}/route:
    get:
      tags: [Inventory]
      summary: The walking sheet for a count session
      description: >
        **This response carries no expected, counted or variance figure of any kind**, and that is
        deliberate rather than incidental. It is the one endpoint a counter needs on a phone in a
        storeroom, so it has to be safe to hand over during a blind count — and a sheet that had to
        be filtered by session status would eventually be filtered wrongly. It therefore needs only
        VIEW_STOCK while `/variances` below is manager-only.

        `filter=RECOUNT` narrows to the lines a second person still has to confirm. That discloses
        *that* those lines have a notable variance, which is unavoidable since somebody has to be
        told which shelves to revisit, but never by how much.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
        - name: mode
          in: query
          required: false
          description: >
            `COUNT` visits every bin holding each SKU — a count that only saw the pick face would
            ignore the overflow pallet and write off what is on it. `PICK` visits the face only.
          schema: { type: string, enum: [COUNT, PICK], default: COUNT }
        - name: filter
          in: query
          required: false
          schema: { type: string, enum: [ALL, UNCOUNTED, RECOUNT], default: ALL }
      responses:
        "200":
          description: Stops in walking order. SKUs no bin records are returned anyway, flagged `unassigned` and sorted last.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CountRouteResponse" }
        "400":
          description: "`invalid_mode` or `invalid_filter`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: "`count_not_found` — including another tenant's session."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/counting/sessions/{id}/variances:
    get:
      tags: [Inventory]
      summary: Reconciled variance and what the policy still demands (VIEW_COST)
      description: >
        What the shelf disagreed with the books by, how much of that was simply trade since the
        snapshot, and what the policy still requires before the count may post. Each line carries
        both figures: `rawVarianceUnits` is `counted − expected`, which is what
        `POST /inventory/counts/{id}/approve` would post, and `varianceUnits` is
        `counted − expected − traded`, which is what this family's approval posts instead. Stock
        sold between the snapshot and the count is not shrinkage, and posting it as such writes off
        goods the shop was paid for.

        **Refused outright while a blind session is still COUNTING.** V20 withholds the baseline
        from the session JSON for exactly that window, and an endpoint here that answered anyway
        would be the leak its comment warns about. `POST /inventory/counts/{id}/review` is how a
        count leaves that window.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
        - name: confirmWriteOffValueCents
          in: query
          required: false
          description: >
            Dry-runs the approval gate with this figure, so a screen can show whether the confirmation
            it is about to send would be accepted. Omitted, `blockedReason` reports
            `write_off_confirmation_required` whenever the write-off is at or over the threshold.
          schema: { type: integer, format: int64 }
      responses:
        "200":
          description: Lines needing a recount first, then largest variance value, then product id.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CountVarianceResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`count_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`blind_count_open` — a blind count's variance is not visible until it is in REVIEW."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/counting/sessions/{id}/recount:
    post:
      tags: [Inventory]
      summary: A second person's count of a flagged line
      description: >
        **Refused when it is the same person who counted first** — that is the entire control, and
        a recount by the original counter is a rubber stamp with extra steps. Needs the "Run
        stocktakes" permission, not a manager's login: recounting is floor work, and a control that needs a manager to walk
        to a shelf is a control that never happens.

        The recount **overwrites** the line's counted quantity. It is the count now, not an average
        of two guesses and not a second opinion filed alongside the first; the previous figure and
        both names are frozen in `count_recounts`, which is what makes the overwrite safe. Allowed
        in REVIEW as well as COUNTING, unlike `POST /inventory/counts/{id}/lines` which refuses
        REVIEW — and that difference is the point, since a variance is not visible until review, so
        review is when a recount is ordered.

        The response echoes only what the recounter typed. Returning the variance would tell them
        what the books expected, one call after being sent to count a shelf blind.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RecountRequest" }
      responses:
        "201":
          description: Recount recorded and the line's counted quantity replaced.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RecountResponse" }
        "400":
          description: "`invalid_counted_qty`, `productId_required` or `line_not_in_session`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: "`count_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: >
            `count_not_open` — the session is neither COUNTING nor REVIEW · `same_counter` — a
            recount has to be somebody other than whoever counted first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/counting/sessions/{id}/approve:
    post:
      tags: [Inventory]
      summary: Post the reconciled variance and close the session (STOCKTAKE)
      description: >
        Three things separate this from `POST /inventory/counts/{id}/approve`, which is left
        exactly as it is because it is live and breaking a working screen costs a shop something
        today:

        1. **REVIEW only.** COUNTING means somebody is still on the floor, and a variance computed
        while a count is in progress moves under the manager's feet between reading the screen and
        pressing the button.

        2. **Trading is reconciled out.** It posts `counted − expected − traded`, so a bottle sold
        at 11am against a 9am snapshot is not written off as shrinkage.

        3. **The discipline is enforced, not advised.** A flagged line with no independent recount
        refuses the whole session, because a partially approved count looks finished while missing
        its most significant lines. A write-off at or over the policy threshold requires
        `confirmWriteOffValueCents` to equal the figure on the screen, to the cent, and a
        recomputation that moved it refuses again rather than posting the new number.

        Uncounted lines post nothing, exactly as V20 has it: a line nobody reached is not evidence
        that the shelf is empty. Approval runs the auto-86 sweep afterwards, since a count that
        found less than the books may have emptied an ingredient.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ApproveVarianceRequest" }
      responses:
        "200":
          description: What was posted, with the unreconciled total alongside so the difference the reconciliation made is visible rather than asserted.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApproveVarianceResponse" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`count_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: >
            `count_not_in_review` · `recount_required` — a flagged line still needs a second
            counter · `second_approver_required` — the write-off is at or over the approval
            figure and the approver counted or recounted a line of it ·
            `write_off_confirmation_required` — the figure was not named ·
            `write_off_value_changed` — it was named and is no longer that figure.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/counting/bins:
    get:
      tags: [Inventory]
      summary: Bins in walking order
      description: >
        Ordered by `walkOrder` then code, which is the order a person physically walks the room.
        Needs VIEW_STOCK or FULFIL_ORDERS — a picker needs it. Inactive bins are included by default: a bin
        taken out of service still holds stock that has to be counted, and hiding it by default
        would make that stock disappear from a sheet rather than from a shelf.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: zone
          in: query
          required: false
          description: Case-insensitive exact match on the bin's zone.
          schema: { type: string }
        - name: includeInactive
          in: query
          required: false
          schema: { type: boolean, default: true }
      responses:
        "200":
          description: Bins at the location.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/BinLocation" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Inventory]
      summary: Create or move a bin, keyed on its code (ADJUST_STOCK)
      description: >
        Keyed on (location, code) rather than on an id because that is how a shop edits its layout:
        the label on the shelf is the identity, it exists before the row does, and making the caller
        work out whether to POST or PUT invites the duplicate V52's unique index would then reject.
        Absent fields are kept, so renumbering a walk does not blank out an aisle.
        400 codes are `locationId_required`, `code_required`, `invalid_walk_order` and
        `unknown_location`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BinUpsert" }
      responses:
        "200":
          description: An existing bin was updated.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BinLocation" }
        "201":
          description: A new bin was created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BinLocation" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/counting/bins/{id}:
    delete:
      tags: [Inventory]
      summary: Delete a bin, only while nothing is assigned to it (ADJUST_STOCK)
      description: >
        V52 cascades assignments on delete, which is the right safety net for a genuine cleanup and
        the wrong default for a manager tidying a layout: deleting one bin would silently un-home
        every SKU in it, and the next count sheet would put them all in the unassigned tail with
        nobody knowing why. So this refuses instead. `active = false` is how a bin is taken out of
        service, and it keeps the assignments so the stock still gets counted.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`bin_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`bin_has_assignments` — move them, or set `active = false` instead."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/counting/bin-assignments:
    get:
      tags: [Inventory]
      summary: Which bin a SKU lives in
      description: >
        Sorted by the bin's walk order, so the list reads in the order a person walks. A SKU can
        hold one PICK_FACE and any number of BULK bins at a location. Needs VIEW_STOCK or FULFIL_ORDERS.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: productId
          in: query
          required: false
          schema: { type: string }
        - name: binId
          in: query
          required: false
          schema: { type: string }
      responses:
        "200":
          description: Assignments at the location, in walk order.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/BinAssignment" } }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Inventory]
      summary: Set a SKU's pick face, or add a bulk bin (ADJUST_STOCK)
      description: >
        `PICK_FACE` **moves** rather than duplicates: a SKU that already has a face has its existing
        row pointed at the new bin, because there is exactly one place you pick from and V52's
        partial unique index would refuse a second anyway. `BULK` is added, since overflow is
        genuinely a list. The location comes from the bin; naming one in the body is an optional
        cross-check that must match, since silently preferring the bin's own would let a back office
        think it had assigned a shelf in a different suburb.
        400 codes are `productId_required`, `binId_required`, `invalid_role`, `invalid_capacity`,
        `unknown_bin`, `bin_location_mismatch`, `unknown_product` and `unknown_variant`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BinAssignmentUpsert" }
      responses:
        "200":
          description: An existing assignment was moved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BinAssignment" }
        "201":
          description: A new assignment was created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BinAssignment" }
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/counting/bin-assignments/{id}:
    delete:
      tags: [Inventory]
      summary: Un-home a SKU (ADJUST_STOCK)
      description: >
        The SKU is not removed from anything else — it simply falls into the unassigned tail of
        every route and putaway sheet until it is given a bin again.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: "`bin_assignment_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/counting/pick-path:
    get:
      tags: [Inventory]
      summary: A set of lines in walking order
      description: >
        The endpoint a phone calls to pick an order, so it is open to any staff member. `skus` is
        required and comma-separated — omitting it is `400 skus_required` rather than "everything",
        because a pick path over the whole shop is not a smaller version of the right answer.
        A SKU nothing records the location of is returned anyway, flagged `unassigned` and sorted
        last: dropping it would send a picker away with a short order and no explanation.
      parameters:
        - name: locationId
          in: query
          required: true
          schema: { type: string }
        - name: skus
          in: query
          required: true
          description: >
            Comma-separated, each entry `productId` or `productId:variantId`. Duplicates are
            collapsed. More than 500 is `too_many_skus` — a pick list that long is a data error,
            not an order.
          schema: { type: string }
          example: "p5,p15,p22:var-500ml"
        - name: mode
          in: query
          required: false
          description: Defaults to `PICK` here — the face only — unlike the count route, which defaults to `COUNT`.
          schema: { type: string, enum: [PICK, COUNT], default: PICK }
      responses:
        "200":
          description: Stops in walking order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PickPathResponse" }
        "400":
          description: "`locationId_required`, `skus_required`, `too_many_skus` or `invalid_mode`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
  /api/v1/counting/putaway:
    get:
      tags: [Inventory]
      summary: Where a delivery goes, face first
      description: >
        Takes either a `poId` — the usual case, straight off a receipt, with the location read from
        the PO — or an explicit `locationId` **and** `skus` together. Guessing either would send a
        receiver to the wrong shelf, so neither alone is accepted.

        The response shape differs from `/counting/pick-path` on purpose: a putaway line names one
        `primary` destination to fill first, then `alternates` nearest-first, whereas a pick path is
        a flat list of stops. No capacity arithmetic is attempted — Ruva holds no quantity per bin,
        so nothing here can know the face is already full, and inventing that would be worse than
        saying "face first". `capacityUnits` on a bin is recorded but never used to decide anything.
      parameters:
        - name: poId
          in: query
          required: false
          description: A purchase order to put away. Its distinct SKUs, in PO line order, and its location.
          schema: { type: string }
        - name: locationId
          in: query
          required: false
          description: Required together with `skus` when `poId` is absent.
          schema: { type: string }
        - name: skus
          in: query
          required: false
          description: Comma-separated, each entry `productId` or `productId:variantId`. Max 500.
          schema: { type: string }
      responses:
        "200":
          description: One line per SKU, with its primary destination and any overflow bins.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PutawayResponse" }
        "400":
          description: "`poId_or_location_and_skus_required` or `too_many_skus`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: "`po_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ── Valuation (V21) ──
  /inventory/valuation:
    get:
      tags: [Inventory]
      summary: Stock value at tracked cost (Manager)
      description: |
        `totalValueCents` is what the units on the shelf actually cost, tracked as
        a moving weighted average by the stock ledger. `listValueCents` is the same
        stock priced at `products.cost_cents`. A wide gap between them means the
        list costs are stale — that gap is the finding, not a rounding error.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: locationId, required: true, schema: { type: string } }
      responses:
        "200":
          description: Valuation, with a per-category breakdown.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ValuationReport" }
        "400":
          description: "`missing_locationId`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/valuation/history:
    get:
      tags: [Inventory]
      summary: Stock value over time (Manager)
      description: |
        One point per day, built by walking today's value *backwards* through the
        movement ledger. Needs no scheduled job and cannot drift from the ledger.

        Limit: movements written before V21 carry no value delta, so a window
        reaching back past the upgrade flattens rather than showing real history.
        `coveredFrom` is the earliest movement in the window.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: locationId, required: true, schema: { type: string } }
        - { in: query, name: days, schema: { type: integer, default: 30, minimum: 1, maximum: 365 } }
      responses:
        "200":
          description: Daily closing values.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ValuationHistory" }
        "400":
          description: "`missing_locationId` or `invalid_days`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/valuation/cogs:
    get:
      tags: [Inventory]
      summary: Cost of goods sold (Manager)
      description: |
        From the cost each sale was actually costed at, so margin is against what
        the goods cost rather than today's list price.

        Only `SALE` movements count as COGS. Wastage, expiry and supplier returns
        are reported separately — they are losses, not cost of goods *sold*, and
        folding them in would flatter or punish margin depending on the month.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: locationId, required: true, schema: { type: string } }
        - { in: query, name: days, schema: { type: integer, default: 30, minimum: 1, maximum: 365 } }
      responses:
        "200":
          description: COGS with losses broken out.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CogsReport" }

  # ── Batches / lots (V23) ──
  /inventory/batches:
    get:
      tags: [Inventory]
      summary: Live lots at a location
      description: "In FEFO pick order. Exhausted lots are retained for traceability but hidden unless `includeEmpty=true`."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: locationId, required: true, schema: { type: string } }
        - { in: query, name: productId, schema: { type: string } }
        - { in: query, name: includeEmpty, schema: { type: boolean, default: false } }
      responses:
        "200":
          description: Lots.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/BatchEntry" } }
    post:
      tags: [Inventory]
      summary: Record a lot directly (Manager)
      description: |
        For opening balances and deliveries that never had a purchase order.
        Normally lots are created by receiving a PO.

        Posts through the stock ledger, so the aggregate level and value move with
        it. Refused with `product_not_batch_tracked` unless the product has
        `trackBatches` on — a lot on an untracked product is a row nothing would
        ever deplete.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreateBatchRequest" }
      responses:
        "201":
          description: Lot recorded.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CreateBatchResponse" }
        "400":
          description: "`invalid_quantity`, `invalid_unit_cost`, `batch_code_blank`, `unknown_product`, `unknown_variant`, `unknown_location` or `product_not_batch_tracked`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/supplier-catalogue/import/review:
    post:
      tags: [Suppliers & Purchasing]
      summary: Review a supplier's price-list file
      description: |
        Reads the supplier's price list — a CSV, a spreadsheet saved as CSV, or cells pasted from one — against what is
        on their catalogue here, and answers the diff with nothing written (T-8.7). Each row is found by their code,
        then a barcode, then our SKU (a column headed "Our SKU"); never by its description. A blank cell leaves a figure
        as it is; a line on file the list does not mention is reported, not removed. Manager-gated.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SupplierPriceListImport" }
      responses:
        "200":
          description: The review — summary, per-row outcome with before and after, and the fingerprint the commit must send back.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SupplierPriceListReview" }
        "400":
          description: "`empty_csv`, or `unknown_supplier` (including another business's supplier)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/supplier-catalogue/import/commit:
    post:
      tags: [Suppliers & Purchasing]
      summary: Apply a reviewed price list
      description: |
        The same file with the review's `fingerprint`. The server reads it again and applies it in one transaction only
        if it reaches the same review; a file edited, or a catalogue changed, since the review is refused with 409
        `plan_stale` and nothing is written. Manager-gated.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SupplierPriceListImport" }
      responses:
        "200":
          description: Applied.
          content:
            application/json:
              schema:
                type: object
                properties:
                  updated: { type: integer }
                  added: { type: integer }
                  refused: { type: integer }
                  summary: { type: string }
        "400":
          description: "`empty_csv`, `fingerprint_required`, `nothing_to_apply`, `unknown_supplier`, or the file's own refusal code."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: "`plan_stale` — the file or the catalogue moved since the review."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/inventory/units/expiry:
    get:
      tags: [Inventory]
      summary: Expiry alerts by tier
      description: |
        Every live lot at a location that needs attention, first-expired-first-out, in its tier: `EXPIRED` (past
        its date), `CRITICAL` (within `criticalDays`) or `WARNING` (within `warningDays`), with the money at risk
        at the lot's own cost. `coverage` lists lot-tracked stock that no live lot accounts for — stock whose
        expiry nobody can see. Manager-gated, because every line carries a per-SKU cost. This is the report the
        back office's Lots & expiry tab reads (T-8.7); the tab's badge counts the `EXPIRED` and `CRITICAL` lots.
      parameters:
        - { in: query, name: locationId, required: true, schema: { type: string } }
        - { in: query, name: criticalDays, schema: { type: integer, default: 3, minimum: 0 } }
        - { in: query, name: warningDays, schema: { type: integer, default: 14, minimum: 0 } }
        - { in: query, name: productId, schema: { type: string } }
      responses:
        "200":
          description: The tiered report.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ExpiryReport" }
        "400":
          description: "`missing_locationId`, `invalid_days` (negative, or not a whole number) or `critical_beyond_warning`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/inventory/movements:
    get:
      tags: [Inventory]
      summary: Stock movement journal
      description: |
        Every movement in the tenant's append-only stock ledger, newest first, paged in SQL with `total` (every
        movement the filter matches, not the page size). Each row says who (`staffBasis`: `MOVEMENT` when the
        movement carries the staff id, `SALE` when it is the cashier on the sale it was posted for), why (reason,
        label, class, reference, note) and, only for a sale or loyalty redemption, the till recorded on the sale
        (`deviceBasis: SALE`). No other movement records a device, and none is claimed. `summary` totals every
        matched movement by reason; `reasonChoices` lists the reasons the filter accepts. Manager-gated: rows carry
        unit cost and value. `from`/`to` are SAST days, both inclusive. A malformed or unknown filter value is
        refused with the field named, never defaulted.
      parameters:
        - { in: query, name: locationId, schema: { type: string } }
        - { in: query, name: productId, schema: { type: string } }
        - { in: query, name: staffId, schema: { type: string } }
        - { in: query, name: reason, schema: { type: string }, description: "Comma-separated reason codes." }
        - { in: query, name: from, schema: { type: string, format: date } }
        - { in: query, name: to, schema: { type: string, format: date } }
        - { in: query, name: limit, schema: { type: integer, default: 50, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, format: int64, default: 0, minimum: 0 } }
      responses:
        "200":
          description: One page, its total and the by-reason summary.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MovementJournalPage" }
        "400":
          description: "`unknown_parameter`, `invalid_<field>` (malformed), `unknown_location`, `unknown_product`, `unknown_staff`, `unknown_reason` or `from_after_to`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /api/v1/inventory/movements/export:
    get:
      tags: [Inventory]
      summary: Stock movement journal as CSV
      description: |
        The same filter as `/inventory/movements` (no `limit`/`offset`: an export is the whole filter), as CSV, newest
        first. Refused with `422 export_too_large`, naming the count, when more than 50 000 movements match — never cut
        short. A text cell a spreadsheet would evaluate as a formula is written with a leading `'`.
      parameters:
        - { in: query, name: locationId, schema: { type: string } }
        - { in: query, name: productId, schema: { type: string } }
        - { in: query, name: staffId, schema: { type: string } }
        - { in: query, name: reason, schema: { type: string } }
        - { in: query, name: from, schema: { type: string, format: date } }
        - { in: query, name: to, schema: { type: string, format: date } }
      responses:
        "200":
          description: The CSV file.
          content:
            text/csv:
              schema: { type: string }
        "400":
          description: As `/inventory/movements`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "422":
          description: "`export_too_large`: narrow the dates, location or reason and export in parts."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/batches/trace/{batchCode}:
    get:
      tags: [Inventory]
      summary: Recall trace for a lot code
      description: "Deliberately across every location — a recall is not a per-shop question."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: batchCode, required: true, schema: { type: string } }
      responses:
        "200":
          description: Where the lot is, and how much is left.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BatchTrace" }
        "404":
          description: "`batch_code_not_found` — including another tenant's lot code."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /inventory/batches/reconcile:
    get:
      tags: [Inventory]
      summary: Lot totals vs aggregate on-hand
      description: |
        Both are written in the same transaction so they should agree. A non-empty
        result means stock moved through a path that bypassed lot tracking — most
        often a product that already held stock when `trackBatches` was switched on.

        Reports drift and does **not** correct it: adjusting one side to match the
        other would destroy the evidence of which path is wrong.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: locationId, required: true, schema: { type: string } }
      responses:
        "200":
          description: Drifting SKUs; empty when everything agrees.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/BatchDrift" } }
  /inventory/batches/write-off:
    post:
      tags: [Inventory]
      summary: Bin expired lots (Manager)
      description: |
        Takes explicit lot ids rather than a "write off everything expired" switch —
        throwing stock away is a decision per lot, and a blanket endpoint invites a
        cron job to quietly destroy inventory.

        Recorded as `EXPIRY`, not `WASTAGE`, so spoilage-through-age stays separable
        from breakage and theft.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WriteOffBatchRequest" }
      responses:
        "200":
          description: What was written off.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WriteOffBatchResponse" }
        "400":
          description: "`no_batches` or `unknown_batch` (including another tenant's lot)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ── Supplier returns / RTV (V22) ──
  /supplier-returns:
    get:
      tags: [Suppliers]
      summary: Supplier returns
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: locationId, schema: { type: string } }
        - { in: query, name: supplierId, schema: { type: string } }
        - { in: query, name: status, schema: { type: string, enum: [DRAFT, SENT, CREDITED, CANCELLED] } }
      responses:
        "200":
          description: Returns with their lines.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/SupplierReturn" } }
    post:
      tags: [Suppliers]
      summary: Raise a return (Manager)
      description: |
        Creates a DRAFT. Stock does **not** move yet — a draft is a picking list and
        the units are still physically in the store. Lines are priced on send.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreateReturnRequest" }
      responses:
        "201":
          description: Draft raised.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  reference: { type: string }
        "400":
          description: "`no_lines`, `invalid_quantity`, `invalid_reason`, `duplicate_line`, `unknown_location`, `unknown_supplier`, `unknown_product` or `unknown_variant`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /supplier-returns/outstanding:
    get:
      tags: [Suppliers]
      summary: Claims awaiting credit
      description: "Sent returns with no credit recorded, oldest first — the order to chase them in."
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Outstanding claims.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/SupplierReturn" } }
  /supplier-returns/{id}/send:
    post:
      tags: [Suppliers]
      summary: Send a return (Manager)
      description: |
        DRAFT → SENT. Stock leaves the shelf with reason `RTV` — **not** `WASTAGE` —
        which is what keeps returned goods out of the shrinkage report: the money is
        owed, not lost.

        Each line is costed at the moving average at this moment and that figure is
        frozen onto the line, so a later price change cannot restate a claim the
        supplier has already received. Runs the auto-86 sweep afterwards.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: Sent, with the claim total.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SendReturnResponse" }
        "409":
          description: "`return_not_draft`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /supplier-returns/{id}/credit:
    post:
      tags: [Suppliers]
      summary: Record a credit note (Manager)
      description: |
        `creditCents` may be **less** than the claim — a short credit is the normal
        case, not an error — and the difference surfaces as `shortfallCents`. A
        credit of `0` records a refused claim, which is a real outcome and better
        recorded than left permanently outstanding.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreditReturnRequest" }
      responses:
        "200":
          description: The credited return.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SupplierReturn" }
        "400":
          description: "`invalid_credit`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`return_not_sent`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /supplier-returns/{id}/cancel:
    post:
      tags: [Suppliers]
      summary: Cancel a draft return (Manager)
      description: "DRAFT only — a sent return's goods have physically gone. Record a credit of 0 for a refused claim instead."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: Cancelled.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  status: { type: string }
        "409":
          description: "`return_not_draft`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ── Loyalty points (V24) ──
  /loyalty/settings:
    get:
      tags: [Loyalty]
      summary: The tenant's loyalty economics
      description: |
        Both sides of the exchange: the earn rate and what a point is worth when
        spent. Every value is an integer — a float in a conversion a guest can
        audit at the till is a defect waiting to be reported as theft.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Settings.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoyaltySettings" }
    post:
      tags: [Loyalty]
      summary: Change the loyalty rates (Manager)
      description: "Keep-on-absent: omitted fields keep their current value."
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LoyaltySettingsRequest" }
      responses:
        "200":
          description: The updated settings.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoyaltySettings" }
        "400":
          description: "`invalid_earn_rate`, `invalid_point_value` (0 is refused — it would empty a balance silently), `invalid_minimum` or `invalid_max_pct`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /loyalty/balance/{customerId}:
    get:
      tags: [Loyalty]
      summary: Points balance and recent ledger
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: customerId, required: true, schema: { type: string } }
      responses:
        "200":
          description: Balance, its cash value, and the last 20 ledger entries.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoyaltyBalance" }
        "404":
          description: "`customer_not_found` — including another tenant's customer."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /loyalty/quote:
    post:
      tags: [Loyalty]
      summary: What may be spent on this bill
      description: |
        Commits nothing. Shares its arithmetic with `/redeem`, so the figure quoted
        at the till is the figure that gets charged.

        `maxValueCents` is what the redeemable points are worth *here*;
        `balanceValueCents` is what the whole balance is worth. They differ when a
        cap bites, which `cappedByBill` reports — a till needs both to say "worth
        R340, R210 usable on this bill".

        The cap chain is: the guest's balance, then `maxRedeemPctBp` of the bill,
        then what is actually still owed (subtotal less discounts already applied).
        Capping against the subtotal instead would let a voucher and a redemption
        together exceed the bill and drive the total negative.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LoyaltyQuoteRequest" }
      responses:
        "200":
          description: The quote. Check `available`; `reason` says why not.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoyaltyQuote" }
        "404":
          description: "`customer_not_found` or `order_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /loyalty/redeem:
    post:
      tags: [Loyalty]
      summary: Spend points on an open order
      description: |
        Open to all staff: redeeming a guest's own points is a normal till action,
        not a discretionary discount, and the amount is bounded by the tenant's
        settings rather than the operator's judgement.

        The discount lands in `pos_transactions.discount_cents` exactly like a
        voucher, so totals, VAT and every downstream report need no special case.
        A `LOYALTY` row is written to `discounts` alongside it, and the order
        records the points spent so a reversal knows what to return.

        Asking for more than the quote allows is **refused**, not silently trimmed:
        a till that quietly redeems fewer points than the cashier keyed gets
        reported as losing the guest's points. One live redemption per order — the
        order row is locked for the check, so two tills cannot both redeem.

        Earning on the net bill falls out for free: checkout computes points from
        the discounted total, so a guest does not earn fresh points on the portion
        their old points just paid for.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LoyaltyRedeemRequest" }
      responses:
        "201":
          description: Redeemed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoyaltyRedeemResult" }
        "400":
          description: "`invalid_points`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`customer_not_found` or `order_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`order_not_open`, `different_guests` (the bill is for another guest: one bill spends one guest's points), `already_redeemed`, `exceeds_redeemable`, `redemption_disabled`, `no_points`, `nothing_to_discount` or `below_minimum`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /loyalty/redeem/reverse:
    post:
      tags: [Loyalty]
      summary: Hand the points back
      description: |
        For a redemption keyed against the wrong guest, or an order about to be
        abandoned. Returns the points, removes the discount, and writes a
        `REDEEM_REVERSED` ledger row rather than deleting the original — the
        reversal is a new fact, not an amendment.

        Only while the order is still OPEN. Once paid, the discount is part of a
        settled bill and a refund is the correct instrument; clawing points back
        from a closed sale would leave the takings and the ledger disagreeing.

        After a reversal the same order may redeem again — a cashier who keys 250
        instead of 25 is doing something legitimate.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LoyaltyReverseRequest" }
      responses:
        "200":
          description: Reversed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LoyaltyReverseResult" }
        "409":
          description: "`nothing_redeemed`, `order_not_open` or `no_customer_on_order`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ── Promotions (V25) ──
  /promotions:
    get:
      tags: [Promotions]
      summary: List promotions
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: active, schema: { type: boolean } }
        - { in: query, name: type, schema: { type: string, enum: [BUY_X_GET_Y, MULTI_BUY, BASKET_PERCENT, BASKET_FIXED] } }
      responses:
        "200":
          description: Promotions, highest priority first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Promotion" } }
    post:
      tags: [Promotions]
      summary: Create a promotion (Manager)
      description: |
        Distinct from `/pricing` rules, which modify a **unit price** inside a time
        window (happy hour). Promotions reason about the **basket**: "buy 2 get 1"
        counts units across lines and decides which one is free, "3 for R100" prices
        a group, and "10% off over R500" depends on a total that does not exist until
        every line is in. The two compose — happy hour sets the prices, promotions
        run over the resulting basket.

        Validation refuses offers that could never work: a `MULTI_BUY` without a
        bundle price, a `BUY_X_GET_Y` giving away 0%, a scoped promotion pointing at
        a category that does not exist.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PromotionUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: "`name_required`, `promo_type_required`, `invalid_promo_type`, `invalid_scope_type`, `scope_ids_required`, `bundle_price_required`, `invalid_buy_quantity`, `invalid_get_discount`, `invalid_value`, `invalid_days_of_week`, `unknown_product` or `unknown_category`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`code_in_use` — codes are unique per tenant, because ambiguity would resolve by row order."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /promotions/{id}:
    post:
      tags: [Promotions]
      summary: Update a promotion (Manager)
      description: "Keep-on-absent: omitted fields keep their current value."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PromotionUpsertRequest" }
      responses:
        "200":
          description: The updated promotion.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Promotion" }
        "404":
          description: "`promotion_not_found` — including another tenant's."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /promotions/{id}/toggle:
    post:
      tags: [Promotions]
      summary: Activate or deactivate (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: The promotion, with `active` flipped.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Promotion" }
        "404":
          description: "`promotion_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /promotions/evaluate:
    post:
      tags: [Promotions]
      summary: What applies to an order
      description: |
        Commits nothing — a till calls this on every cart change so the guest can see
        the offer land. Shares its code path with `/apply` and with checkout, so a
        guest cannot be quoted one figure and charged another.

        `skipped` explains every live promotion that did **not** apply, which is what
        lets a cashier answer "why didn't my offer come off?".
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EvaluateRequest" }
      responses:
        "200":
          description: Awards and skips.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PromotionEvaluation" }
        "404":
          description: "`order_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /promotions/apply:
    post:
      tags: [Promotions]
      summary: Evaluate and write the discount to the order
      description: |
        Idempotent by recomputation: the previous promotion discount is removed and
        the freshly derived one added, so calling it repeatedly as a cart changes
        cannot accumulate. A manager's goodwill discount or a redeemed points balance
        sharing the same `discount_cents` column is left untouched.

        Calling this is **optional** — checkout re-evaluates promotions itself, so an
        automatic offer applies whether or not the client remembers. Use it to show
        the discount on the order before payment.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EvaluateRequest" }
      responses:
        "200":
          description: What was written.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApplyPromotionsResponse" }
        "409":
          description: "`order_not_open`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /promotions/{id}/performance:
    get:
      tags: [Promotions]
      summary: What a promotion has given away (Manager)
      description: |
        `usageCount` is the counter the engine gates on; `salesCount` and the totals
        come from the redemption rows. Both are reported — if they disagree the
        counter has drifted and the rows are the truth.

        The counter increments once per **sale**, not per application, and only at
        checkout. Counting in `/apply` would exhaust a limited-use offer on a
        customer who never paid.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: Performance.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PromotionPerformance" }

  # ── Composite bundles (V26) ──
  /bundles:
    get:
      tags: [Catalogue]
      summary: Every bundle with its slots and options
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Bundles.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Bundle" } }
    post:
      tags: [Catalogue]
      summary: Create or replace a bundle (Manager)
      description: |
        Replace-not-patch, like recipes: send the whole bundle. `201` on create, `200`
        on replace. Patching slots individually invites a half-edited meal deal that
        prices wrongly at the till.

        Distinct from a recipe, which explodes a dish into raw **ingredients**. A
        bundle's components are full products with their own stock, VAT type and
        kitchen station, so ringing one up expands into real sale lines.

        Refused when the bundle product tracks stock (`bundle_cannot_track_stock`) —
        its components deplete, and tracking both would double-count. Also refused
        for a bundle containing itself, or another bundle: expanding a nested bundle
        would need a selection the till has no way to prompt for.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BundleUpsertRequest" }
      responses:
        "200":
          description: Replaced.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Bundle" }
        "201":
          description: Created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Bundle" }
        "400":
          description: "`empty_bundle`, `empty_slot`, `invalid_pricing_mode`, `invalid_slot_quantity`, `slot_quantity_exceeds_options`, `duplicate_option`, `self_referencing_component`, `nested_bundle`, `unknown_product`, `unknown_component`, `unknown_variant` or `bundle_cannot_track_stock`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /bundles/{productId}:
    get:
      tags: [Catalogue]
      summary: One bundle
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: productId, required: true, schema: { type: string } }
      responses:
        "200":
          description: The bundle.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Bundle" }
        "404":
          description: "`bundle_not_found` — including another tenant's."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: [Catalogue]
      summary: Stop a product being a bundle (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: productId, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted. Slots and options cascade.
        "404":
          description: "`bundle_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /bundles/{productId}/quote:
    post:
      tags: [Catalogue]
      summary: Price a selection
      description: |
        Commits nothing — a till calls this as the guest chooses, so the price on
        screen is the price that gets rung up. Omit `selections` to price the
        bundle's defaults.

        Component prices are read **live**, so a menu price change flows into every
        bundle automatically rather than needing them re-saved.

        Each component's `lineTotalCents` is its apportioned share of the bundle
        price, pro-rata by list price with the truncation remainder given to the
        dearest component. The shares always total the bundle price exactly.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: productId, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BundleQuoteRequest" }
      responses:
        "200":
          description: The priced components.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BundleQuote" }
        "400":
          description: "`slot_required`, `wrong_selection_count`, `option_not_in_slot`, `unknown_slot` or `nothing_selected`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`bundle_inactive`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /orders/{orderId}/bundle:
    post:
      tags: [Orders]
      summary: Ring a bundle onto an order
      description: |
        Expands into **one sale line per component**, each priced at its apportioned
        share and all sharing a `bundleGroupId` so a bill can group them back into
        "Burger Meal — R120".

        Expanding rather than holding one opaque line means stock depletion, kitchen
        routing, VAT apportionment, per-product revenue and the 86 sweep all keep
        working untouched. Each component line carries the **component's** product id
        and its own `vatType`, so a bundle mixing standard-rated and zero-rated goods
        is taxed correctly with no special case.

        `quantity` creates that many independent bundle instances, each with its own
        group id — two meals on a bill are two things a guest can send back
        separately.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: orderId, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddBundleRequest" }
      responses:
        "201":
          description: Lines added.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddBundleResponse" }
        "400":
          description: "`invalid_quantity`, or any selection error from the quote endpoint."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`order_not_found` or `bundle_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`order_not_open` or `bundle_inactive`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  # ── Price lists (V27) ──
  # ─────────────────── Click & collect (V34) ───────────────────
  /public/collect/{tenantId}/{locationId}/slots:
    get:
      tags: ["Click & Collect"]
      summary: Bookable collection windows (public)
      description: >-
        No JWT — a customer ordering has no account. Slots are derived from
        per-location settings rather than stored, so changing the interval applies
        immediately. Full slots are omitted rather than greyed out: a public surface
        should not advertise a time it will then refuse. 404 until the venue enables
        collection.
      security: []
      parameters:
        - { name: tenantId, in: path, required: true, schema: { type: string } }
        - { name: locationId, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Windows with remaining capacity.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectSlots" }
        "404":
          description: "`location_not_found` or `collect_not_enabled`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /public/collect/{tenantId}/{locationId}/catalogue:
    get:
      tags: ["Click & Collect"]
      summary: What can be ordered right now (public)
      description: >-
        Quantified by `on_hand - reserved`, never on-hand: showing on-hand would
        promise the last item to two people, and the second finds out on arrival. A
        tracked product with nothing available is omitted entirely — this is an
        ordering surface, and a listing you cannot buy is a dead end. A non-tracked
        product returns a null unit count, having nothing to run out of. A product
        that is 86'd at this location is omitted too (and an order naming one is refused
        400 `product_unavailable`), and a hold whose collection window has closed is
        released first, so its stock is on offer again at this read.
      security: []
      parameters:
        - { name: tenantId, in: path, required: true, schema: { type: string } }
        - { name: locationId, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Orderable products, priced at this location.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CollectCatalogueItem" } }
        "404":
          description: "`collect_not_enabled`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /public/collect/{tenantId}/{locationId}/orders:
    post:
      tags: ["Click & Collect"]
      summary: Place a collection order (public)
      description: |
        Holds the stock. `reserved_units` is incremented under `SELECT … FOR UPDATE`
        with availability re-read inside the lock, so two customers ordering the last
        item at the same moment cannot both succeed — the second gets
        `409 out_of_stock`.

        **All-or-nothing**: a mixed order with one short line reserves nothing. A
        customer arriving to an incomplete order they have paid for is worse than
        being refused now.

        Prices are resolved server-side at this location and frozen — the price shown
        is the price paid, and a client cannot set its own.

        `clientToken` is strongly recommended: it makes a double-tap idempotent,
        returning 200 with `duplicate: true` and creating nothing.

        The requested slot is validated against the generated list, so an 03:00 slot,
        a non-boundary time, or one inside the lead time cannot be booked by posting a
        timestamp.
      security: []
      parameters:
        - { name: tenantId, in: path, required: true, schema: { type: string } }
        - { name: locationId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PlaceCollectOrderRequest" }
      responses:
        "201":
          description: Placed and holding stock.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectPlaced" }
        "200":
          description: This clientToken had already ordered — nothing was created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectPlaced" }
        "400":
          description: >-
            `contact_name_required`, `contact_phone_required`, `no_lines`,
            `invalid_quantity`, `too_many_lines`, `unknown_product`, `unknown_variant` (also a
            variant of another product), `line_price_negative`, `line_price_too_large` or
            `pay_on_collection_not_allowed`. Identical lines (a product and variant) are
            merged first; an order carries at most 50 different lines and, of one item, the
            venue's own figure (`maxPerItem` in the slots answer, 1 to 9999, 50 where none is set —
            T-2.54, D-110), and the refusal's `message` says so (T-2.35). A catalogue price outside core
            `SaleLine`'s range is not sold (T-2.34).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`slot_unavailable` or `out_of_stock` (which names the products)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "413":
          description: "`payload_too_large`: the body is over 256 KB, refused before it is read (T-2.35)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "408":
          description: "`body_too_slow`: the body did not arrive within ten seconds (T-2.35); nothing was read or written — send it again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: "`busy`: the location's collection desk was taken — its turn taken (two orders in flight there, or its business or the server at its share) and no turn within two seconds, its lock held by another order for longer than two seconds, or the placement past its five-second bound — so nothing was written and no reference taken; try again in a moment (T-2.35)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /public/collect/{tenantId}/orders/{id}:
    get:
      tags: ["Click & Collect"]
      summary: Track an order (public)
      description: >-
        Deliberately narrow: progress and a sentence, and none of the customer's phone
        number, the note, the reservation flag, the expiry or the line detail. A public
        surface shows progress, not the venue's operational state. The id is the
        capability, as a signed receipt link is.
      security: []
      parameters:
        - { name: tenantId, in: path, required: true, schema: { type: string } }
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Progress.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectTracking" }
        "404":
          description: "`order_not_found` — including another tenant's."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /collect/settings:
    get:
      tags: ["Click & Collect"]
      summary: Per-location configuration
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: Settings, or the disabled default.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectSettings" }
    post:
      tags: ["Click & Collect"]
      summary: Configure collection (Manager)
      description: >-
        `enabled` is false until a venue opts in, so nothing about an existing location
        changes on deploy. `allowPayOnCollection` is off by default: an order paid
        online cannot be abandoned, which is the whole risk this feature carries.
        `holdMinutes` is clamped to 1..1440 — zero would expire before the customer
        reached the payment screen.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CollectSettingsRequest" }
      responses:
        "200":
          description: Saved.
          content:
            application/json:
              schema: { type: object, additionalProperties: { type: string } }
        "400":
          description: >-
            `invalid_slot_minutes`, `invalid_capacity`, `invalid_hold`, `invalid_hours`
            or `unknown_location`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /collect/orders:
    get:
      tags: ["Click & Collect"]
      summary: The picking list, in slot order
      description: >-
        Open to any authenticated staff member — waiters do the picking. Each order
        carries `standing`, a sentence naming what to do next rather than a status code.
      security: [{ bearerAuth: [] }]
      parameters:
        - name: status
          in: query
          schema:
            type: string
            enum: [PENDING_PAYMENT, RESERVED, READY, SHORT, COLLECTED, CANCELLED, EXPIRED]
        - { name: locationId, in: query, schema: { type: string } }
      responses:
        "200":
          description: Orders.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CollectOrder" } }
  /collect/orders/{id}/pay:
    post:
      tags: ["Click & Collect"]
      summary: Take payment
      description: >-
        Creates the sale if needed and captures against it, the same call a layby
        instalment and a special-order deposit make, so the money counts towards the
        shift that took it. Full payment **clears the expiry**: a paid order is never
        dropped. Overpaying is refused. `invalid_method` (400) for any method but CASH, CARD, EFT or YOCO_CARD, before a sale is raised or a payment row is written (T-21.14).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CollectPayRequest" }
      responses:
        "200":
          description: Money position.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectMoney" }
        "400":
          description: "`invalid_amount` or `overpays_order`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`order_closed`, or `invalid_quantity` / `line_price_negative` / `line_price_too_large` for an order stored with a line a sale cannot carry (T-2.34) — cancel it and take it again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /collect/orders/{id}/ready:
    post:
      tags: ["Click & Collect"]
      summary: Picked and on the collection shelf
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectOrder" }
        "409":
          description: "`invalid_transition`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /collect/orders/{id}/notify:
    post:
      tags: ["Click & Collect"]
      summary: Record that the customer was told
      description: Separate from `ready` because the two genuinely come apart.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectOrder" }
        "409":
          description: "`nothing_to_notify`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /collect/orders/{id}/collect:
    post:
      tags: ["Click & Collect"]
      summary: Hand over and settle
      description: >-
        **Releases** the reservation and lets the ordinary checkout deplete. That is
        what makes a collected order cost at the moving average, deplete FEFO lots and
        post to the journal exactly as a walk-in does — reserving and depleting
        separately would need a second costing implementation that would drift. Legal
        from READY or SHORT; a customer may accept a short order. `invalid_method` (400) for any method but CASH, CARD, EFT or YOCO_CARD, before a sale is raised or a payment row is written (T-21.14).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CollectHandoverRequest" }
      responses:
        "200":
          description: Handed over.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectHandover" }
        "409":
          description: "`invalid_transition`, or `invalid_quantity` / `line_price_negative` / `line_price_too_large` for an order stored with a line a sale cannot carry (T-2.34)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /collect/orders/{id}/cancel:
    post:
      tags: ["Click & Collect"]
      summary: Cancel and release the hold
      description: >-
        Reports `refundDueCents` rather than silently keeping money already taken.
        Idempotent against a racing sweep — the release is guarded by a flag checked
        and cleared in the same locked transaction.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { type: object, properties: { reason: { type: string } } }
      responses:
        "200":
          description: Cancelled, with what was released and what is owed back.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectCancelled" }
        "409":
          description: "`invalid_transition`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /collect/sweep:
    post:
      tags: ["Click & Collect"]
      summary: Release expired holds (Manager)
      description: |
        **Idempotent**, so it is safe as both a button and a cron target — and it must
        run. A hold nobody releases is stock nobody can sell, invisible behind an
        on-hand figure that still looks right; over months a shop's availability drains
        away with no error anywhere.

        A **paid** order is never expired — the venue is holding the customer's money.
        Those are marked `SHORT` instead when a walk-in has taken the stock, so
        somebody rings the customer.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: What the sweep did.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CollectSweepResult" }
  # ─────────────────── Rota & delivery (V32) ───────────────────
  /rota:
    get:
      tags: ["Rota & Delivery"]
      summary: The roster for a window
      description: >-
        Staff see published shifts only — a half-finished week visible to everyone
        produces a morning of questions about shifts never meant to exist — and never
        see cost figures. `forecastCostCents` (the total and each person's) is null for non-managers, and for a
        session that may not read pay where the business requires a second factor (T-37.4).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: locationId, in: query, schema: { type: string } }
        - { name: preset, in: query, schema: { type: string, enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM], default: THIS_WEEK }, description: "Case-insensitive. Any other value is refused with 400 `invalid_preset` naming it; `CUSTOM` needs from and until (400 `custom_range_required`) (T-15.1). The default applies only when no dates are given." }
      responses:
        "200":
          description: The roster.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Rota" }
    post:
      tags: ["Rota & Delivery"]
      summary: Roster a shift (Manager)
      description: |
        A planned shift, deliberately **not** a row in `shifts`: that table records
        attendance, and writing a roster into it would mean publishing next week's
        rota created next week's clock-ins — counted in labour cost and holding
        registers nobody opened.

        Overlaps are refused, including the same person at two different branches.
        Half-open `[startsAt, endsAt)`, so a 17:00 handover is not an overlap and a
        split shift stays rosterable.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RotaUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          description: "`times_required`, `invalid_window`, `invalid_break`, `shift_too_long`, `unknown_staff` or `unknown_location`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`shift_overlaps` — one person cannot be in two places."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /rota/{id}:
    post:
      tags: ["Rota & Delivery"]
      summary: Move or edit a shift (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RotaUpsertRequest" }
      responses:
        "200":
          description: Updated.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "404":
          description: "`rota_shift_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: ["Rota & Delivery"]
      summary: Remove a shift (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204": { description: Deleted. }
        "404":
          description: "`rota_shift_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /rota/publish:
    post:
      tags: ["Rota & Delivery"]
      summary: Make a window visible to staff (Manager)
      description: >-
        Idempotent, and does **not** re-stamp already-published shifts — so "when was
        this published" keeps answering what staff actually ask: when could I first
        have seen it.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RotaPublishRequest" }
      responses:
        "200":
          description: How many shifts became visible.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RotaPublishResult" }
  /rota/mine:
    get:
      tags: ["Rota & Delivery"]
      summary: My own published shifts
      description: Keyed on the authenticated user, so a staff member can only fetch their own roster.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: preset, in: query, schema: { type: string, enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM], default: THIS_WEEK }, description: "Case-insensitive. Any other value is refused with 400 `invalid_preset` naming it; `CUSTOM` needs from and until (400 `custom_range_required`) (T-15.1). The default applies only when no dates are given." }
      responses:
        "200":
          description: Shifts.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/RotaShift" } }
  /rota/variance:
    get:
      tags: ["Rota & Delivery"]
      summary: Rostered against worked (VIEW_WAGES)
      description: |
        Each person's planned and paid cost is a wages read: VIEW_WAGES, held to the business's second factor
        (`403 second_factor_required`, T-37.4). The number neither table gives alone. Matched by staff member over the window
        rather than shift-by-shift: a pairing would need a rule for someone who worked
        a shift they were not rostered for, and every such rule guesses. Someone in
        only one list still gets a line — a shift worked with nobody rostered, and a
        roster nobody turned up for, are both what this exists to surface.

        Forecast cost uses **today's** rate; actual cost uses the rate frozen on each
        shift (V31). That asymmetry is intended: a plan prices at current pay, a past
        report must not move.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: locationId, in: query, schema: { type: string } }
        - { name: preset, in: query, schema: { type: string, enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM], default: LAST_WEEK }, description: "Case-insensitive. Any other value is refused with 400 `invalid_preset` naming it; `CUSTOM` needs from and until (400 `custom_range_required`) (T-15.1). The default applies only when no dates are given." }
      responses:
        "200":
          description: Variance per staff member.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RotaVariance" }
  /delivery/platforms:
    get:
      tags: ["Rota & Delivery"]
      summary: "Aggregators configured (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: The webhook secret is never echoed back — only whether one is set.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Platforms.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/DeliveryPlatform" } }
    post:
      tags: ["Rota & Delivery"]
      summary: "Configure an aggregator (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: >-
        One row per platform per location, so it is never ambiguous which commission
        rate and secret apply. `commissionBp` is capped at 10000 — above 100% the
        payout would be negative, which is a percent/basis-point slip rather than a
        commission arrangement.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeliveryPlatformUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          description: "`platform_required`, `invalid_platform`, `invalid_commission` or `location_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`platform_already_configured`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /delivery/platforms/{id}:
    post:
      tags: ["Rota & Delivery"]
      summary: "Update an aggregator (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: >-
        A rate change applies to orders from here on. Orders already ingested keep the
        split they were recorded with, so a renegotiated rate cannot restate last
        month's payouts.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeliveryPlatformUpsertRequest" }
      responses:
        "200":
          description: Updated.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "404":
          description: "`platform_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: ["Rota & Delivery"]
      summary: "Remove an aggregator (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: Refused once orders have come through — they carry the money split and would be orphaned.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204": { description: Deleted. }
        "409":
          description: "`platform_has_orders`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /delivery/platforms/{id}/items:
    get:
      tags: ["Rota & Delivery"]
      summary: "The platform item map (MANAGE_INTEGRATIONS: the owner or an admin)"
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Mappings.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/DeliveryItemMapping" } }
    post:
      tags: ["Rota & Delivery"]
      summary: "Map a platform item to a product (MANAGE_INTEGRATIONS: the owner or an admin)"
      description: >-
        Clears the unmapped flag on any order whose items are now all mapped, but does
        **not** rewrite those orders' lines — their stock movements and journal are
        already posted. The mapping applies from here on.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeliveryItemMapRequest" }
      responses:
        "200":
          description: How many orders left the queue.
          content:
            application/json:
              schema:
                type: object
                properties:
                  externalItemId: { type: string }
                  ordersCleared: { type: integer }
        "400":
          description: "`external_item_id_required`, `unknown_product` or `unknown_variant`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /delivery/orders:
    get:
      tags: ["Rota & Delivery"]
      summary: Delivery orders, newest first (FULFIL_ORDERS)
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Orders.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/DeliveryOrder" } }
    post:
      tags: ["Rota & Delivery"]
      summary: Ingest an aggregator order
      description: |
        **Idempotent on (platform, external id).** Every one of these platforms
        retries; without the unique index a retry creates a second sale, a second
        kitchen ticket and a second stock depletion, and the duplicate is only noticed
        weeks later when the platform statement fails to reconcile. A repeat returns
        200 with `duplicate: true` and creates nothing.

        Prices come from the platform's payload, not the catalogue: an aggregator's
        menu price is usually marked up, and re-pricing would make the sale disagree
        with both the customer's receipt and the statement.

        The claim, the sale, its lines and the kitchen fire are one transaction (T-13.6): a
        first placement reaches the kitchen screens at once, and a failure leaves nothing
        half-placed. The sale then settles through the ordinary checkout path with a
        `DELIVERY` tender — the customer has already paid the platform — so stock depletes,
        VAT computes and the journal posts as for any sale, debiting **1045 Delivery
        Platforms Receivable** (it debited Cash on Hand until T-13.6). Revenue is the
        **gross**; the platform's cut is recorded as commission. A repeat of an order whose
        settlement did not finish (`status: RECEIVED`) settles it, once.

        **An unmapped item does not reject the order.** Refusing would lose the trade
        and hide the order from the kitchen. The line is anchored to a per-tenant
        system product and the order flagged into `/delivery/orders/unmapped`.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeliveryIngestRequest" }
      responses:
        "201":
          description: Ingested and settled.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryIngestResult" }
        "200":
          description: Already seen — nothing was created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryIngestResult" }
        "400":
          description: "`external_id_required`, `no_lines`, `invalid_quantity`, `line_price_negative`, `line_price_too_large`, `too_many_lines` (over 200) or `delivery_order_refused` (a retry of one refused before). A refused order is kept as REJECTED with its `failureReason` and no sale. Each line is held to core `SaleLine` (T-2.34) — a quantity of 1–9 999, a unit price from nothing to R10 000 000 — by the one ingest a platform's webhook goes through too; nothing is written."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_platform`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`platform_inactive`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /delivery/webhook/{tenantId}/{platformId}:
    post:
      tags: ["Rota & Delivery"]
      summary: A delivery platform posts its own order (public, signed)
      description: |
        Public — no JWT. What authorises it is an HMAC-SHA256 over the **raw** body under the
        platform account's `webhookSecret`, read from the header the platform's channel names
        (`integrations/delivery/DeliveryChannel.kt`). The channel parses the platform's own
        order shape into Ruva's normalised order, which goes through the same ingest as
        `POST /delivery/orders`: placed once per platform order id, fired to the kitchen and
        settled. A recognised non-order event (a ping, a status change) answers 200 with
        `ingested: false` so the platform stops resending it.

        **No platform's adapter is live** (D-05): each needs a partner agreement and keys.
        Until one is registered, a platform's body is read by the shared parsers, which were
        written from public descriptions rather than a partner's documentation.

        **When the driver is due (T-36.9).** A body in Ruva's own shape (a platform with no adapter of its own) may carry
        `expectedArrivalAt` — epoch millis, or an ISO-8601 instant — beside `externalId`. It is kept on the delivery order and
        shown on the kitchen ticket as Driver due. An absent or unreadable value is none: nothing is estimated.
      security: []
      parameters:
        - { name: tenantId, in: path, required: true, schema: { type: string } }
        - { name: platformId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, description: "The platform's own order JSON, signed as sent." }
      responses:
        "201":
          description: Placed (and settled, unless `status` is `RECEIVED`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryWebhookAck" }
        "200":
          description: >-
            Already placed (`duplicate: true`), or a non-order event (`ingested: false`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryWebhookAck" }
        "400":
          description: "`unparseable_payload` — not the shape this platform sends, or no sellable line."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401":
          description: "`bad_signature` (missing or wrong) or `no_webhook_secret`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_platform`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`platform_inactive`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /delivery/orders/unmapped:
    get:
      tags: ["Rota & Delivery"]
      summary: The mapping queue (FULFIL_ORDERS)
      description: Orders with an item nobody has mapped, listing the ids to map.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Orders needing attention.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/DeliveryOrder" } }
  /delivery/orders/{id}/reconcile:
    post:
      tags: ["Rota & Delivery"]
      summary: Record what the platform actually paid (Manager)
      description: >-
        One-cent tolerance absorbs the platform rounding the other way. Reports the
        **implied commission rate**, which is how a venue discovers the rate it is
        really being charged rather than the one it was quoted — a consistent gap is
        usually a rate change nobody mentioned.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [actualPayoutCents]
              properties:
                actualPayoutCents: { type: integer, format: int64 }
      responses:
        "200":
          description: The comparison.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryReconciliation" }
        "404":
          description: "`delivery_order_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  # ─────────────────── Menus & invoices (V33) ───────────────────
  /menus/effective:
    get:
      tags: ["Menus & Invoices"]
      summary: What this till should show
      description: |
        Open to any authenticated staff member — a till needs it on every sync.

        A location with **no menu**, or one whose menu has **never been published**,
        gets every active product, which is exactly what every location did before
        this feature existed. Nothing changes on deploy, and an accidental assignment
        cannot blank a till. `source` says which mode it is in.

        Products deactivated globally are filtered even when a menu still lists them.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: locationId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: The effective product list.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EffectiveMenu" }
        "404":
          description: "`location_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /menus:
    get:
      tags: ["Menus & Invoices"]
      summary: Menus with their versions (Manager)
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Menus.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Menu" } }
    post:
      tags: ["Menus & Invoices"]
      summary: Create a menu (Manager)
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: "{ type: string, nullable: true }"
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema: { type: object, properties: { id: { type: string } } }
        "400":
          description: "`name_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`name_in_use`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /menus/{id}/items:
    post:
      tags: ["Menus & Invoices"]
      summary: Set the draft's products (Manager)
      description: >-
        Writes to the **draft** version only, so the live menu is untouched until
        publish — a till syncing mid-edit gets the last coherent version rather than a
        menu with the starters removed and the mains not yet added.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                productIds: { type: array, items: { type: string } }
      responses:
        "200":
          description: The draft.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MenuDraft" }
        "400":
          description: "`unknown_product`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`menu_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /menus/{id}/publish:
    post:
      tags: ["Menus & Invoices"]
      summary: Publish the draft (Manager)
      description: >-
        A single integer bump, so every till moves from one coherent version to the
        next with no intermediate state. The published items are carried forward as
        the next draft, so an edit starts from what is live. An **empty** draft is
        refused — publishing nothing would leave a till blank, which is far more
        likely a mistake than an intention.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Published.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MenuPublishResult" }
        "400":
          description: "`empty_menu`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /menus/{id}/rollback:
    post:
      tags: ["Menus & Invoices"]
      summary: Republish the previous version (Manager)
      description: Possible at all because versions are additive — a rollback is an integer write, not a restore.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Rolled back.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MenuPublishResult" }
        "409":
          description: "`nothing_to_roll_back_to` or `previous_version_empty`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /menus/{id}/assign:
    post:
      tags: ["Menus & Invoices"]
      summary: Point locations at a menu (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                locationIds: { type: array, items: { type: string } }
      responses:
        "200":
          description: How many were assigned.
          content:
            application/json:
              schema: { type: object, additionalProperties: { type: string } }
        "400":
          description: "`unknown_location`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /menus/{id}:
    delete:
      tags: ["Menus & Invoices"]
      summary: Delete a menu (Manager)
      description: >-
        Unassigns its locations first: one left pointing at a deleted menu would fall
        back to every active product silently, which looks like the feature failing
        rather than the menu being gone.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204": { description: Deleted. }
        "404":
          description: "`menu_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /invoices:
    get:
      tags: ["Menus & Invoices"]
      summary: Invoices, with OVERDUE derived (Manager)
      description: >-
        `status=OVERDUE` means ISSUED and past its due date — derived, never stored, so
        it cannot drift between sweeper runs. The filter runs after the derivation.
      security: [{ bearerAuth: [] }]
      parameters:
        - name: status
          in: query
          schema: { type: string, enum: [DRAFT, ISSUED, OVERDUE, PAID, VOID] }
        - { name: houseAccountId, in: query, schema: { type: string } }
      responses:
        "200":
          description: Invoices.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Invoice" } }
    post:
      tags: ["Menus & Invoices"]
      summary: Raise a draft invoice (Manager)
      description: |
        `transactionIds` consolidates sales onto it, which is the month-end case for a
        house account.

        **A sale can only ever be invoiced once** —
        `UNIQUE (tenant_id, transaction_id)` on invoice lines. Without it,
        consolidating twice (a double-click, a re-run, two people doing month-end)
        bills the customer for the same meals twice, and the error is only found when
        they refuse to pay. A sale already billed returns `409 already_invoiced`.

        Billing details are snapshotted from the account, so a later change of contact
        does not alter a document already sent.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/InvoiceCreateRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  invoiceNumber: { type: string, example: "INV-20260804-000001" }
        "400":
          description: "`bill_to_required`, `unknown_house_account`, `unknown_customer`, `unknown_location` or `unknown_transaction`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`already_invoiced`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /invoices/{id}:
    get:
      tags: ["Menus & Invoices"]
      summary: One invoice with its lines and payments (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The invoice.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Invoice" }
        "404":
          description: "`invoice_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /invoices/{id}/lines:
    post:
      tags: ["Menus & Invoices"]
      summary: Replace the lines while DRAFT (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/InvoiceLinesRequest" }
      responses:
        "200":
          description: Recomputed totals.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/InvoiceTotals" }
        "409":
          description: "`invoice_not_editable` — an issued invoice is corrected by credit note."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /invoices/{id}/issue:
    post:
      tags: ["Menus & Invoices"]
      summary: DRAFT → ISSUED (Manager)
      description: >-
        After this the invoice is immutable: a tax invoice is a legal document, and two
        versions with one number can never reconcile. `termsDays` sets the due date; 0
        means due on issue, null means no due date, which never goes overdue.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                termsDays: { type: integer, nullable: true, default: 30 }
      responses:
        "200":
          description: The issued invoice.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Invoice" }
        "400":
          description: "`invoice_empty`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`invalid_transition`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /invoices/{id}/payment:
    post:
      tags: ["Menus & Invoices"]
      summary: Record money received (Manager)
      description: >-
        Partial payment is normal on account. Overpaying is refused rather than
        absorbed: money beyond an invoice is a credit on the account, and swallowing it
        here would lose it.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/InvoicePaymentRequest" }
      responses:
        "200":
          description: The invoice, marked PAID once settled.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Invoice" }
        "400":
          description: "`invalid_amount` or `overpays_invoice`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`invoice_not_payable`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /invoices/{id}/void:
    post:
      tags: ["Menus & Invoices"]
      summary: Void an invoice (Manager)
      description: >-
        DRAFT or ISSUED only — a PAID invoice cannot be voided because money has moved
        and voiding would leave it unexplained. Voiding releases its sales so they can
        be invoiced properly, while the invoice keeps its number: a number is never
        reused, which is what an audit expects.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { type: object, properties: { reason: { type: string } } }
      responses:
        "200":
          description: The voided invoice.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Invoice" }
        "409":
          description: "`invalid_transition`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /invoices/{id}/credit-note:
    post:
      tags: ["Menus & Invoices"]
      summary: Correct an issued invoice (Manager)
      description: >-
        The only way. A new invoice with a negative total and negated lines, issued
        immediately with no draft stage, pointing at the original. Both documents
        survive, which is what the VAT Act expects. The original keeps its sales, so
        they still cannot be re-billed. Once credited, a second attempt is refused, and
        a credit note cannot itself be credited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { type: object, properties: { reason: { type: string } } }
      responses:
        "201":
          description: The credit note.
          content:
            application/json:
              schema: { type: object, additionalProperties: { type: string } }
        "409":
          description: "`invoice_not_issued`, `already_credited` or `already_a_credit_note`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  # ─────────────────── Saved reports & labour (V31) ───────────────────
  /reports/presets:
    get:
      tags: ["Saved Reports"]
      summary: Date presets, resolved against now
      description: |
        Returns each preset with its current window, so a UI can show "Last month
        (1–31 July)" rather than making the user guess. In the order a picker shows them;
        `LAST_7_DAYS` is labelled `Week`: the same days as `period=week`, today and the six before.

        Windows are half-open `[from, until)` and resolved in **SAST** — half-open so
        adjacent periods tile exactly (last month's `until` *is* this month's `from`),
        and SAST because a venue closing at 02:00 needs "yesterday" to mean their
        trading day. In-progress periods end at **now**, not at a future boundary.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Presets.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReportPreset" } }
  /reports/templates:
    get:
      tags: ["Saved Reports"]
      summary: Saved reports, each with its window resolved (VIEW_REPORTS)
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: >-
            Templates. `resolvedFrom`/`resolvedUntil`/`periodLabel` are computed live
            and never stored.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReportTemplate" } }
    post:
      tags: ["Saved Reports"]
      summary: Save a report (Manager)
      description: |
        **Stores a preset, not two dates.** Saving whatever range was on screen means
        "Last month", saved in August, reports July forever — it keeps working, keeps
        looking right, and is wrong from September onwards, with nothing complaining.
        A genuinely frozen range uses `CUSTOM` plus `customFrom`/`customUntil`, which
        is explicit about being frozen rather than accidentally so.

        `reportType` is whitelisted **here**, not at delivery: a template naming a
        report that does not exist would otherwise fail unattended at 07:00.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReportTemplateUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: >-
            `name_required`, `report_type_required`, `invalid_report_type`,
            `invalid_preset`, `custom_range_required`, `invalid_window` or
            `unknown_location`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`name_in_use`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /reports/templates/{id}:
    post:
      tags: ["Saved Reports"]
      summary: Update a saved report (Manager)
      description: Keep-on-absent — an omitted field keeps its current value.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReportTemplateUpsertRequest" }
      responses:
        "200":
          description: The updated template.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportTemplate" }
        "404":
          description: "`template_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: ["Saved Reports"]
      summary: Delete a saved report (Manager)
      description: >-
        Its schedules cascade, but the delivery history is kept — it is the record of
        what was emailed to whom, and retiring a schedule does not un-send last
        month's report.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "404":
          description: "`template_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /reports/templates/{id}/run:
    get:
      tags: ["Saved Reports"]
      summary: Run a saved report (VIEW_REPORTS)
      description: |
        Resolves the template's preset against **now**, so the same template run in
        September reports August — not whatever month it was created in.

        Returns columns and rows of strings rather than a typed shape per report, so
        one CSV writer serves every report; a per-report serialiser silently loses a
        column whenever someone forgets one.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The rendered report.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RenderedReport" }
        "404":
          description: "`template_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /reports/schedules:
    get:
      tags: ["Saved Reports"]
      summary: Scheduled deliveries (VIEW_REPORTS)
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Schedules, with the outcome of their last delivery.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReportSchedule" } }
    post:
      tags: ["Saved Reports"]
      summary: Schedule a saved report (Manager)
      description: |
        The cadence decides **when and how often**; the template's own preset decides
        **what period the report covers**. Deriving the content window from the
        cadence would make a template that says "Last month" email yesterday's
        figures — the saved intent silently overridden.

        `dayOfMonth` is capped at **28**: a monthly report set for the 30th would not
        fire in February, which reads as the feature being broken rather than as a
        configuration choice. A schedule with no recipients is refused, because it
        would run, succeed, and deliver nothing.

        EXPORT_DATA, without the second factor (D-151(2)): only a schedule carrying pay asks it, so a
        labour template also needs VIEW_WAGES, which is `403 second_factor_required` from a session
        that has not typed its code. Pausing, removing and running due schedules ask nothing; resuming
        a labour schedule asks it again.

        Recipients are **people of the business** — a user or a staff member, named by the email address
        or WhatsApp number on their record — whose role holds the report's own permission (`VIEW_REPORTS`;
        `VIEW_WAGES` for the labour report). Anyone else is refused with `recipient_cannot_read`. The same
        question is asked again each time the schedule is sent, of every recipient and of whoever made it
        (who also needs `EXPORT_DATA`): someone deactivated, removed, or no longer holding the permission
        is left out, and a schedule none of whose recipients remain is recorded `WITHHELD` and sends nothing.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReportScheduleUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: >-
            `invalid_cadence`, `recipients_required`, `invalid_recipient`,
            `recipient_cannot_read`, `invalid_hour`, `invalid_day_of_week`, `invalid_day_of_month` or
            `invalid_format`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`template_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /reports/schedules/{id}/toggle:
    post:
      tags: ["Saved Reports"]
      summary: Pause or resume a schedule (Manager)
      description: |
        EXPORT_DATA without the second factor (D-151(2)): pausing sends nothing. Resuming a labour
        schedule sends pay again, so it also needs VIEW_WAGES — `403 second_factor_required` from a
        session that has not typed its code.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The new state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  active: { type: string }
        "404":
          description: "`schedule_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /reports/schedules/{id}:
    delete:
      tags: ["Saved Reports"]
      summary: Delete a schedule (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "404":
          description: "`schedule_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /reports/schedules/run-due:
    post:
      tags: ["Saved Reports"]
      summary: Deliver everything due (Manager)
      description: |
        **Idempotent.** `UNIQUE (schedule_id, period_key)` makes "once per period" a
        property of the schema rather than of whoever wrote the scheduler, so seven
        calls deliver once — which is what makes this safe as both a button and a cron
        target.

        Due-ness is "has the hour passed and have we not covered this period", not "is
        it exactly 07:00": an exact match misses the period entirely whenever the
        process is restarting or a minute late, and the report simply never arrives.

        A schedule already delivered for its period returns `ALREADY_SENT` rather than
        being omitted — "it ran and there was nothing to do" and "it did not run" are
        different answers to the only question asked when a report has not arrived.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: One outcome per schedule considered.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReportDeliveryOutcome" } }
  /reports/deliveries:
    get:
      tags: ["Saved Reports"]
      summary: What went out, and what did not (VIEW_REPORTS)
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Recent deliveries, newest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ReportDelivery" } }
  /reports/labour:
    get:
      tags: ["Saved Reports"]
      summary: Labour cost against sales (VIEW_REPORTS)
      description: |
        The rate is the one **snapshotted onto each shift at clock-in**, so a pay rise
        cannot restate a past report — "labour was 28% of sales in May" stays 28%.

        An overnight shift is **clipped** to the window rather than counted whole in
        both days it spans, and its break is pro-rated by the clipped portion; without
        that, a Friday-night shift would double the weekend's labour cost. **Open
        shifts count up to now**, because a live figure excluding everyone currently
        working is useless mid-service. **The sales are net sales** — `Trading`'s, ex
        VAT and without tips (T-14.2; it was the bill totals with both until then).
        **Time on duty with no drawer open counts** (T-25.9): a chef clocked on at the
        kitchen screen or a phone opens no shift, and their duty-log minutes no drawer
        covers are worked time, costed at the person's current rate (a stint snapshots
        none) — the same count the tips report and the payroll file read, so a stint and
        a drawer over the same minutes count once.
        **Zero sales with labour on the clock reports
        0%, not infinity** — a closed day someone was paid for, shown as a huge
        number, would make every genuine outlier invisible beside it.
      security: [{ bearerAuth: [] }]
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - { name: preset, in: query, schema: { type: string, enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM] }, description: "A preset wins over explicit dates. Case-insensitive. Any other value is refused with 400 `invalid_preset` naming it (T-15.1)." }
        - { name: from, in: query, schema: { type: integer, format: int64 } }
        - { name: until, in: query, schema: { type: integer, format: int64 } }
        - { name: locationId, in: query, schema: { type: string } }
      responses:
        "200":
          description: Labour cost, the percentage, and a per-staff breakdown.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LabourReport" }
  /api/v1/reports/payroll:
    get:
      tags: ["Saved Reports"]
      summary: The pay period's payroll file — hours, tips and commission per person (VIEW_WAGES)
      description: |
        One line per person for a pay period, for whoever runs pay. **Nothing is worked out here**: each figure is read from the
        owner that already answers it, so the file agrees with the screens a manager has read all period —
        paid minutes are the person's shifts **less their breaks** and their time **on duty with no drawer open** (a chef clocked
        on at the kitchen screen; a stint and a drawer over the same minutes count once) — the labour report's and the tips
        report's one count; an overnight shift is clipped to the period. The wages are those minutes at the rate **snapshotted
        onto each shift**, and duty time alone at the person's current rate. Tips owed are the tips report's "paid out" over
        the location's pooling rules (added across locations unless `locationId` names one; tips held back because nobody was
        on shift to share them are named in `notes`, by the location's name, not in anyone's line). Commission is what was
        written in the period net of reversals, with how much of it is still unpaid — **business-wide only**: an entry records
        no location, so with `locationId` both commission fields are absent and `notes` says so. A drawer or a duty stint
        still open is counted to now (or the period's end) and named in `notes` ("Not clocked out — check") so it is not paid
        on trust. `role` is in words ("Chef", "Owner").

        `format=csv` is the file: one header row, then a row per person, with the columns `Staff ID`, `Person`, `Role`,
        `Paid minutes`, `Paid hours` (to the hundredth), `Hourly rate (R/h)`, `Wages (R)`, `Tips owed (R)`,
        `Commission earned (R)`, `Commission still owed (R)` (blank in a one-location file); then a blank line, a `Period` row
        and one `Note` row per note. Money is rands with two decimals and no symbol. The download is named after its period
        (`payroll-2026-10-01-to-2026-10-31.csv`). `format=pdf` lays out the same table and notes. Without `format` the JSON
        below is returned.

        The file carries each person's pay rate, so it needs `VIEW_WAGES` (and the second factor where the business asks for
        one on wages); a role without it is refused with 403 before anything is read. Defaults to `LAST_MONTH`.
      security: [{ bearerAuth: [] }]
      parameters:
        - $ref: "#/components/parameters/ExportFormat"
        - { name: preset, in: query, schema: { type: string, enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM] }, description: "A preset wins over explicit dates. Case-insensitive. Any other value is refused with 400 `invalid_preset` naming it." }
        - { name: from, in: query, schema: { type: integer, format: int64 } }
        - { name: until, in: query, schema: { type: integer, format: int64 } }
        - { name: locationId, in: query, schema: { type: string }, description: "One location; omitted, every location of the business." }
      responses:
        "200":
          description: The payroll file for the period.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PayrollFile" }
        "403":
          description: The caller does not hold `VIEW_WAGES`.
  /reports/by-dimension:
    get:
      tags: ["Saved Reports"]
      summary: Sales grouped by brand, supplier or category (VIEW_REPORTS)
      description: |
        `brand` and `supplier_id` have sat on products since V18 and nothing ever
        aggregated by them, so "which supplier's stock earns us the most" — the
        question a buyer asks before renegotiating — had no answer.

        Products with nothing recorded go into an explicit `__unset__` bucket labelled
        "Not recorded", **never dropped**: dropping them would make this report's
        total quietly disagree with the sales report, and that bucket is exactly the
        list of products someone needs to go and fill in. It is drillable. Units, revenue,
        cost and margin are `ProductMix`'s, cost recipe-aware (T-14.2: it was the product's own
        `cost_cents`).
      security: [{ bearerAuth: [] }]
      parameters:
        - name: dimension
          in: query
          schema: { type: string, enum: [brand, supplier, category], default: brand }
        - $ref: "#/components/parameters/ExportFormat"
        - { name: preset, in: query, schema: { type: string, enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM] }, description: "Case-insensitive. Any other value is refused with 400 `invalid_preset` naming it; `CUSTOM` needs from and until (400 `custom_range_required`) (T-15.1)." }
        - { name: from, in: query, schema: { type: integer, format: int64 } }
        - { name: until, in: query, schema: { type: integer, format: int64 } }
        - { name: locationId, in: query, schema: { type: string } }
      responses:
        "200":
          description: Grouped revenue, cost and margin, biggest first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DimensionReport" }
        "400":
          description: "`invalid_dimension`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /reports/drilldown:
    get:
      tags: ["Saved Reports"]
      summary: The sales behind one report row (VIEW_REPORTS)
      description: >-
        A total nobody can open is a total nobody trusts: "Suppliers R48,000" is only
        useful if you can see which sales it came from. Pass `value=__unset__` to open
        the "Not recorded" bucket, which is how you find products missing a supplier.
      security: [{ bearerAuth: [] }]
      parameters:
        - name: dimension
          in: query
          schema: { type: string, enum: [brand, supplier, category] }
        - { name: value, in: query, required: true, schema: { type: string } }
        - { name: preset, in: query, schema: { type: string, enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM] }, description: "Case-insensitive. Any other value is refused with 400 `invalid_preset` naming it; `CUSTOM` needs from and until (400 `custom_range_required`) (T-15.1)." }
        - { name: from, in: query, schema: { type: integer, format: int64 } }
        - { name: until, in: query, schema: { type: integer, format: int64 } }
        - { name: locationId, in: query, schema: { type: string } }
      responses:
        "200":
          description: Up to 500 sale lines, newest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/DrilldownLine" } }
        "400":
          description: "`invalid_dimension` or `value_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  # ─────────────────────── Commission (V30) ───────────────────────
  /commission/schemes:
    get:
      tags: ["Commission"]
      summary: Commission schemes (VIEW_WAGES, held to the second factor)
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Schemes, with how many entries each has earned.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CommissionScheme" } }
    post:
      tags: ["Commission"]
      summary: Create a scheme (VIEW_WAGES, held to the second factor)
      description: |
        Schemes **stack**: "2% on everything" plus "5% on wine" is a deliberate
        arrangement, and a line can earn under both.

        `rateBp` is basis points (500 = 5%) and is capped at 10000 — a higher value
        is almost always a percent/basis-point mix-up, and catching it here is
        cheaper than catching it on a payslip.

        An unrecognised `basis` or `scopeType` pays **nothing** rather than
        everything: a configuration typo must not silently widen a scheme to the
        whole menu.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CommissionSchemeUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: >-
            `name_required`, `rate_required`, `invalid_rate`, `invalid_basis`,
            `invalid_scope`, `scope_ids_required`, `unknown_staff` or `invalid_window`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`name_in_use`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /commission/schemes/{id}:
    post:
      tags: ["Commission"]
      summary: Update a scheme (VIEW_WAGES, held to the second factor)
      description: |
        Keep-on-absent. Editing a rate does **not** restate commission already
        accrued — entries carry their own frozen `rateBp`, so the change applies to
        future sales only. A mid-month rate rise must not silently re-price the
        first half of the month.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CommissionSchemeUpsertRequest" }
      responses:
        "200":
          description: Updated.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "404":
          description: "`scheme_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: ["Commission"]
      summary: Delete a scheme (VIEW_WAGES, held to the second factor)
      description: >-
        Refused once anything has been earned under it: entries reference the scheme
        and are pay records, so deleting it would make a payslip unexplainable.
        Deactivate instead.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "409":
          description: "`scheme_has_entries`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /commission:
    get:
      tags: ["Commission"]
      summary: Per-staff commission for a period (VIEW_WAGES, held to the second factor)
      description: |
        `period` is `YYYY-MM` in SAST, defaulting to the current month. Amounts are
        signed, so reversals net off. `owedCents` is never negative — a staff member
        overpaid because of a later refund is a conversation, not a deduction the
        next payslip makes silently.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: period, in: query, schema: { type: string, example: "2026-08" } }
      responses:
        "200":
          description: Totals per staff member, most owed first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/StaffCommission" } }
  /commission/{staffId}:
    get:
      tags: ["Commission"]
      summary: The entries behind one staff member's number (VIEW_WAGES, held to the second factor)
      description: >-
        What makes commission arguable-with rather than argued-about. Each entry's
        `baseCents × rateBp ÷ 10000` reproduces its `amountCents`, so a report can
        never disagree with a payslip. Negative amounts are refund reversals.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: staffId, in: path, required: true, schema: { type: string } }
        - { name: period, in: query, schema: { type: string } }
      responses:
        "200":
          description: Entries, oldest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CommissionEntry" } }
        "404":
          description: "`staff_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /commission/{staffId}/pay:
    post:
      tags: ["Commission"]
      summary: Mark a period's commission paid (VIEW_WAGES, held to the second factor)
      description: |
        Only ACCRUED rows move, so paying twice hands over nothing the second time.
        Reversals carry ACCRUED too and settle in the same pass — they are negative
        amounts equally pending settlement, and leaving them behind would make the
        paid figure gross while the total stayed net.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: staffId, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PayCommissionRequest" }
      responses:
        "200":
          description: What was handed over.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PayCommissionResult" }
        "404":
          description: "`staff_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  # ─────────────────────── Marketing (V29) ───────────────────────
  /segments:
    get:
      tags: ["Marketing"]
      summary: Segments, with a plain-English rule and a live size
      description: |
        `size` is who matches **right now** — membership is derived, not stored.
        `reachableWhatsapp` / `reachableEmail` are reported separately because a
        segment of 200 of whom 40 have opted in is a 40-person campaign, and a
        manager who only sees 200 will blame the message.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Segments.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Segment" } }
    post:
      tags: ["Marketing"]
      summary: Create a segment (Manager)
      description: |
        Criteria are **ANDed** — every non-null field must match, and an empty rule
        is every customer. There is no OR: "gold OR big spenders" is two segments,
        which is also two separately measurable campaigns.

        Impossible windows are refused by name rather than silently returning
        nobody.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SegmentUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: >-
            `name_required`, `impossible_spend_window`, `impossible_visit_window`,
            `invalid_birthday_month`, `invalid_lapsed_days` or `invalid_active_days`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`name_in_use` — a duplicate is invisible to whoever later picks one from a list."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /segments/preview:
    post:
      tags: ["Marketing"]
      summary: Size an unsaved rule
      description: |
        The point of the feature: learn that "gold, lapsed 90 days" is four people
        **before** writing the message, not after sending it. Returns the
        description, the size, how many are reachable per channel, and a sample.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SegmentPreviewRequest" }
      responses:
        "200":
          description: The audience this rule would select.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SegmentPreview" }
  /segments/{id}:
    post:
      tags: ["Marketing"]
      summary: Update a segment (Manager)
      description: |
        Keep-on-absent. Send `ruleProvided: false` to rename without touching the
        criteria — without that flag an update carrying only a name would reset the
        rule to "everyone", the default value being indistinguishable from an
        omitted one.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SegmentUpsertRequest" }
      responses:
        "200":
          description: The updated segment.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Segment" }
        "404":
          description: "`segment_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: ["Marketing"]
      summary: Delete a segment (Manager)
      description: |
        Refused if a campaign targeted it — deleting the segment out from under a
        campaign would leave that campaign's audience unexplainable. Deactivate
        instead.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "409":
          description: "`segment_in_use`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /segments/{id}/members:
    get:
      tags: ["Marketing"]
      summary: Who is in a segment right now
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Members.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/SegmentMember" } }
  /campaigns:
    get:
      tags: ["Marketing"]
      summary: Campaigns with their outcome counters
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: status, in: query, schema: { type: string } }
      responses:
        "200":
          description: Campaigns.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Campaign" } }
    post:
      tags: ["Marketing"]
      summary: Create a campaign (Manager)
      description: |
        One channel per campaign, because the body is written for the channel — an
        email subject is meaningless on WhatsApp. Reaching people both ways is two
        campaigns, which is also two measurements.

        **Unknown placeholders are rejected here**, not at send: discovering
        `{nmae}` after a thousand messages have gone out cannot be undone. A
        *missing value* never leaves a hole either — `{name}` for a customer with
        no name renders "there", so nobody receives "Hi ,".
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CampaignUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: >-
            `name_required`, `channel_required`, `invalid_channel`, `body_required`
            or `unknown_placeholder` (whose message lists the valid tokens).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /campaigns/{id}:
    get:
      tags: ["Marketing"]
      summary: One campaign
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The campaign.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "404":
          description: "`campaign_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: ["Marketing"]
      summary: Update a campaign (Manager)
      description: |
        Allowed while DRAFT or SCHEDULED only. A sent campaign is a record of what
        went out; editing its body would make the recipient rows describe a message
        that was never sent.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CampaignUpsertRequest" }
      responses:
        "200":
          description: The updated campaign.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "409":
          description: "`campaign_not_editable`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /campaigns/{id}/send:
    post:
      tags: ["Marketing"]
      summary: Resolve the audience and send (Manager)
      description: |
        **Every audience member gets a recipient row.** A customer who cannot be
        messaged is written as SUPPRESSED with a reason — `NO_CONSENT` (marketing),
        `NO_ADDRESS` (data), `DUPLICATE` (the guard working) or `NOT_CONFIGURED`
        (deployment) — so `sentCount + failedCount + suppressedCount` always
        accounts for `audienceCount`. Collapsing those into one "not delivered"
        number tells a manager which of them to fix: none.

        Rows are written **before** each send, so a process that dies mid-campaign
        leaves an accurate record of how far it got, and
        `UNIQUE (campaign_id, customer_id)` means a retry cannot double-message
        anyone. Addresses are snapshotted, so a later number change does not rewrite
        this campaign's history.

        Sending twice is refused under a row lock on the campaign.

        `dryRun: true` means the channel has no credentials, so **nothing was
        delivered** — reported explicitly rather than counted as success.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SendCampaignRequest" }
      responses:
        "200":
          description: What happened.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SendCampaignResult" }
        "409":
          description: "`campaign_not_sendable` — already sent, or cancelled."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /campaigns/{id}/cancel:
    post:
      tags: ["Marketing"]
      summary: Cancel before sending (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The cancelled campaign.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "409":
          description: "`campaign_not_cancellable`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /campaigns/{id}/recipients:
    get:
      tags: ["Marketing"]
      summary: Who a campaign reached, and who it did not
      description: >-
        Filterable by status. `suppressReason` names whose job the fix is;
        `channelAddress` is the address as it was at send time.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - name: status
          in: query
          schema: { type: string, enum: [PENDING, SENT, FAILED, SUPPRESSED] }
      responses:
        "200":
          description: Recipients.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CampaignRecipient" } }
  /lifecycle:
    get:
      tags: ["Marketing"]
      summary: Lifecycle automations, with totals
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Automations.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/LifecycleAutomation" } }
    post:
      tags: ["Marketing"]
      summary: Create or replace an automation (Manager)
      description: |
        **Replaces** any existing automation for the same trigger and channel rather
        than adding a second: two active birthday WhatsApps would send every
        customer two messages, and the dedupe log cannot catch that because they are
        different automations.

        `WIN_BACK` with `days: 0` is refused — every customer would be "lapsed" the
        instant they paid, so the message saying "we miss you" would arrive before
        they left the building.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LifecycleUpsertRequest" }
      responses:
        "201":
          description: Saved.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: >-
            `invalid_trigger`, `invalid_channel`, `body_required`,
            `unknown_placeholder`, `invalid_days` or `win_back_needs_days`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /lifecycle/run:
    post:
      tags: ["Marketing"]
      summary: Evaluate every automation now (Manager)
      description: |
        **Idempotent by design**, which is what makes it safe both as a button and
        as a schedule. Each trigger's condition stays true for as long as it holds —
        a birthday is true all day, and someone lapsed 60 days is still lapsed
        tomorrow — so a sweep with no memory would send a win-back every single day.
        Each send records a `period_key` unique per (automation, customer): the year
        for a birthday, the `last_visit_at` they lapsed from for a win-back, a
        constant for a welcome, the transaction for a review request. The insert
        **is** the claim, because a check-then-send would let two overlapping sweeps
        both pass the check.

        `skippedAlreadySent` is the dedupe log doing its job, not an error.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: One result per active automation.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/LifecycleRunResult" } }
  /lifecycle/{id}/toggle:
    post:
      tags: ["Marketing"]
      summary: Pause or switch on an automation (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The new state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  active: { type: boolean }
        "404":
          description: "`automation_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /lifecycle/{id}:
    delete:
      tags: ["Marketing"]
      summary: Delete an automation (Manager)
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted.
        "404":
          description: "`automation_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /customers/{id}/consent:
    get:
      tags: ["Marketing"]
      summary: The consent audit trail
      description: >-
        Newest first. Re-consenting appends rather than overwrites, so opting back
        in does not erase an earlier withdrawal — which is the point.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Consent events.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ConsentEvent" } }
    post:
      tags: ["Marketing"]
      summary: Record an opt-in or opt-out
      description: |
        Writes the event and updates the flag the send path reads, in one
        transaction. The flag alone cannot answer "prove they agreed", which is what
        POPIA asks for. Consent is per channel: opting out of WhatsApp says nothing
        about email.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ConsentRequest" }
      responses:
        "200":
          description: Recorded.
          content:
            application/json:
              schema:
                type: object
                additionalProperties: { type: string }
        "400":
          description: "`invalid_channel` or `invalid_source`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/customers/{id}/delete:
    post:
      tags: [Customers]
      summary: Remove a guest from the book (EDIT_CUSTOMERS)
      description: |
        The guest's erasure, never a bare hide: the row is marked deleted so tills drop it on their next pull, and every place
        their details sit is cleared (as `/customers/{id}/anonymise`, which it shares its owner with). Past sales keep their
        amounts. Refused while money is open between the guest and the venue — store credit, an open lay-by, a house account
        with a balance — each with its own code and the remedy (the retention sweep skips such a guest too). A guest already
        removed answers OK. Writing to a guest removed afterwards answers `customer_anonymised`.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: The guest is removed.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "403":
          description: The caller lacks EDIT_CUSTOMERS (`permission_required`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "404":
          description: No such guest in this business (`customer_not_found`).
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
        "409":
          description: >-
            Money is open between the guest and the venue: store credit (`store_credit_outstanding`), an open lay-by
            (`layby_open`) or a house account with a balance (`house_account_balance`); the message names the remedy.
          content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } }
  /api/v1/customers/{id}/anonymise:
    post:
      tags: ["Marketing"]
      summary: Erase a guest's personal information now
      description: |
        For a guest who asks to be forgotten (POPIA s24), rather than waiting for the
        retention sweep. Name becomes "Deleted guest"; phone, email, birthday, tags, notes,
        address and VAT number are cleared, opt-ins go off and the row is deleted so tills
        drop it on their next pull. The row stays because sales reference it. The consent
        ledger keeps its rows and loses its notes. EDIT_CUSTOMERS. A second request answers
        OK with the original time. Afterwards, writing to or opting in this guest answers
        410 `customer_anonymised`: add them as a new guest.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Anonymised.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  anonymisedAt: { type: string, description: "Epoch milliseconds, as a string." }
        "403":
          description: "The caller lacks EDIT_CUSTOMERS (`permission_required`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`customer_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "Money is open between the guest and the venue, as `/customers/{id}/delete` refuses: `store_credit_outstanding`, `layby_open` or `house_account_balance`; the message names the remedy."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/support-access:
    get:
      tags: ["System"]
      summary: Whether Ruva support may act for this business now
      description: >-
        The banner every till, kitchen screen and back-office session shows while support access is open: until when, and in
        which areas. Every role reads it, a paired screen included.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Support access now.
          content:
            application/json:
              schema:
                type: object
                required: [open]
                properties:
                  open: { type: boolean }
                  until: { type: integer, format: int64, nullable: true, description: Epoch milliseconds the latest open grant ends. }
                  scopes: { type: array, items: { type: string, enum: [ORDERING, MENU] } }
    post:
      tags: ["System"]
      summary: Let Ruva support act for this business
      description: >-
        Opens support access for 15 to 480 minutes (60 by default) in the areas named: ORDERING (pause or
        resume guest ordering) and MENU (86 a dish or put it back). Money, the subscription, payment accounts,
        people and customers are never an area. Needs ASSIGN_ROLES (owners and managers), and the giver must work
        in each area themselves. Replaces any grant still open. Every write support then makes is authored by
        the support person and listed in the history.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [scopes]
              properties:
                scopes: { type: array, items: { type: string, enum: [ORDERING, MENU] } }
                minutes: { type: integer, minimum: 15, maximum: 480, default: 60 }
      responses:
        "201":
          description: The grant.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  scopes: { type: array, items: { type: string, enum: [ORDERING, MENU] } }
                  grantedBy: { type: string, description: The venue person who gave it (user id). }
                  grantedAt: { type: integer, format: int64 }
                  expiresAt: { type: integer, format: int64 }
                  revokedAt: { type: integer, format: int64, nullable: true }
                  revokedBy: { type: string, nullable: true }
        "400":
          description: "`support_minutes_out_of_range`, `support_scope_required` or `unknown_support_scope`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`permission_required` or `support_scope_beyond_your_role`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: ["System"]
      summary: End Ruva support's access now
      description: >-
        Ends every open grant at once: support's next act is refused. 204 whether or not one was open.
        Needs ASSIGN_ROLES.
      security: [{ bearerAuth: [] }]
      responses:
        "204":
          description: Ended.
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/support-access/history:
    get:
      tags: ["System"]
      summary: Who from Ruva support acted for this business, and when
      description: >-
        The grants (newest first) and every write support made under them: when, the support person's id and
        work address, the action and what it touched. Needs ASSIGN_ROLES.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Grants and acts, newest first, 50 of each at most.
          content:
            application/json:
              schema:
                type: object
                properties:
                  grants: { type: array, items: { type: object } }
                  acts:
                    type: array
                    items:
                      type: object
                      properties:
                        at: { type: integer, format: int64 }
                        operatorId: { type: string }
                        operatorEmail: { type: string, nullable: true }
                        action: { type: string, example: support.location.ordering_pace }
                        entityType: { type: string, nullable: true }
                        entityId: { type: string, nullable: true }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/privacy/retention:
    get:
      tags: ["Marketing"]
      summary: How long guests' personal information is kept
      description: >-
        Months after a guest's last visit (or after they were added, if they never
        visited) before the hourly sweep anonymises them. 24 by default. A guest holding
        store credit is kept. Manager-gated.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: The period.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RetentionDto" }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: ["Marketing"]
      summary: Set how long guests' personal information is kept
      description: >-
        1 to 120 months. Shortening it takes effect on the next hourly sweep, which
        anonymises every guest now outside the period. Manager-gated.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RetentionDto" }
      responses:
        "200":
          description: Saved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RetentionDto" }
        "400":
          description: "`invalid_retention_months`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`manager_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/cashier-discount-limit:
    get:
      tags: ["Staff"]
      summary: How much a cashier may discount alone
      description: >-
        The whole percentage of a line or a bill a cashier may take off without a manager's approval. 0, the
        default, means every discount needs a manager. Readable by whoever sells (`TILL_SELL`: the till pulls it for
        its own check while offline) and by a manager at Settings (`EDIT_SETTINGS`); anyone else, a screen paired as
        itself included, is refused `403 permission_required`.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: The limit.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CashierDiscountLimit" }
    post:
      tags: ["Staff"]
      summary: Set how much a cashier may discount alone
      description: >-
        0 to 100. A discount above it needs a manager's approval on every till and every route that takes a
        discount; a paid sale a till took offline above it is recorded and flagged for review. Needs
        `EDIT_SETTINGS` (management), asked before the body is read, and audited with the old and new figures.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CashierDiscountLimit" }
      responses:
        "200":
          description: Saved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CashierDiscountLimit" }
        "400":
          description: "`discount_limit_invalid`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`permission_required`: the caller does not hold `EDIT_SETTINGS`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/couriers:
    get:
      tags: ["Rota & Delivery"]
      summary: The couriers this server offers and the venue's connection to each
      description: >-
        Each courier with its state: NOT_CONNECTED, VERIFYING (saved, not yet accepted), CONNECTED or REJECTED with the courier's
        own sentence, the address the courier should call with driver updates, and whether a signing key is held. Never carries a
        secret: no field of the answer can hold one (T-37.9). Needs MANAGE_INTEGRATIONS.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Every courier.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/CourierAccountView" } }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/couriers/{provider}:
    put:
      tags: ["Rota & Delivery"]
      summary: Save a venue's own courier account
      description: >-
        Keeps what was pasted, encrypted at rest (AES-GCM under the server's own key, bound to the business and courier), as
        VERIFYING: no delivery is booked until Test connection passes, and saving again clears an earlier verdict. The secrets are
        write-only: never returned, logged or exported. Refused 503 `courier_keys_cannot_be_stored` when the server has no
        encryption key, rather than stored in the clear. Needs MANAGE_INTEGRATIONS; audited (method, path, status — never the body).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [UBER_DIRECT] } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CourierConnect" }
      responses:
        "200":
          description: Saved, not yet verified.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CourierAccountView" }
        "400":
          description: "`invalid_courier_account`, with what to fix."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`permission_required`, or `courier_not_for_demo`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_courier`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: "`courier_keys_cannot_be_stored`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: ["Rota & Delivery"]
      summary: Disconnect a courier
      description: The keys are deleted, not hidden. A delivery already booked is no longer followed once its account is gone. Needs MANAGE_INTEGRATIONS; audited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [UBER_DIRECT] } }
      responses:
        "204":
          description: Disconnected.
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_courier` or `courier_account_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/couriers/{provider}/test:
    post:
      tags: ["Rota & Delivery"]
      summary: Test connection
      description: >-
        One sign-in the courier answers without booking anything, under the venue's own keys, and one read of the account's own
        delivery list to prove the customer ID. Accepted → CONNECTED; refused → REJECTED with the courier's sentence; not reached →
        unchanged, with `unreachable` saying so. Needs MANAGE_INTEGRATIONS; audited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [UBER_DIRECT] } }
      responses:
        "200":
          description: The account as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CourierTestResult" }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_courier`, or `courier_account_not_found` (save the details first)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/couriers/jobs:
    get:
      tags: ["Rota & Delivery"]
      summary: The courier jobs of the last day
      description: >-
        Where each delivery handed to a courier stands (booking, driver finding, on the way, delivered, cancelled), which ones
        failed and wait for a person (`unclear`: the last booking went unanswered and may exist at the courier; `mayBookAgain`),
        and what the courier charges the venue. Optionally for one of this business's locations. Never carries a guest's details.
        Needs MANAGE_INTEGRATIONS (never a kitchen screen's).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: locationId, in: query, required: false, schema: { type: string } }
      responses:
        "200":
          description: The jobs, newest first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CourierJobsResponse" }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`location_not_found` — the location is not this business's."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/couriers/jobs/{id}/retry:
    post:
      tags: ["Rota & Delivery"]
      summary: Book again
      description: >-
        A delivery whose booking failed and is held for a person goes back to booking, now. After a definite failure it is a new
        booking round, so a new idempotency key (`<job id>-<round>`); after an unanswered booking it resends the same key, and only
        within 30 minutes of that answer. Needs MANAGE_INTEGRATIONS; audited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "202":
          description: Queued.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CourierRetryAck" }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`courier_job_not_held` — it is booked, finished, being retried, or its order was cancelled; `courier_booking_unclear` — the last booking went unanswered over 30 minutes ago and may exist at the courier: check its dashboard."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/couriers/jobs/{id}/dismiss:
    post:
      tags: ["Rota & Delivery"]
      summary: Mark a cancel as handled
      description: >-
        A cancelled order's delivery that needs a person (the driver already had it, no courier account, the courier never
        answered the cancel, or the booking went unanswered and may exist) leaves the list of things needing attention once a
        person has checked the courier's dashboard. Changes nothing at the courier; an unanswered cancel is still asked again.
        Needs MANAGE_INTEGRATIONS; audited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Marked handled.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CourierDismissAck" }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`courier_job_not_flagged` — no cancel is waiting for a person on this delivery (or it is not this business's)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/payments:
    get:
      tags: ["Payments"]
      summary: The venue's own online payment accounts
      description: >-
        Yoco, PayFast and SnapScan, each with its state — NOT_CONNECTED, VERIFYING (saved, not yet accepted by
        the provider), CONNECTED, or REJECTED with the provider's own sentence. A guest is offered only a
        CONNECTED account, and pays into the venue's own account (T-2.1). Never carries a secret: no field of
        the answer can hold one. Needs MANAGE_INTEGRATIONS.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Every rail.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PaymentRailView" } }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/payments/{provider}:
    put:
      tags: ["Payments"]
      summary: Save a venue's own payment account
      description: >-
        Keeps what was pasted, encrypted at rest (AES-GCM under the server's own key), as VERIFYING: a new key is
        offered to no guest until Test connection passes. The secret is write-only — it is never returned, logged
        or exported. Refused 503 `payment_keys_cannot_be_stored` when the server has no encryption key, rather
        than stored in the clear. Needs MANAGE_INTEGRATIONS and the caller's current password (`currentPassword`;
        403 `reauth_required` otherwise, nothing saved); a saved change emails the business's owners who changed it and
        when, with no key in the email. Where the owner requires two-factor sign-in, a session that has not proved it is
        refused 403 `second_factor_required` before the password is judged (T-41.58), so an unproved session learns nothing
        of the password. Audited (method, path, status — never the body).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [YOCO, PAYFAST, SNAPSCAN] } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PaymentRailConnect" }
      responses:
        "200":
          description: Saved, not yet verified.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentRailView" }
        "400":
          description: "`invalid_payment_account`, with what to fix."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`permission_required`; `second_factor_required` — the business requires two-factor sign-in and this session has not typed its code (asked before the password); or `reauth_required` — the current password was missing or wrong."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_payment_provider`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`payment_account_in_use` — the same key, PayFast merchant or SnapCode is connected to another business; or `snapscan_not_offered` — SnapScan is not offered to venues (D-171) and takes no new key; what was saved before is kept."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503":
          description: "`payment_keys_cannot_be_stored`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/payments/{provider}/prefer:
    post:
      tags: ["Payments"]
      summary: Choose the card account guests pay through
      description: >-
        Where a venue has connected more than one card account (Yoco and PayFast), the one every new guest card
        checkout opens on: an order, a share of a bill, a booking's deposit. With none chosen, PayFast where it is
        connected, otherwise Yoco. A payment already taken settles and refunds on its own provider. The same proof as
        saving a key: 403 `second_factor_required` first where the business requires two-factor sign-in, then the
        changer's current password (403 `reauth_required`); the business's owners are emailed who changed it and
        when. Needs MANAGE_INTEGRATIONS; audited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [YOCO, PAYFAST, SNAPSCAN] } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PaymentRailPrefer" }
      responses:
        "200":
          description: Every rail as `GET /api/v1/settings/payments` answers it, the chosen one marked.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PaymentRailView" } }
        "403":
          description: "`permission_required`, `second_factor_required` or `reauth_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_payment_provider`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`payment_account_not_live` — the account is not connected and tested, so guests could not pay through it."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/payments/{provider}/enabled:
    post:
      tags: ["Payments"]
      summary: Switch a payment provider on or off for guests
      description: >-
        The switch at the top of a provider's card. Off, the business's guests are offered no new payment on it — an
        order's checkout, a share of a bill, a booking's deposit, a till's pay-by-link or tab hold — and the card checkout
        moves to the business's other connected card account, if any. The saved keys stay (never returned), so switching it
        on again offers the same account with nothing re-entered; a payment already taken on it still settles, is still
        verified when the provider calls, and still refunds. No password is asked; 403 `second_factor_required` where the
        business requires two-factor sign-in and the session has not proved it. Needs MANAGE_INTEGRATIONS; audited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [YOCO, PAYFAST, SNAPSCAN] } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PaymentRailSwitch" }
      responses:
        "200":
          description: Every rail as `GET /api/v1/settings/payments` answers it, each with its `enabled`.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PaymentRailView" } }
        "403":
          description: "`permission_required` or `second_factor_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`unknown_payment_provider`, or `payment_account_not_found` — nothing is saved for this provider, or it is not offered (SnapScan)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/settings/payments/{provider}/test:
    post:
      tags: ["Payments"]
      summary: Test connection
      description: >-
        One call the provider answers without moving money, under the venue's own key: Yoco lists the account's
        webhooks, deletes a stale registration of this venue's URL and registers
        `/api/v1/payments/yoco/webhook/{tenant}`, keeping the signing secret it gives (encrypted); PayFast is
        asked for today's transaction history; SnapScan for its payments list. Accepted → CONNECTED; refused →
        REJECTED with the provider's sentence; not reached → unchanged, with `unreachable` saying so. Needs
        MANAGE_INTEGRATIONS; audited.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: provider, in: path, required: true, schema: { type: string, enum: [YOCO, PAYFAST, SNAPSCAN] } }
      responses:
        "200":
          description: The account as it now stands.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PaymentRailTestResult" }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`payment_account_not_found` (nothing saved yet) or `unknown_payment_provider`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/client-errors:
    post:
      tags: ["Devices"]
      summary: Send the crashes a device kept
      description: >-
        A till, KDS or back office keeps up to five crashes on the device, scrubbed of
        personal details as they are kept, and sends them here once it is signed in and
        online. The server scrubs every field again and passes each to error reporting,
        named by the token's role and tenant only. At most ten reports and 128 KB a call;
        extra reports are ignored. Any signed-in role, a device included.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              maxItems: 10
              items:
                type: object
                required: [id, atMs, platform, surface, release, type, message, trace]
                properties:
                  id: { type: string }
                  atMs: { type: integer, format: int64, description: When it crashed, epoch milliseconds. }
                  platform: { type: string, example: android }
                  surface: { type: string, example: till }
                  release: { type: string, example: "1.0.0" }
                  type: { type: string, example: java.lang.IllegalStateException }
                  message: { type: string }
                  trace: { type: string }
      responses:
        "202":
          description: Taken; `accepted` is how many were passed on.
          content:
            application/json:
              schema:
                type: object
                properties:
                  accepted: { type: integer }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "413":
          description: "`client_errors_too_large`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/data/export:
    get:
      tags: ["System"]
      summary: Download everything the business holds
      description: |
        A ZIP with one CSV per table the tenant has rows in (every table with a
        tenant column, read from the database catalogue, so a table added later is
        included without anyone listing it), the tenant's own settings row, every
        full-size picture its rows name at `pictures/<key>` (the key a `*_key` column
        holds; thumbnails are not included), and `manifest.json` with the row count per
        table, the credential columns left out (password and PIN hashes, API and
        connection secrets), the number of pictures and `picturesMissing`: each picture
        the store could not give, which never fails the export. Needs EXPORT_DATA.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: The export.
          content:
            application/zip:
              schema: { type: string, format: binary }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/customers/{id}/export:
    get:
      tags: ["Marketing"]
      summary: Everything held about one guest (subject access)
      description: |
        For a guest's request under POPIA s23. The guest's row, every row that
        references them, and every row in a guest-facing table whose phone or email
        holds theirs (a booking records the number typed, not the customer). Table
        name → rows. Needs EXPORT_DATA.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The guest's data.
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  type: array
                  items: { type: object, additionalProperties: { type: string, nullable: true } }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`customer_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/data/subject-access:
    post:
      tags: ["Marketing"]
      summary: Everything held about a guest by their phone number or email (subject access)
      description: |
        For a guest's request under POPIA s23 when the business holds no customer record
        for them: a booking, a message, a tab or an order typed with only a number or an
        address. Give `phone` (written any way: `082 555 0148`, `+27 82 555 0148`) and/or
        `email` (any case). Answers table → rows for every place Ruva's erasure would clear
        for the same contact, plus a customer record the contact belongs to and everything
        linked to it. A business that holds nothing gets `{}`. It is a POST so the number or
        address is in the body, never in a URL or a log; the call is audited by method, path
        and status only. Needs EXPORT_DATA (never a cashier or a device).
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                phone: { type: string, nullable: true }
                email: { type: string, nullable: true }
      responses:
        "200":
          description: The guest's data.
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  type: array
                  items: { type: object, additionalProperties: { type: string, nullable: true } }
        "400":
          description: "`contact_required`, `invalid_phone` or `invalid_email`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`permission_required`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /api/v1/data/deletion:
    get:
      tags: ["System"]
      summary: Where a request to close the account stands
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: The status; `dueAt` is null when nothing is requested.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeletionStatusDto" }
        "403":
          description: "`permission_required` — needs MANAGE_LICENCE."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: ["System"]
      summary: Ask for the account to be closed
      description: |
        Everything the tenant holds is deleted once the cooling-off period
        (`coolingOffDays`, 30) has passed. Until then staff keep trading and the
        request can be cancelled. The business name must be typed back. Asking again
        keeps the first date. Needs MANAGE_LICENCE. Asking cancels the subscription
        first (the PayFast debit at PayFast, the Yoco link withdrawn); withdrawing the
        request leaves it cancelled, for Billing to resume. Ruva's own invoices to the
        business are kept after the purge (VAT records). `502 payfast_unconfirmed` or
        `409 change_in_progress`: the debit was not stopped, so nothing was requested.
        It may ask PayFast, so it spends the business's `billingWrite` bucket.
      security: [{ bearerAuth: [] }]
      x-rate-limit: "billingWrite: 10/min"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DeletionRequest" }
      responses:
        "200":
          description: Requested.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeletionStatusDto" }
        "400":
          description: "`confirmation_mismatch`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "403":
          description: "`permission_required` — needs MANAGE_LICENCE."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`change_in_progress` — another change to the subscription is with PayFast; nothing was requested."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "502":
          description: "`payfast_unconfirmed` — PayFast did not confirm the debit stopped; nothing was requested."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "429": { description: "More than the `billingWrite` bucket allows for this business in a minute; see `Retry-After`." }
  /api/v1/data/deletion/cancel:
    post:
      tags: ["System"]
      summary: Keep the account
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Cancelled.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeletionStatusDto" }
        "403":
          description: "`permission_required` — needs MANAGE_LICENCE."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "404":
          description: "`no_deletion_requested`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /customers/{id}/contact-history:
    get:
      tags: ["Marketing"]
      summary: What we have already sent this customer
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Campaign contacts, newest first.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/ContactHistoryEntry" } }
  # ─────────────────── Quotes & special orders (V28) ───────────────────
  /quotes:
    get:
      tags: ["Quotes & Special Orders"]
      summary: Quotes, newest first
      description: |
        `status` accepts `EXPIRED`, which is **not** a stored status — it is derived by
        comparing `validUntil` to now. Asking for it means "SENT and past its date", so
        such a quote also still appears under `?status=SENT`.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: locationId, in: query, schema: { type: string } }
        - { name: customerId, in: query, schema: { type: string } }
        - name: status
          in: query
          schema:
            type: string
            enum: [DRAFT, SENT, EXPIRED, ACCEPTED, DECLINED, CONVERTED, CANCELLED]
      responses:
        "200":
          description: Quotes with their lines.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Quote" } }
    post:
      tags: ["Quotes & Special Orders"]
      summary: Raise a quote
      description: |
        Creates a DRAFT with its lines. A line's `unitPriceCents` may be omitted, in
        which case it is resolved once through the ordinary layers at the quote's
        location (base → price list → active rules) and then **frozen** — honouring
        the offer later is the whole point of quoting.

        `productId` may be null, making the line free text ("Staff — 3 waiters, 5
        hours"). `description` is always required: the customer reads it, and products
        get renamed. A `variantId` without a `productId` is rejected.

        The quote reserves no stock, so five quotes for the last case of wine all
        succeed.

        **A quote cannot give a sale away.** A unit price that is not the catalogue's (a free-text line's price
        included), a line discount and a header discount each need a manager: the signed-in caller when they are
        one, else a live manager of this business named in `approverStaffId`. A discount is never negative and never
        above what it comes off. Refused with `quote_needs_manager`, `discount_negative`, `discount_above_gross` or
        `line_not_discountable` (a discount on a gift card, deposit or levy line, T-2.34).
        A line at the price a time rule (happy hour) gives now, when that is not the standing price, needs a manager
        the same way (T-2.56); the standing price is never a price of the author's own, happy hour or not.

        **A quote holds its price for at most 30 days** (T-2.56, D-112): `validUntil` may be no later than the end of
        the 30th South African day after today, else `quote_valid_too_long`; none given is that day.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QuoteCreateRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  reference: { type: string, example: "QT-20260804-000001" }
        "400":
          description: >-
            `no_lines`, `invalid_quantity`, `missing_description`, `invalid_discount`,
            `invalid_vat_type`, `variant_without_product`, `unknown_product`,
            `unknown_variant`, `variant_not_of_product`, `unknown_location`, `unknown_customer`, `quote_needs_manager`,
            `discount_negative`, `discount_above_gross`, `line_not_discountable` or `quote_valid_too_long`; `invalid_quantity` covers a quantity
            above 9 999 and `line_price_too_large` a unit price beyond R10 000 000 either way.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /quotes/open:
    get:
      tags: ["Quotes & Special Orders"]
      summary: Sent and unanswered, soonest to expire first
      description: |
        The follow-up list. Quotes with no expiry sort last — an open-ended standing
        price for a corporate account needs no chasing, so it should not sit above a
        quote that dies on Friday.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Quotes awaiting an answer.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/Quote" } }
  /quotes/{id}:
    get:
      tags: ["Quotes & Special Orders"]
      summary: One quote with its lines
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The quote.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Quote" }
        "404":
          description: "`quote_not_found` — including another tenant's quote."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /quotes/{id}/lines:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Replace every line and re-total
      description: |
        Wholesale replacement rather than per-line edits: a quote is negotiated as a
        document, and diffing an edited table into inserts/updates/deletes would add a
        way for the stored total to disagree with the lines that produced it.

        Allowed while DRAFT **or SENT** — revising a price and re-sending is the normal
        shape of a negotiation. Once ACCEPTED the figures are the agreement and this
        returns 409; a change then needs a fresh quote, which is the paper trail an
        argument later depends on.

        The quote as it will stand is judged like one being raised: a price that is not the catalogue's or any
        discount (the header discount it keeps included) needs a manager (`approverStaffId`).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QuoteLinesRequest" }
      responses:
        "200":
          description: Recomputed totals.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QuoteTotals" }
        "400":
          description: >-
            The same refusals as raising a quote: `no_lines`, `invalid_quantity`, `line_price_too_large`, `quote_needs_manager`,
            `discount_negative`, `discount_above_gross`, `unknown_product`, `unknown_variant` or `variant_not_of_product`.
            A line re-sent at the price the quote froze it at is not a price of the author's own while the quote's last
            judgement found none.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`quote_not_editable` — the quote is ACCEPTED, CONVERTED or CANCELLED."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /quotes/{id}/send:
    post:
      tags: ["Quotes & Special Orders"]
      summary: DRAFT → SENT
      description: |
        Refuses a quote whose `validUntil` has already passed (`valid_until_past`): the
        customer would receive an offer dead on arrival, and its derived status would
        read EXPIRED the instant it was sent.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The sent quote.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Quote" }
        "400":
          description: "`quote_empty` or `valid_until_past`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`quote_not_draft`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /quotes/{id}/accept:
    post:
      tags: ["Quotes & Special Orders"]
      summary: SENT → ACCEPTED
      description: |
        An expired quote is refused rather than silently honoured — re-dating the offer
        is a decision someone should take deliberately.

        **Who stood behind the yes is recorded** (T-2.56, audit `QUOTE_ACCEPTED`): a manager caller, or a
        live manager of this business named in the optional `approverStaffId`. Only such an acceptance,
        within the quote's 30 days, lets a repair job's own linked quote keep its accepted price past them
        at the job's handover; a cashier's acceptance records the yes and freezes nothing.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                approverStaffId: { type: string, nullable: true }
      responses:
        "200":
          description: The accepted quote.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Quote" }
        "409":
          description: "`quote_not_sent` or `quote_expired`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /quotes/{id}/decline:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Record a lost quote, with its reason
      description: |
        Allowed from DRAFT as well as SENT: a customer can say no to a verbal number
        before the document ever goes out, and losing that loses the win/loss rate the
        whole record exists to produce.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string, example: "Chose a cheaper venue" }
      responses:
        "200":
          description: The declined quote.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Quote" }
        "409":
          description: "`quote_not_open`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /quotes/{id}/cancel:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Withdraw a quote
      description: |
        Refused once CONVERTED: a sale sits behind it, and unpicking that is a void or
        refund on the order, not an edit here.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The withdrawn quote.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Quote" }
        "409":
          description: "`quote_converted` or `already_cancelled`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /quotes/{id}/convert:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Turn a quote into an OPEN order
      description: |
        Creates a sale at the quote's location, ready to settle by the ordinary till
        path (stock, VAT, loyalty, journal, receipt).

        **Prices are copied, never re-derived, while they hold** — `PriceResolver` is not
        consulted, and the quote's header discount rides onto the order so checkout
        apportions it and corrects output VAT exactly as the quote's own totals did. The
        number on the paper is the number charged, to the cent.

        **Past its date the offer has lapsed** (T-2.56, D-112). A quote's price holds to its
        `validUntil` and never past the 30th South African day after it was written (a quote
        stored with no date, or a later one, included). Converted after that, each catalogue
        line rings at today's price and the quote is judged as if written today: a free-text
        line's figure, a discount or a time rule's price then needs a manager behind this
        conversion (the approval given when it was written lapsed with it), else
        `quote_needs_manager`. The quote's own lines stay as written. An accepted quote is no
        exception here; only a repair job's handover of its own linked quote, accepted under a
        manager within the 30 days, keeps the accepted price (core `QuoteValidity.priceHolds`).
        A happy-hour price is a rule with a window, days or dates; an all-day, every-day,
        undated rule is the standing price and needs no manager.

        **Once only.** `converted_order_id` is set inside a `SELECT … FOR UPDATE` on the
        quote, so two clicks on a slow connection cannot produce two orders.

        SENT converts as well as ACCEPTED: a customer who walks in with a printout and
        pays has accepted it in the only way that matters. `acceptedAt` is backfilled so
        win/loss does not read the sale as an unanswered enquiry.

        **The quote is judged again.** One whose price or discount a manager approved when it was written converts
        for whoever rings it up while that approver is still a live manager. One nobody approved (written before
        this rule) converts only with a manager behind it: the signed-in caller, or `approverStaffId`. A quote with
        no price of its own and no discount converts as before.

        Free-text lines are anchored to a per-tenant system product
        (`product_type = COMMITMENT_LINE`, inactive, untracked) that never appears on a
        menu; the line's `name_snapshot` carries the agreed wording.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QuoteConvertRequest" }
      responses:
        "201":
          description: The order raised.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QuoteConverted" }
        "400":
          description: "`quote_empty`, `quote_needs_manager` (the sentence asks for a manager to ring it up), `discount_negative`, `discount_above_gross`, `invalid_quantity` or `line_price_too_large` (a line an order cannot hold), or `line_price_negative` (an allowance line with no manager behind the quote), or `line_not_discountable` (a stored line discount on a gift card, deposit or levy, T-2.34)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: >-
            `already_converted` (carries the existing order id) or `quote_not_convertible`. A lapsed
            quote is no longer refused with `quote_expired`: it converts at today's prices (T-2.56).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders:
    get:
      tags: ["Quotes & Special Orders"]
      summary: Special orders
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: locationId, in: query, schema: { type: string } }
        - { name: customerId, in: query, schema: { type: string } }
        - name: status
          in: query
          schema:
            type: string
            enum: [REQUESTED, ORDERED, READY, COLLECTED, CANCELLED]
      responses:
        "200":
          description: Orders with their money position.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/SpecialOrder" } }
    post:
      tags: ["Quotes & Special Orders"]
      summary: Request goods for a named customer
      description: |
        `customerId` is required — an order held for nobody in particular is just stock,
        and knowing who to ring is the feature. `productId` may be null: the commonest
        special order is for something not in the catalogue at all, which is usually why
        it is special.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SpecialOrderCreateRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  reference: { type: string, example: "SO-20260804-000001" }
        "400":
          description: >-
            `missing_description`, `invalid_quantity`, `line_price_negative`,
            `line_price_too_large`, `variant_without_product`, `unknown_location`,
            `unknown_customer`, `unknown_product`, `unknown_variant` or `unknown_supplier`.
            A quantity is 1–9 999 and a unit price, when given, from nothing to R10 000 000
            (core `SaleLine`, T-2.34).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/waiting:
    get:
      tags: ["Quotes & Special Orders"]
      summary: Uncollected goods, longest wait first
      description: |
        Everything READY, with `daysWaiting`. This is how floor space and tied-up money
        get recovered: goods bought for one person who never came back are invisible in
        ordinary stock reporting, because on the shelf they look like stock that simply
        is not selling.
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Orders on the collection shelf.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/SpecialOrder" } }
  /special-orders/{id}:
    get:
      tags: ["Quotes & Special Orders"]
      summary: One special order
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrder" }
        "404":
          description: "`special_order_not_found` — including another tenant's."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/{id}/price:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Price it, raising the sale that carries the deposit
      description: |
        The sale is created here rather than at request time because an order cannot be
        raised for a nameless, unpriced thing — and that is how most special orders
        start. Omit `unitPriceCents` for a catalogue item and it is priced at the
        order's location.

        **Re-pricing is allowed until money changes hands** — the customer has not
        committed and the supplier's cost may come back different. Once `paid_cents > 0`
        it returns `409 deposit_taken`: changing the price under a paid deposit would
        silently move the balance the customer agreed to. A re-price reuses the existing
        sale and rewrites its single line, so no duplicate line can appear.

        `depositPctBp` only *suggests* a figure back (rounded up to the cent, so the
        venue never loses a cent per function); nothing is collected here.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SpecialOrderPriceRequest" }
      responses:
        "200":
          description: Priced, with the sale id.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrderPriced" }
        "400":
          description: "`price_required`, `invalid_quantity`, `line_price_negative`, `line_price_too_large`, `price_below_catalogue` or `variant_without_product`. The one line is held to core `SaleLine` (T-2.34): a quantity of 1–9 999 and a unit price from nothing to R10 000 000, judged before anything is written; a catalogue item's typed price is never below its catalogue price here (money off is a discount, with the till's limits)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`deposit_taken` or `special_order_closed`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/{id}/deposit:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Take a deposit
      description: |
        Captures immediately against the order's sale, through the same function a layby
        instalment uses — a deposit and a layby instalment are the same money
        movement. So the tender counts towards the shift that took it, the day's Z-report
        balances, and V18 checkout credits it at collection.

        It is deliberately **not** a `deposit_cents` column: that would invent a second
        money system where cash sits in the drawer with no register aware of it and no
        accounting entry until collection, so a deposit taken in March would land in
        May's books.

        `invalid_method` (400) for any method but CASH, CARD, EFT or YOCO_CARD, before a sale is raised or a payment row is written (T-21.14).

        Overpaying the balance is rejected.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SpecialOrderDepositRequest" }
      responses:
        "200":
          description: Money position after the deposit.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrderMoney" }
        "400":
          description: "`invalid_amount` or `overpays_balance`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`not_priced` — there is no sale to attach the money to yet."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/{id}/ordered:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Placed with a supplier
      description: Links the purchase order raised, so receiving stock can find the customers waiting on it.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SpecialOrderOrderedRequest" }
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrder" }
        "400":
          description: "`unknown_purchase_order` or `unknown_supplier`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`invalid_transition`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/{id}/ready:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Arrived and set aside
      description: |
        Deliberately moves **no stock**: the receipt that brought the goods in already
        did, and moving them again would double-count. What this marks is that they are
        spoken for.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrder" }
        "409":
          description: "`invalid_transition`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/{id}/notify:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Record that the customer was told
      description: |
        Separate from `/ready` because the two genuinely come apart — goods can sit on
        the shelf for a day before anyone gets hold of the customer. There is no
        NOTIFIED status: whether the customer has been told is a fact about a message,
        not a stage of the goods, and modelling it as a status would make "arrived but
        unreachable by phone" — the state that actually needs chasing — unrepresentable.
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: The order.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrder" }
        "409":
          description: "`nothing_to_notify`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/{id}/collect:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Collect and settle the balance
      description: |
        Closes the sale through the ordinary checkout path, so stock depletes, VAT is
        recomputed, loyalty earns, the journal posts and a receipt exists — none of
        which a bespoke "mark collected" would do.

        The deposit needs no mention: it is already CAPTURED on the sale, so the legs
        passed here only have to cover **what is left**. The sale still totals the full
        price.

        `invalid_method` (400) for any method but CASH, CARD, EFT or YOCO_CARD, before a sale is raised or a payment row is written (T-21.14).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SpecialOrderCollectRequest" }
      responses:
        "200":
          description: Collected.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrderCollected" }
        "409":
          description: "`invalid_transition` or `not_priced`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /special-orders/{id}/cancel:
    post:
      tags: ["Quotes & Special Orders"]
      summary: Cancel before arrival
      description: |
        Reachable from REQUESTED and ORDERED only. **Not from READY**: the goods are in
        the building, bought for one named person, so the resolution is either that they
        collect or that the venue refunds the deposit and takes the item into stock.
        Both are real operations; silently cancelling would leave physical stock nobody
        owns and a deposit nobody has returned.

        Any deposit already taken is reported back as `depositToRefundCents` rather than
        dropped. The sale is voided (`VOIDED`) so it can never be settled later, but the captured
        payment rows **stay** — the money did change hands, and deleting the evidence
        would leave the register short with no explanation. A sale already paid or refunded is
        never cancelled: `409 sale_not_open`, with what to do instead (return the goods through Refunds).
      security: [{ bearerAuth: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string }
      responses:
        "200":
          description: Cancelled, with any deposit still owed back.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SpecialOrderCancelled" }
        "409":
          description: "`invalid_transition` — notably READY, where the goods are already in."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /price-lists:
    get:
      tags: [Pricing]
      summary: Price lists with their assigned locations
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Lists.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PriceList" } }
    post:
      tags: [Pricing]
      summary: Create a price list (Manager)
      description: |
        A named set of prices assigned to locations, so a coffee can cost more at the
        airport than in Observatory.

        `upliftBp` moves everything the list does not itemise (1500 = +15%, and it is
        signed, so a staff or wholesale list is the same mechanism). Explicit prices
        for the exceptions go in via `/items`. Supporting only items would mean
        hundreds of rows to express one decision; supporting only an uplift could not
        express a flat-price exception.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PriceListUpsertRequest" }
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "400":
          description: "`name_required`, `invalid_uplift` or `invalid_window`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "409":
          description: "`name_in_use` — a duplicate name is invisible to a manager assigning one."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /price-lists/preview:
    get:
      tags: [Pricing]
      summary: What a product costs at a location, and why (Manager)
      description: |
        Returns each layer separately — `basePriceCents` → `listPriceCents` →
        `priceCents` — plus which list and which rule produced them. A price that
        cannot be explained is a support call.

        Omit `locationId` to see base prices with only location-agnostic rules, which
        is what a menu preview should show.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: query, name: productId, required: true, schema: { type: string } }
        - { in: query, name: locationId, schema: { type: string } }
        - { in: query, name: variantId, schema: { type: string } }
      responses:
        "200":
          description: The resolved price, layer by layer.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PricePreview" }
        "400":
          description: "`missing_productId`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /price-lists/unassign:
    post:
      tags: [Pricing]
      summary: Send locations back to base prices (Manager)
      description: |
        Not nested under a list id: a manager unassigning a location does not
        necessarily know which list it is on, and making them look it up first invites
        unassigning from the wrong one.
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AssignRequest" }
      responses:
        "200":
          description: How many locations reverted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  locationsReverted: { type: integer }
  /price-lists/{id}:
    post:
      tags: [Pricing]
      summary: Update a price list (Manager)
      description: "Keep-on-absent: omitted fields keep their current value."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PriceListUpsertRequest" }
      responses:
        "200":
          description: The updated list.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PriceList" }
        "404":
          description: "`price_list_not_found` — including another tenant's."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    delete:
      tags: [Pricing]
      summary: Delete a price list (Manager)
      description: |
        Assigned locations are unassigned first and revert to base prices — the only
        safe reading of "the list is gone", and it avoids leaving a location pointing
        at a row that no longer exists.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "204":
          description: Deleted. Items cascade; locations revert to base.
        "404":
          description: "`price_list_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /price-lists/{id}/items:
    get:
      tags: [Pricing]
      summary: The explicit prices on a list
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        "200":
          description: Items, with each product's base price for comparison.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PriceListItem" } }
        "404":
          description: "`price_list_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
    post:
      tags: [Pricing]
      summary: Set explicit prices (Manager)
      description: |
        Upsert per SKU, not replace-all: a price list is edited a few rows at a time
        from a long product list, and a replace-all would silently drop everything a
        partial UI did not send.

        A `variantId` of null prices the product for every variant — the variant delta
        still applies on top, so "tees are R150 here" with Large at +R20 rings R170. A
        variant-specific item prices that SKU absolutely and wins outright.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/PriceListItemsRequest" }
      responses:
        "200":
          description: The list's items after the upsert.
          content:
            application/json:
              schema: { type: array, items: { $ref: "#/components/schemas/PriceListItem" } }
        "400":
          description: "`empty_items`, `invalid_price`, `duplicate_item`, `unknown_product` or `unknown_variant`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /price-lists/{id}/items/{itemId}:
    delete:
      tags: [Pricing]
      summary: Drop a SKU back to the list's uplift (Manager)
      description: "Removing an item does not remove the price — the SKU falls back to `upliftBp`."
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
        - { in: path, name: itemId, required: true, schema: { type: string } }
      responses:
        "204":
          description: Removed.
        "404":
          description: "`price_list_not_found` or `item_not_found`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /price-lists/{id}/assign:
    post:
      tags: [Pricing]
      summary: Point locations at this list (Manager)
      description: |
        A location has at most one list — the assignment is a single column on the
        location, so reassigning moves it off whatever list it was on with no special
        case, and "two lists claim this location" is a state the schema cannot express.
      security: [{ bearerAuth: [] }]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AssignRequest" }
      responses:
        "200":
          description: The list, with its locations.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PriceList" }
        "400":
          description: "`no_locations` or `unknown_location`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }

  /api/v1/whats-new/{version}:
    get:
      tags: [Training]
      summary: The release notes for one version
      description: |
        What changed in `version`, from `docs/CHANGELOG.md` (T-15.7) — the same notes `/whats-new` shows. A till asks
        for the version it runs and shows them once after an update. Any signed-in person or device.
      parameters:
        - { name: version, in: path, required: true, schema: { type: string, example: "1.0.0" }, description: "MAJOR.MINOR.PATCH." }
      responses:
        "200":
          description: The release.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReleaseNotes" }
        "400": { description: "`invalid_version` — not MAJOR.MINOR.PATCH." }
        "404": { description: "`no_release_notes` — the changelog has no entry for that version." }
  /api/v1/training/courses:
    get:
      tags: [Training]
      summary: The training academy for a till
      description: |
        Every course, lesson, step and check from `docs/TRAINING.md` (T-15.5) — the questions and their options,
        never which is right; the server grades. `pagePath` is the lesson's page on `/train`, with its screenshots.
        Any signed-in person or device.
      responses:
        "200":
          description: The academy.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TrainingCatalogue" }
  /api/v1/training/lessons/{slug}/attempt:
    post:
      tags: [Training]
      summary: Record one staff member's check
      description: |
        Graded by the server against the academy and recorded against `staffId`, who must be an active staff member
        of the caller's business — a till names whoever signed in to it with their PIN, as a clock-in does. All
        questions right passes the lesson; the first pass stands, so a later miss never un-passes it.
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [staffId, answers]
              properties:
                staffId: { type: string }
                answers: { type: array, items: { type: integer }, description: "The chosen option's index, per question." }
      responses:
        "200":
          description: The grade.
          content:
            application/json:
              schema:
                type: object
                required: [passed, correct, of, wrong]
                properties:
                  passed: { type: boolean }
                  correct: { type: integer }
                  of: { type: integer }
                  wrong: { type: array, items: { type: integer }, description: "0-based questions answered wrongly." }
        "400": { description: "`invalid_answers` (a missing answer or an option that is not there) or `staff_not_found`." }
        "404": { description: "`lesson_not_found`." }
  /api/v1/training/team:
    get:
      tags: [Training]
      summary: The team's training progress
      description: Every active staff member and the lessons each has passed (T-15.5). Managers.
      responses:
        "200":
          description: The team.
          content:
            application/json:
              schema:
                type: object
                required: [staff]
                properties:
                  staff:
                    type: array
                    items:
                      type: object
                      required: [staffId, staffName, role, passed]
                      properties:
                        staffId: { type: string }
                        staffName: { type: string }
                        role: { type: string }
                        passed: { type: array, items: { type: string }, description: "Lesson slugs passed." }
                        lastAttemptAt: { type: integer, format: int64, nullable: true }
        "403": { description: "Not a manager." }
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        JWT access token issued by `POST /api/v1/auth/login` or `POST /api/v1/auth/refresh`. Send as
        `Authorization: Bearer <accessToken>`. Manager-gated endpoints additionally require the token's
        `role` claim to be `ADMIN`, `SUPER_ADMIN`, or `MANAGER`.
  parameters:
    QrOrderKey:
      name: X-Ruva-Order-Key
      in: header
      required: false
      description: >-
        The key that opens a guest's order or round (T-2.12): the `receiptToken` (an order, and the round that opened it)
        or `roundToken` (a round added to a table's tab) the first answer to `POST /api/v1/qr/orders` carried. A header,
        never a query string, which Cloud Run and the load balancer log whole. A missing, wrong or another order's key
        answers exactly as an unknown order (404). On `POST /api/v1/qr/orders` it is the key the device minted for the
        order it is placing: stored as that order's, and required to have a replay of its `clientOrderId` answered.
      schema: { type: string }
    QrBillCode:
      name: X-Ruva-Bill-Code
      in: header
      required: false
      description: >-
        A table's bill's share code (T-2.50): eight characters, shown `XXXX-XXXX` to the phone that opened the bill with
        the order's key (`shareCode`), typed in any case with or without the dash. A header, never a query string (a `code`
        in the query is not read); a link carries it in the fragment. Lives while the bill is open and three hours after it
        closes. A wrong code answers exactly as an unknown order and is counted, per bill and per address.
      schema: { type: string }
    PathId:
      name: id
      in: path
      required: true
      schema: { type: string }
    PictureSize:
      name: size
      in: query
      required: false
      description: "`thumb` answers the small copy kept beside every picture (long edge 320 px, T-41.82), for a picture drawn small; absent, the picture itself."
      schema: { type: string, enum: [thumb] }
    Period:
      name: period
      in: query
      description: "Named period window, resolved in Africa/Johannesburg time: `week` is today and the six days before (seven days), `month` and `year` run from their first day; each ends at midnight tonight. Defaults to `today`. Any other value is refused with 400 `invalid_period`, naming the value and these (T-15.1) — it is checked even when `from`/`until` win."
      schema: { type: string, enum: [today, yesterday, week, month, year], default: today }
    ExportFormat:
      name: format
      in: query
      required: false
      description: "`csv` or `pdf` downloads the report's table (money in rands, two decimals); omit for JSON. Any other value is refused (`invalid_format`)."
      schema: { type: string, enum: [csv, pdf] }
    CsvFormat:
      name: format
      in: query
      required: false
      description: "`csv` downloads the report as a CSV attachment; omit for JSON."
      schema: { type: string, enum: [csv] }
    LocationId:
      name: locationId
      in: query
      required: false
      description: "Narrow the report to a single location. Omit for tenant-wide (BO-F18)."
      schema: { type: string }
    RangeFrom:
      name: from
      in: query
      required: false
      description: "Epoch-millis window start. With `until` it overrides `period` (BO-F18). Not a number → 400 `invalid_from`; given without `until`, or not before it → 400 `invalid_range`."
      schema: { type: integer, format: int64 }
    RangeUntil:
      name: until
      in: query
      required: false
      description: "Epoch-millis window end (exclusive). With `from` it overrides `period` (BO-F18). Not a number → 400 `invalid_until`."
      schema: { type: integer, format: int64 }
  responses:
    BadRequest:
      description: Validation error.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    Unauthorized:
      description: Missing, malformed, or expired bearer token (`error:"missing_or_invalid_token"`).
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    Forbidden:
      description: Authenticated, but the caller's role does not permit this action (`error:"manager_required"` or `"role_escalation_forbidden"`).
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    NotFound:
      description: Resource not found.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    Conflict:
      description: State conflict (e.g. duplicate id, business-rule violation).
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    TooManyRequests:
      description: Rate limit exceeded for this endpoint's bucket.
  schemas:
    AccountingStatus:
      type: object
      properties:
        provider: { type: string, nullable: true, description: "The package's name as the server keeps it; null when none is connected." }
        connected: { type: boolean }
        needsReconnect: { type: boolean, description: "The package's sign-in has lapsed: only someone who may manage integrations can reconnect it." }
        lastBatchAt: { type: integer, format: int64, nullable: true }
        lastPostingFailed: { type: boolean, description: "The last posting failed; the reason is the connection's, for whoever manages it." }
        pending: { type: integer, format: int64 }
        posted: { type: integer, format: int64 }
        failed: { type: integer, format: int64 }
    AccountingHealth:
      type: object
      required: [status, provider]
      properties:
        status: { type: string, enum: [CONNECTED, REAUTHORISE, THROTTLED, UNAVAILABLE, NOT_CONNECTED] }
        provider: { type: string }
        organisation: { type: string, nullable: true, description: "The company the credentials reach, when the package names it." }
        message: { type: string, nullable: true }
    ItemSyncResult:
      type: object
      required: [provider]
      properties:
        provider: { type: string }
        created: { type: integer }
        updated: { type: integer }
        failed: { type: integer }
        inFlight: { type: integer, description: "Sent with no answer yet: re-sent under the same key, never duplicated." }
        remaining: { type: integer }
        unchanged: { type: integer, description: "Already in the package exactly as they are here: no call spent." }
        throttledUntil: { type: integer, format: int64, nullable: true }
        notConfigured: { type: boolean }
        blocked: { type: array, items: { type: string } }
    KioskFunnelKiosk:
      type: object
      description: One kiosk's counts, or every kiosk's added (deviceId empty).
      properties:
        deviceId: { type: string }
        name: { type: string }
        started: { type: integer, format: int64 }
        basketOpened: { type: integer, format: int64 }
        reviewed: { type: integer, format: int64 }
        placed: { type: integer, format: int64 }
        leftBrowsing: { type: integer, format: int64 }
        leftBasket: { type: integer, format: int64 }
        leftReview: { type: integer, format: int64 }
        placedPerStartBp: { type: integer, format: int64, nullable: true }
    LocationTrackingRow:
      type: object
      required: [locationId, name]
      properties:
        locationId: { type: string }
        name: { type: string }
        trackingCategory: { type: string, nullable: true, description: "Xero's tracking category name; null for the others." }
        trackingOption: { type: string, nullable: true, description: "Null when the location is not mapped." }
    LocationTrackingMap:
      type: object
      required: [provider, trackingNoun, needsCategory]
      properties:
        provider: { type: string }
        trackingNoun: { type: string }
        needsCategory: { type: boolean }
        locations: { type: array, items: { $ref: "#/components/schemas/LocationTrackingRow" } }
    LocationTrackingRequest:
      type: object
      properties:
        trackingCategory: { type: string, nullable: true }
        trackingOption: { type: string, nullable: true, description: "Null or blank removes the mapping." }
    CategoryAccountRow:
      type: object
      required: [categoryId, name]
      properties:
        categoryId: { type: string }
        name: { type: string }
        providerCode: { type: string, nullable: true, description: "The package's account reference; null keeps the category on the sales account." }
    CategoryAccountRequest:
      type: object
      properties:
        providerCode: { type: string, nullable: true }
    ReconcileDay:
      type: object
      required: [day, entries, entryCents, sent, sentCents, waiting, failed, notSent, notSentCents, differenceCents]
      properties:
        day: { type: string, format: date }
        entries: { type: integer }
        entryCents: { type: integer, format: int64 }
        sent: { type: integer, description: "In the package: posted on their own, or inside a daily summary that posted." }
        sentCents: { type: integer, format: int64 }
        waiting: { type: integer }
        failed: { type: integer }
        notSent: { type: integer }
        notSentCents: { type: integer, format: int64 }
        differenceCents: { type: integer, format: int64, description: "What Ruva raised less what is in the package; 0 before the push-from date." }
        references: { type: array, items: { type: string } }
        documentsSent: { type: integer }
        documentsWaiting: { type: integer }
        documentsFailed: { type: integer }
        beforeSyncFrom: { type: boolean }
        locked: { type: boolean }
        canRepost: { type: boolean }
        heldClosedPeriod: { type: integer, description: "Inventory journals of the day more than 35 days back that have not posted: never sent again or re-posted, so not counted as failed or waiting and no reason for Re-post. Look for each in the accounting system and post by hand what is missing." }
        lastError: { type: string, nullable: true }
    ReconcileDaysView:
      type: object
      required: [provider, from, to]
      properties:
        provider: { type: string }
        from: { type: string, format: date }
        to: { type: string, format: date }
        lockedThrough: { type: string, format: date, nullable: true }
        lockUnknown: { type: string, nullable: true }
        days: { type: array, items: { $ref: "#/components/schemas/ReconcileDay" } }
        late: { type: array, description: "Stock movements Ruva will not journal by itself, oldest first: a person who posted one by hand says so (POST /accounting/late/{day}/{class}/posted-by-hand).", items: { $ref: "#/components/schemas/LateDay" } }
        closed: { type: array, description: "The late rows of the range a person posted by hand, with who and when.", items: { $ref: "#/components/schemas/HandPostedDay" } }
    LateDay:
      type: object
      required: [day, movementClass, movementCount, valueCents]
      properties:
        day: { type: string, format: date }
        movementClass: { type: string, enum: [COGS, WRITE_OFF, ADJUSTMENT] }
        movementCount: { type: integer }
        valueCents: { type: integer, format: int64, description: "Signed as the journal would be: negative is value out of stock." }
        refused: { type: string, nullable: true, description: "Why Ruva will not post it by itself (`closed_period`, `closed_period_sent`, `older_revision`, `xids_went_backwards`, `claimed`); null when the next sync will." }
        handSentence: { type: string, nullable: true, description: "What to look for and post by hand, in the accounting system's own words; null when there is nothing to post by hand." }
        awaitingAnswer: { type: boolean }
        canClose: { type: boolean, description: "A person may say they posted it by hand: a closed period's row only, and not while its send waits for an answer." }
        heldJournal: { type: string, nullable: true, description: "`closed_period_sent`: the key of the journal sent and not confirmed." }
        heldCents: { type: integer, format: int64, nullable: true, description: "`closed_period_sent`: that journal's own signed amount, as sent." }
        ifFoundPostCents: { type: integer, format: int64, nullable: true, description: "`closed_period_sent`: what is still to post when that journal IS in the package." }
    PostedByHandRequest:
      type: object
      properties:
        part: { type: string, enum: [ALL, BEYOND_HELD], default: ALL, description: "All of the row's figure, or only what lay beyond the held journal, which the person found in the package." }
        expectedCents: { type: integer, format: int64, nullable: true, description: "The figure the person read for that part: refused `changed_meanwhile` when the list's is another now." }
    HandPostedDay:
      type: object
      required: [day, movementClass, netCents, movementCount, postedAt]
      properties:
        day: { type: string, format: date }
        movementClass: { type: string, enum: [COGS, WRITE_OFF, ADJUSTMENT] }
        netCents: { type: integer, format: int64, description: "The signed figure the late list showed when it was closed." }
        revision: { type: integer, description: "Its place among the day's journals of its class (the narration it was posted with)." }
        listedAs: { type: string, nullable: true, enum: [closed_period, closed_period_sent] }
        postedPart: { type: string, enum: [ALL, BEYOND_HELD] }
        postedCents: { type: integer, format: int64, description: "What the person says they posted, as the list showed it." }
        heldJournal: { type: string, nullable: true }
        heldCents: { type: integer, format: int64, nullable: true }
        beyondCents: { type: integer, format: int64 }
        movementCount: { type: integer }
        postedAt: { type: integer, format: int64, description: "When it was closed (epoch milliseconds)." }
        postedBy: { type: string, nullable: true, description: "The name of the person who closed it; null once that person is gone." }
    RepostResult:
      type: object
      required: [day, requeued]
      properties:
        day: { type: string, format: date }
        requeued: { type: integer }
        heldClosedPeriod: { type: integer, description: "Inventory journals dated more than 35 days back, left failed: post them in the accounting system by hand." }
        posted: { type: integer }
        failed: { type: integer }
        inFlight: { type: integer }
        lockUnknown: { type: string, nullable: true }
    PayoutImportSummary:
      type: object
      required: [id, provider, source, lineCount, matchedCount, exceptionCount, grossCents, feeCents, feeVatCents, netCents, createdAt]
      properties:
        id: { type: string }
        provider: { type: string, enum: [PAYFAST, YOCO, SNAPSCAN, ZAPPER] }
        source: { type: string, enum: [API, CSV] }
        periodFrom: { type: integer, format: int64, nullable: true }
        periodTo: { type: integer, format: int64, nullable: true }
        lineCount: { type: integer }
        matchedCount: { type: integer }
        exceptionCount: { type: integer, description: "Rows not matched that are payments: UNMATCHED, AMOUNT_MISMATCH, DUPLICATE." }
        grossCents: { type: integer, format: int64 }
        feeCents: { type: integer, format: int64 }
        feeVatCents: { type: integer, format: int64 }
        netCents: { type: integer, format: int64 }
        journalEntryId: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
    PayoutLineView:
      type: object
      required: [occurredAt, type, grossCents, feeCents, feeVatCents, netCents, outcome]
      properties:
        occurredAt: { type: integer, format: int64 }
        type: { type: string }
        providerRef: { type: string, nullable: true }
        grossCents: { type: integer, format: int64 }
        feeCents: { type: integer, format: int64 }
        feeVatCents: { type: integer, format: int64 }
        netCents: { type: integer, format: int64 }
        outcome: { type: string, enum: [MATCHED, UNMATCHED, AMOUNT_MISMATCH, DUPLICATE, NOT_A_PAYMENT] }
        paymentId: { type: string, nullable: true }
    UnsettledPayment:
      type: object
      required: [paymentId, method, grossCents, capturedAt]
      properties:
        paymentId: { type: string }
        method: { type: string }
        grossCents: { type: integer, format: int64 }
        capturedAt: { type: integer, format: int64 }
    PayoutImportDetail:
      type: object
      required: [summary, lines, notSettled]
      properties:
        summary: { $ref: "#/components/schemas/PayoutImportSummary" }
        lines: { type: array, items: { $ref: "#/components/schemas/PayoutLineView" } }
        notSettled: { type: array, items: { $ref: "#/components/schemas/UnsettledPayment" } }
        alreadyImported: { type: boolean, default: false }
    PayFastPayoutFetch:
      type: object
      required: [from, to]
      properties:
        from: { type: string, format: date }
        to: { type: string, format: date }
    ReleaseNotes:
      type: object
      required: [version, date, summary, sections]
      properties:
        version: { type: string, example: "1.0.0" }
        date: { type: string, format: date }
        summary: { type: string, description: "One sentence on what the release is about." }
        sections:
          type: array
          description: "New, Improved and Fixed, in that order, each present only when it has points. Points may carry **bold**."
          items:
            type: object
            required: [title, items]
            properties:
              title: { type: string, enum: [New, Improved, Fixed] }
              items: { type: array, items: { type: string } }
    TrainingCatalogue:
      type: object
      required: [courses]
      properties:
        courses:
          type: array
          items:
            type: object
            required: [slug, title, roles, pitch, lessons]
            properties:
              slug: { type: string }
              title: { type: string }
              roles: { type: array, items: { type: string }, description: "StaffRole names this course is for." }
              pitch: { type: string }
              lessons:
                type: array
                items:
                  type: object
                  required: [slug, title, goal, steps, questions, pagePath]
                  properties:
                    slug: { type: string }
                    title: { type: string }
                    goal: { type: string }
                    steps: { type: array, items: { type: string } }
                    questions:
                      type: array
                      items:
                        type: object
                        required: [text, options]
                        properties:
                          text: { type: string }
                          options: { type: array, items: { type: string } }
                    pagePath: { type: string }
    OpenCheckDto:
      type: object
      properties:
        id: { type: string }
        kind: { type: string, enum: [ORDER, TAB] }
        label: { type: string }
        number: { type: string, nullable: true }
        totalCents: { type: integer, format: int64 }
        openedAt: { type: integer, format: int64 }
      required: [id, kind, label, totalCents, openedAt]
    DayShiftDto:
      type: object
      properties:
        shiftId: { type: string }
        staffId: { type: string }
        staffName: { type: string }
        clockInAt: { type: integer, format: int64 }
        clockOutAt: { type: integer, format: int64, nullable: true }
        register: { type: boolean, description: "The shift held a float — a register to count and Z." }
        countedCashCents: { type: integer, format: int64, nullable: true }
        cashVarianceCents: { type: integer, format: int64, nullable: true }
        closingFloatCents: { type: integer, format: int64, nullable: true }
      required: [shiftId, staffId, staffName, clockInAt, register]
    DayCloseDto:
      type: object
      properties:
        locationId: { type: string }
        tradingDate: { type: string }
        closedAt: { type: integer, format: int64 }
        closedByStaffId: { type: string, nullable: true }
        registers: { type: integer }
        grossCents: { type: integer, format: int64 }
        countedCashCents: { type: integer, format: int64 }
        cashVarianceCents: { type: integer, format: int64 }
      required: [locationId, tradingDate, closedAt, registers, grossCents, countedCashCents, cashVarianceCents]
    CloseOfDayStatusDto:
      type: object
      properties:
        locationId: { type: string }
        tradingDate: { type: string }
        openChecks: { type: array, items: { $ref: "#/components/schemas/OpenCheckDto" } }
        onShift: { type: array, items: { $ref: "#/components/schemas/DayShiftDto" } }
        awaitingZ: { type: array, items: { $ref: "#/components/schemas/DayShiftDto" } }
        zDone: { type: array, items: { $ref: "#/components/schemas/DayShiftDto" } }
        grossCents: { type: integer, format: int64 }
        countedCashCents: { type: integer, format: int64 }
        cashVarianceCents: { type: integer, format: int64 }
        cashRefundsCents: { type: integer, format: int64, default: 0, description: "T-41.39 - the cash the day's refunds handed back out of this location's drawers." }
        blockers: { type: array, items: { type: string }, description: "What is still in the way, in words; empty when the day can close." }
        tillsHoldingSales: { type: array, items: { type: string }, description: "The tills still holding sales of the day, by name; the day does not close until they reach the server or are signed out (T-35.5)." }
        notes: { type: array, items: { type: string }, description: "Beside the close, never in its way: a till seen today that has not checked in for ten minutes and may hold sales (T-35.5)." }
        closed: { $ref: "#/components/schemas/DayCloseDto" }
      required: [locationId, tradingDate, openChecks, onShift, awaitingZ, zDone, grossCents, countedCashCents, cashVarianceCents, blockers]
    DayTakingDto:
      type: object
      properties:
        method: { type: string, description: "`payments.method`: YOCO_CARD, PAYFAST, CASH, COUNTER_CARD, COUNTER_EFT…" }
        label: { type: string }
        cents: { type: integer, format: int64, description: Takings by this method, tips included. }
        atCounter: { type: boolean }
      required: [method, label, cents, atCounter]
    DaySummaryDto:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
        tradingDate: { type: string }
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        salesCents: { type: integer, format: int64 }
        netSalesCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        tipsCents: { type: integer, format: int64 }
        refundsCents: { type: integer, format: int64 }
        ordersCount: { type: integer }
        takings: { type: array, items: { $ref: "#/components/schemas/DayTakingDto" } }
        notSettledCount: { type: integer, description: "Orders of the last 90 days under Orders' Not settled: paid and not closed, paid twice, or a refund to check." }
        notSettledNotClosed: { type: integer, description: "Of notSettledCount, paid orders that did not close." }
        notSettledPaidTwice: { type: integer, description: "Of notSettledCount, orders a guest paid twice (a refund to make)." }
        counterOrders: { type: array, items: { $ref: "#/components/schemas/CounterOrder" } }
        counterCash: { $ref: "#/components/schemas/CounterCash" }
        mayBank: { type: boolean }
        salesDefinition: { type: string }
      required: [locationId, locationName, tradingDate, periodStart, periodEnd, salesCents, netSalesCents, vatCents, tipsCents, refundsCents, ordersCount, takings, notSettledCount, counterOrders, counterCash, mayBank, salesDefinition]
    CloseDayRequest:
      type: object
      properties:
        locationId: { type: string }
        tradingDate: { type: string, nullable: true }
      required: [locationId]
    SendDayReportRequest:
      type: object
      properties:
        locationId: { type: string }
        tradingDate: { type: string, nullable: true }
        channel: { type: string, enum: [EMAIL, WHATSAPP] }
        to: { type: string, description: "An email address, or a WhatsApp number in E.164 (+27…)." }
      required: [locationId, channel, to]
    SendDayReportResponse:
      type: object
      properties:
        sent: { type: boolean }
        status: { type: string }
        message: { type: string }
      required: [sent, status, message]
    ErrorBody:
      type: object
      properties:
        error: { type: string, description: "Machine-readable error code, e.g. `validation_error`, `manager_required`, `order_not_open`." }
        message: { type: string, nullable: true }
        correlationId: { type: string, nullable: true }
      required: [error]

    HealthStatus:
      type: object
      properties:
        status: { type: string }
        version: { type: string }
        database: { type: string }
      required: [status, version, database]

    # ── Auth ──
    LoginRequest:
      type: object
      properties:
        email: { type: string }
        password: { type: string }
        tenantId: { type: string, nullable: true, description: "Optional, and normally omitted — the server resolves the business from the credentials. Send it only after a 409 TenantChoiceResponse says the email signs in to more than one." }
        device: { $ref: "#/components/schemas/DeviceHello" }
        surface: { type: string, nullable: true, description: "Where the person is signing in to, by surface name; the back office sends `admin`. A role that holds no back-office permission (a chef, server, bartender, host or cashier) is then refused 403 `back_office_not_for_role`, with a sentence that says where to go, and no session is started. Omit it everywhere else." }
        atDevice: { allOf: [{ $ref: "#/components/schemas/DeviceHello" }], description: "The device a person signs in AT without signing it in (T-22.3): the back office's own sign-in, a person's email at a till already signed in. Read only by registered-devices-only (its id and secret); a manager's sign-in registers it, its session never moves. `device` wins when both are sent." }
      required: [email, password]
    TenantChoiceResponse:
      type: object
      description: >
        409 on POST /auth/login: the credentials are right but they identify accounts in several
        businesses (users is unique on (tenant_id, email), not on email), so the answer is a choice
        rather than a token. Retry with the chosen tenantId.
      properties:
        error: { type: string, enum: [tenant_required] }
        message: { type: string }
        tenants: { type: array, items: { $ref: "#/components/schemas/TenantOption" } }
      required: [error, message, tenants]
    TenantOption:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
      required: [id, name]
    LoginResponse:
      type: object
      properties:
        accessToken: { type: string }
        refreshToken: { type: string }
        expiresInSeconds: { type: integer, format: int64 }
        user: { $ref: "#/components/schemas/UserDto" }
        pinnedSurface: { type: string, nullable: true, description: "The surface this device is pinned to (T-2.4), or null for a shared device or a sign-in that sent no device." }
        device: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        secondFactor: { type: string, nullable: true, description: "ENROL or VERIFY while the business requires a second factor of this person and the session has not proved it (T-37.4)." }
        deviceSecret: { type: string, nullable: true, description: "The device's registration secret, answered once: when this manager's sign-in (any second factor proved) registered the device it named, or the one it signed in at — a new secret every time, so the one the device held before stops proving it, and the sessions of people it proved AT the device end (T-22.3, round 3 P2-1, fix 4 P3-A). Only to a client whose hello says `keepsSecret`, and only where a location of the business has \"registered devices only\" on; absent otherwise. Keep it beside the device id and send it in the device's hello." }
      required: [accessToken, refreshToken, expiresInSeconds, user]
    RefreshRequest:
      type: object
      properties:
        refreshToken: { type: string }
      required: [refreshToken]
    UserDto:
      type: object
      properties:
        id: { type: string }
        tenantId: { type: string }
        email: { type: string }
        role: { type: string }
        locale: { type: string }
        displayName:
          type: string
          maxLength: 120
          description: "D-212: the person's own name, as typed at sign-up, on an invite or in Your sign-in. Absent when they have none, and for a screen."
      required: [id, tenantId, email, role, locale]
    OwnNameRequest:
      type: object
      description: "D-212: the caller's new name. Trimmed; a blank one clears it; at most 120 characters."
      properties:
        displayName: { type: string }
      required: [displayName]
    DeviceHello:
      type: object
      description: What a device says about itself when it is signed in (T-2.4). Its id is minted once on the device.
      properties:
        id: { type: string }
        name: { type: string }
        platform: { type: string, description: "android, ios, desktop or web." }
        appVersion: { type: string, nullable: true }
        secret: { type: string, nullable: true, description: "The registration secret this device was handed (T-22.3). Where a location lets people sign in only on its own devices, a person who is not a manager is on a registered device only with its id AND this secret; the id alone proves nothing." }
        keepsSecret: { type: boolean, default: false, description: "This client keeps a registration secret it is handed (T-22.3 fix 4). A secret is minted and answered only to a client that says so; where every switch of the business is off, none is minted at all." }
      required: [id, name, platform]
    LanHubSecret:
      type: object
      required: [tenantId, secret, version]
      properties:
        tenantId: { type: string }
        secret: { type: string, description: "64 hex characters. Keep on the till; never on a kitchen or customer display." }
        version: { type: integer, description: "Bumped when every business's key is rotated at once." }
    HubNameRequest:
      type: object
      required: [address]
      properties:
        address: { type: string, description: "The private LAN address the till serves on now." }
        csr: { type: string, nullable: true, description: "PKCS#10 request, base64 of the DER, made with a key that stays on the till." }
    HubNameAnswer:
      type: object
      required: [host, url, address, status]
      properties:
        host: { type: string }
        url: { type: string }
        address: { type: string }
        status: { type: string, enum: [NEEDS_CSR, PENDING, ISSUED, FAILED, REVOKED] }
        chainPem: { type: string, nullable: true, description: "The leaf then its issuers, PEM. Never a private key." }
        notAfter: { type: integer, format: int64, nullable: true, description: "Epoch milliseconds." }
    HubNameView:
      type: object
      required: [deviceId, host, url, notAfter]
      properties:
        deviceId: { type: string }
        host: { type: string }
        url: { type: string }
        notAfter: { type: integer, format: int64 }
    HubNamesList:
      type: object
      properties:
        names:
          type: array
          items: { $ref: "#/components/schemas/HubNameView" }
    DeviceRegistrationDto:
      type: object
      description: One registered device (device_registrations, T-2.4).
      properties:
        id: { type: string }
        name: { type: string }
        platform: { type: string }
        appVersion: { type: string, nullable: true }
        locationId: { type: string, nullable: true }
        pinnedSurface: { type: string, nullable: true, enum: [pos, admin, kds, kiosk, customer-display, null] }
        stationId: { type: string, nullable: true, description: "Prep station a kitchen display shows; its printer is the station's." }
        lastSeenAt: { type: integer, format: int64 }
        signedOutAt: { type: integer, format: int64, nullable: true, description: "When a manager signed it out remotely." }
        current: { type: boolean }
        paired: { type: boolean, description: "A screen that signs in as itself with a pairing code (T-18.7)." }
        pairingCodeExpiresAt: { type: integer, format: int64, nullable: true, description: "When its unused pairing code stops working, while there is one." }
        pinLockClearedAt: { type: integer, format: int64, nullable: true, description: "When a manager last let its PIN pad take PINs again; null if never." }
        screenLock: { type: string, enum: [locked, pinned, open], nullable: true, description: "How firmly the screen says it is held on its surface: locked (nobody can leave from the screen), pinned (screen pinning or Guided Access, which a person can end) or open (nothing holds it); null if it has not said, or cannot lock itself." }
        registered: { type: boolean, default: false, description: "Whether the venue registered this device (T-22.3): a manager signed in on it, or it was paired from Devices. Absent when false, and always where every switch of the business is off." }
        signedInAt: { type: integer, default: 0, description: "How many people are signed in AT this device now (T-22.3 round 3, P2-1: `LoginRequest.atDevice` proved by its secret); each session ends when the device is signed out or removed, and when a manager signing in there rotates its secret. Only in the list; absent when 0." }
        sellsAsTill: { type: boolean, default: false, description: "Whether this device is selling now, so a till plan counts it as a till (T-23.9: its check-in says it shows the till, or it rang a sale today). Only in the list; it refuses nothing. Absent when false." }
        secret: { type: string, nullable: true, description: "Only on GET /devices/this, once: the secret of a device the venue registered with none yet, handed to its manager's session (T-22.3)." }
        holderName: { type: string, nullable: true, description: "Who is signed in ON this device now: the person's own name, else their sign-in address (T-43.11), so a manager registering it sees whom they vouch for. Only in the list; absent when nobody is." }
        holderRole: { type: string, nullable: true, description: "That person's role (a StaffRole). Only in the list; absent with holderName." }
        managerSignedIn: { type: boolean, default: false, description: "Whether a manager other than the caller is signed in on or at this device now; unregistering never ends a manager's sign-in (T-43.11). Only in the list; absent when false." }
      required: [id, name, platform, lastSeenAt, current]
    DeviceCreateRequest:
      type: object
      properties:
        name: { type: string }
        surface: { type: string, enum: [kds, kiosk] }
        locationId: { type: string }
        stationId: { type: string, nullable: true, description: "The prep station a kitchen screen shows." }
      required: [name, surface, locationId]
    KitchenScreenAllowance:
      type: object
      description: A business's kitchen screens against its plan (T-3.8).
      properties:
        planKey: { type: string, nullable: true, description: "The QR plan's key (starter, pro, group, till-addon), or null when the business has none." }
        limit: { type: integer, nullable: true, description: "Kitchen screens the business may have in use; null for no limit." }
        inUse: { type: integer, description: "Kitchen screens in use: set to the kitchen display and not signed out." }
      required: [inUse]
    DevicePairingCodeDto:
      type: object
      description: A screen and its one-time code, shown once.
      properties:
        device: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        code: { type: string, description: "Eight letters and digits shown as two groups of four, e.g. K7QF-M2XP." }
        expiresAt: { type: integer, format: int64 }
      required: [device, code, expiresAt]
    TwoFactorStatus:
      type: object
      properties:
        applies: { type: boolean, description: "The caller's role holds pay rates, refunds or exports." }
        required: { type: boolean, description: "The owner requires the factor of such roles." }
        enrolled: { type: boolean }
        proven: { type: boolean, description: "THIS session holds a code now (a session a device registered, for five minutes after it was typed)." }
        recoveryCodesLeft: { type: integer }
        provenOnce: { type: boolean, default: false, description: "THIS session has presented a code, though it may have lapsed since: the sign-in is not owed again." }
      required: [applies, required, enrolled, proven]
    TwoFactorEnrolment:
      type: object
      properties:
        secret: { type: string, description: "The key, base32, shown once." }
        otpauthUri: { type: string, description: "The otpauth:// link an authenticator app reads." }
      required: [secret, otpauthUri]
    TwoFactorCode:
      type: object
      description: Exactly one of the two.
      properties:
        code: { type: string, description: "Six digits from the authenticator." }
        recoveryCode: { type: string, description: "One of the ten recovery codes; works once." }
        device: { allOf: [{ $ref: "#/components/schemas/DeviceHello" }], description: "On verify: the device the code is typed on. A manager's proof registers it (T-22.3) and answers its secret once." }
    TwoFactorEnrolRequest:
      type: object
      properties:
        password: { type: string, description: "The account's password, asked again." }
      required: [password]
    TwoFactorConfirmRequest:
      type: object
      properties:
        code: { type: string, description: "Six digits from the new authenticator." }
        password: { type: string, description: "The account's password, asked again." }
        device: { allOf: [{ $ref: "#/components/schemas/DeviceHello" }], description: "The device the code is typed on. A manager's proof registers it (T-22.3) and answers its secret once." }
      required: [code, password]
    TwoFactorRenewRequest:
      type: object
      properties:
        password: { type: string, description: "The account's password, asked again." }
        code: { type: string, description: "Six digits the authenticator shows now; a recovery code is refused." }
      required: [password, code]
    TwoFactorRecoveryCodes:
      type: object
      properties:
        recoveryCodes: { type: array, items: { type: string }, description: "Ten codes, shown once and never again." }
        deviceSecret: { type: string, nullable: true, description: "The named device's registration secret, when this proof registered it (T-22.3); answered once." }
      required: [recoveryCodes]
    TwoFactorProof:
      type: object
      properties:
        recoveryCodesLeft: { type: integer }
        deviceSecret: { type: string, nullable: true, description: "The named device's registration secret, when this proof registered it (T-22.3); answered once." }
      required: [recoveryCodesLeft]
    TillSecondFactorRequest:
      type: object
      properties:
        staffId: { type: string, description: The person the till's PIN pad switched to }
        code: { type: string, description: Six digits from the authenticator }
        recoveryCode: { type: string }
      required: [staffId]
    TillCodeForgetRequest:
      type: object
      properties:
        reason: { type: string, enum: [switch, sign_out, idle], description: Why the till drops it; any other word is kept as `other` }
        staffId: { type: string, maxLength: 64, description: "The person whose PIN-pad code is dropped (the one a switch leaves); the account's own code goes whatever is named; absent drops every code of the session" }
        starts: { type: string, maxLength: 64, description: "Who is at the PIN pad now, on a switch. When it is the till's own account, on the account's own token, the server notes its own clock as the start of the account's shift (read only by the lapsed-licence check on a new sale); anyone else, or a seat's token, changes nothing" }
    TillSecondFactorProof:
      type: object
      properties:
        staffId: { type: string }
        expiresAt: { type: integer, format: int64, description: "Epoch milliseconds; five minutes after the code, unless the one act it opens spends it first" }
        recoveryCodesLeft: { type: integer }
      required: [staffId, expiresAt, recoveryCodesLeft]
    TwoFactorSetting:
      type: object
      properties:
        required: { type: boolean }
        code: { type: string, description: "The owner's own current code, asked when turning it off." }
        recoveryCode: { type: string }
      required: [required]
    TwoFactorPerson:
      type: object
      properties:
        userId: { type: string }
        email: { type: string }
        role: { type: string }
        enrolled: { type: boolean }
      required: [userId, email, role, enrolled]
    TwoFactorOverview:
      type: object
      properties:
        required: { type: boolean }
        people: { type: array, items: { $ref: "#/components/schemas/TwoFactorPerson" } }
      required: [required, people]
    ForgotPasswordRequest:
      type: object
      properties:
        email: { type: string }
      required: [email]
    ResetLinkCheck:
      type: object
      properties:
        token: { type: string, description: "The token from the emailed link." }
      required: [token]
    ResetPasswordRequest:
      type: object
      properties:
        token: { type: string, description: "The token from the emailed link." }
        password: { type: string, minLength: 10, maxLength: 128 }
      required: [token, password]
    PasswordResetAnswer:
      type: object
      properties:
        message: { type: string, description: "One sentence to show as it is." }
      required: [message]
    DevicePairRequest:
      type: object
      properties:
        code: { type: string }
        device: { $ref: "#/components/schemas/DeviceHello" }
      required: [code]
    DevicePairStartRequest:
      type: object
      properties:
        surface: { type: string, enum: [kds, kiosk] }
      required: [surface]
    DevicePairStartDto:
      type: object
      description: What an unpaired screen is told. No business data.
      properties:
        claimToken: { type: string, description: "Public, in the QR. 256 bits, single use." }
        code: { type: string, description: "Shown under the QR, e.g. K7QF-M2XP." }
        secret: { type: string, description: "The screen's alone: sent only to the poll." }
        surface: { type: string }
        expiresAt: { type: integer, format: int64 }
        pollEveryMs: { type: integer, format: int64 }
      required: [claimToken, code, secret, surface, expiresAt, pollEveryMs]
    DevicePairPollRequest:
      type: object
      properties:
        secret: { type: string }
        device: { $ref: "#/components/schemas/DeviceHello" }
        confirm: { type: boolean, default: false, description: "Join: collect the sign-in of a claimed screen." }
        reject: { type: boolean, default: false, description: "Not mine: remove what the claim made and wait again." }
      required: [secret]
    DevicePairWaitingDto:
      type: object
      properties:
        state: { type: string, enum: [waiting, claimed] }
        expiresAt: { type: integer, format: int64 }
        businessName: { type: string, nullable: true, description: "Only when claimed." }
        locationName: { type: string, nullable: true, description: "Only when claimed." }
      required: [state, expiresAt]
    DevicePairClaimRequest:
      type: object
      description: Exactly one of `claimToken` and `code`.
      properties:
        claimToken: { type: string, nullable: true }
        code: { type: string, nullable: true }
        name: { type: string }
        locationId: { type: string }
        stationId: { type: string, nullable: true }
        anotherNetworkConfirmed: { type: boolean, default: false, description: "True only once the manager answered yes to adding a screen that started from another network than this claim (the 409 `screen_on_another_network` question)." }
      required: [name, locationId]
    DevicePairClaimedDto:
      type: object
      properties:
        device: { $ref: "#/components/schemas/DeviceRegistrationDto" }
        surface: { type: string }
        sameNetwork: { type: boolean, description: "False when the screen started its pairing from another network than this claim, which the manager confirmed with `anotherNetworkConfirmed`." }
      required: [device, surface, sameNetwork]
    DeviceUpdateRequest:
      type: object
      properties:
        name: { type: string, nullable: true }
        locationId: { type: string, nullable: true, description: "Empty string clears it." }
        stationId: { type: string, nullable: true, description: "Empty string clears it." }
    DevicePinRequest:
      type: object
      properties:
        surface: { type: string, nullable: true, enum: [pos, admin, kds, kiosk, customer-display, null] }
    DeviceRegisteredRequest:
      type: object
      properties:
        registered: { type: boolean }
      required: [registered]
    DeviceUnpinRequest:
      type: object
      properties:
        pin: { type: string }
      required: [pin]
    OwnPinRequest:
      type: object
      properties:
        password: { type: string, description: "The person's own password, typed again." }
        pin: { type: string, description: "4-8 digits." }
      required: [password, pin]
    OwnPasswordRequest:
      type: object
      properties:
        currentPassword: { type: string, writeOnly: true, description: "The password the person signs in with now. Never stored or logged." }
        newPassword: { type: string, writeOnly: true, description: "The new password: sign-up's rule (10 to 128 characters, not the email address)." }
      required: [currentPassword, newPassword]
    OwnPasswordChanged:
      type: object
      properties:
        otherSessionsEnded: { type: integer, description: "How many of the person's other signed-in sessions were signed out." }
        noticeSent: { type: boolean, description: "Whether the email saying the password was changed was taken by the email service." }
      required: [otherSessionsEnded, noticeSent]
    OwnPinState:
      type: object
      properties:
        hasPin: { type: boolean }
        canSet: { type: boolean, description: "False for an account on no staff list here: there is no PIN to set." }
      required: [hasPin, canSet]
    ManagerPinCheck:
      type: object
      properties:
        pin: { type: string }
        kind: { type: string, enum: [DISCOUNT, OPEN_PRICE, VOID, COMP] }
        orderId: { type: string }
        amountCents: { type: integer, format: int64 }
        lineId: { type: string, nullable: true, description: "The line a VOID or COMP (or a line's discount) is for; null for the whole order or a line not yet written." }
      required: [pin, kind, orderId, amountCents]
    ManagerPinCheckWithoutPin:
      type: object
      properties:
        kind: { type: string, enum: [DISCOUNT, OPEN_PRICE, VOID, COMP] }
        orderId: { type: string }
        amountCents: { type: integer, format: int64 }
        lineId: { type: string, nullable: true }
        productId: { type: string, nullable: true }
        quantity: { type: integer, nullable: true }
      required: [kind, orderId, amountCents]
    PhoneApprovalOpened:
      type: object
      properties:
        requestId: { type: string }
        expiresAt: { type: integer, format: int64, description: "Epoch milliseconds." }
      required: [requestId, expiresAt]
    PhoneApprovalWaitingList:
      type: object
      properties:
        requests:
          type: array
          items:
            type: object
            properties:
              requestId: { type: string }
              kind: { type: string, enum: [DISCOUNT, OPEN_PRICE, VOID, COMP] }
              orderNumber: { type: string }
              tableLabel: { type: string, nullable: true }
              amountCents: { type: integer, format: int64 }
              askedAt: { type: integer, format: int64 }
              expiresAt: { type: integer, format: int64 }
              sentence: { type: string, description: "What to show, built by the server from the bill's own rows and the catalogue: the thing, the item, the order and the amount." }
              item:
                type: object
                nullable: true
                description: The item the request touches as the server read it (null for the whole bill); never the asking till's words.
                properties:
                  name: { type: string, description: "The product's catalogue name." }
                  quantity: { type: integer }
                  lineValueCents: { type: integer, format: int64, nullable: true, description: "The line's own value on the bill; null for a line not yet written." }
                  catalogueUnitCents: { type: integer, format: int64, nullable: true, description: "The catalogue's price for one, beside a typed price or for a line not yet written." }
                required: [name, quantity]
            required: [requestId, kind, orderNumber, amountCents, askedAt, expiresAt, sentence]
      required: [requests]
    PhoneApprovalDecision:
      type: object
      properties:
        approve: { type: boolean }
      required: [approve]
    PhoneApprovalAnswer:
      type: object
      properties:
        status: { type: string, enum: [WAITING, APPROVED, DECLINED, CLAIMED, CANCELLED, EXPIRED] }
        approval: { $ref: "#/components/schemas/ManagerApproval" }
        words: { type: string }
      required: [status, words]
    ManagerApproval:
      type: object
      properties:
        approverStaffId: { type: string }
        approverName: { type: string }
        approval: { type: string, description: "Send with the write it approves; the server keeps only its hash." }
        kind: { type: string, enum: [DISCOUNT, OPEN_PRICE, VOID, COMP] }
        orderId: { type: string }
        amountCents: { type: integer, format: int64 }
        expiresAt: { type: integer, format: int64, description: "Epoch milliseconds." }
        lineId: { type: string, nullable: true, description: "The line a VOID or COMP (or a line's discount) is for; null for the whole order or a line not yet written." }
      required: [approverStaffId, approverName, approval, kind, orderId, amountCents, expiresAt]
    SessionDto:
      type: object
      description: One signed-in device (V82).
      properties:
        id: { type: string, description: "Session id; the access token's `sid` claim." }
        lastRefreshedAt: { type: integer, format: int64, description: "Epoch ms of the session's latest token." }
        device: { type: string, nullable: true, description: "User agent the session last refreshed from." }
        current: { type: boolean, description: "True for the session the calling token belongs to." }
      required: [id, lastRefreshedAt, current]
    EntitlementsDto:
      type: object
      description: |
        What a tenant is licensed to run (V40/V72). Also carried on the access token as the `prd` claim.
      properties:
        products:
          type: array
          items: { type: string, enum: [RESTAURANT, RETAIL, QR_ORDERING] }
          description: "The products this tenant holds. QR_ORDERING is sold bundled with either till product or standalone."
        validUntil: { type: string, nullable: true, description: "ISO date (YYYY-MM-DD) the licence runs to; null = perpetual." }
        licenceCode: { type: string, nullable: true, description: "The key that was redeemed, for support conversations." }
        subscription: { type: string, nullable: true, enum: [NONE, RUNNING, CANCELLED], description: "What stands behind validUntil: a plan paid in Billing (RUNNING), one the owner cancelled (CANCELLED), or none — a term Ruva set or a licence key (NONE). Absent: not known (an older server)." }
      required: [products]

    # ── Catalogue ──
    CategoryDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        courseType: { type: string }
        colorHex: { type: string }
        sortOrder: { type: integer }
        active: { type: boolean }
        defaultStationId: { type: string, nullable: true, description: "Default KDS prep station id for this category (V12); null = unassigned (legacy course_type fallback)." }
        ageRestrictedYears: { type: integer, nullable: true, description: "T-37.1 - the age a sale of anything in this category needs checked (18 for alcohol); null = none." }
        tobacco: { type: boolean, default: false, description: "T-37.1 - tobacco is sold at a till with an age check and never on a phone, a kiosk or the online store." }
        afterHours: { type: boolean, default: false, description: "T-41.51 (V306) - guests keep ordering from it after the kitchen closes (drinks at the bar): outside the location's kitchen hours a guest order of only such items is taken; anything else is refused 409 kitchen_closed." }
        dayparts: { type: array, items: { $ref: "#/components/schemas/Daypart" }, description: "The times of day it is served (T-25.7), every location's; empty = all day." }
      required: [id, name, courseType, colorHex, sortOrder, active]
    CategoryUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        name: { type: string }
        courseType: { type: string, default: OTHER }
        colorHex: { type: string, default: "#00BCD4" }
        sortOrder: { type: integer, default: 0 }
        active: { type: boolean, default: true }
        defaultStationId: { type: string, nullable: true, description: "Default prep station id for products in this category (V12); empty/null clears it. Must be a live station of this tenant (else 400 unknown_station)." }
        ageRestrictedYears: { type: integer, nullable: true, description: "T-37.1 - the age to check for this category (18 for alcohol); null clears it." }
        tobacco: { type: boolean, nullable: true, description: "T-37.1 - mark the category as tobacco (an age of 18 is implied); null leaves it as it is." }
        afterHours: { type: boolean, nullable: true, description: "T-41.51 - keep taking guests' orders after the kitchen closes; null leaves it as it is (off for a new category). Audited by the plugin." }
        dayparts: { type: array, nullable: true, items: { $ref: "#/components/schemas/Daypart" }, description: "The times of day it is served (T-25.7): absent leaves them as they are, an empty list clears them (served all day), otherwise the list replaces them. A window that ends before it starts is 400 invalid_daypart; one naming another business's location is 404 location_not_found." }
      required: [name]
    Daypart:
      type: object
      description: "One time of day a category is served (T-25.7). Minutes since local midnight, in the location's own time zone; `startMinute` is the first minute served and `endMinute` the first minute not served (1440 = midnight), always start < end — a service past midnight is two windows."
      properties:
        id: { type: string, description: "Blank on write mints one." }
        locationId: { type: string, nullable: true, description: "null = every location of the business; otherwise this location only (must be the business's own, else 404 location_not_found)." }
        days: { type: string, default: MTWRFSU, description: "Weekday letters, Monday first (M T W R F S U); at least one." }
        startMinute: { type: integer, minimum: 0, maximum: 1439 }
        endMinute: { type: integer, minimum: 1, maximum: 1440 }
      required: [startMinute, endMinute]
    DishCardDto:
      type: object
      required: [productId, name]
      description: A dish as the kitchen reads it from a ticket (T-36.11). There is no cost or margin field, for any role.
      properties:
        productId: { type: string }
        name: { type: string }
        prepNotes: { type: string, nullable: true }
        photoUrl: { type: string, nullable: true, description: "The dish's photo (the one on the product); fetched as bytes." }
        recipeName: { type: string, nullable: true }
        portions: { type: integer, nullable: true, description: "What the recipe makes, when it makes more than one." }
        recipe: { type: array, items: { $ref: "#/components/schemas/DishRecipeLineDto" } }
        partial: { type: boolean, default: false, description: "True when a venue's hub answered: the notes only, with no recipe or photo." }
    DishRecipeLineDto:
      type: object
      required: [ingredient, quantity]
      properties:
        ingredient: { type: string }
        quantity: { type: string, description: "As the cook reads it, e.g. `800 g`." }
        subRecipe: { type: boolean, default: false, description: "The ingredient is itself made here." }
    PrepStationDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        sortOrder: { type: integer }
        active: { type: boolean }
        printerHost: { type: string, nullable: true }
        printerPort: { type: integer, nullable: true }
        targetSeconds: { type: integer, nullable: true }
        printMode: { type: string, enum: [EVERY_TICKET, IF_SCREEN_MISSES, SCREEN_ONLY], description: "T-5.6 — what the station's printer is for." }
        fallbackSeconds: { type: integer, minimum: 10, maximum: 600, nullable: true, description: "Under IF_SCREEN_MISSES, how long a ticket waits for a kitchen screen before it prints; null = 60." }
        kind: { type: string, enum: [PREP, BAR, EXPO, PASS], default: PREP, description: "T-36.4 — what the station is for. PREP and BAR are where dishes are routed; EXPO and PASS look across their whole location and are never a dish's destination. A screen set to one shows every ticket at its location." }
        locationId: { type: string, nullable: true, description: "T-36.4 — the one location the station exists at; null = every location." }
        twinGroup: { type: string, nullable: true, maxLength: 40, description: "T-36.17 — the group of twin stations it belongs to (PREP and BAR only). A dish routed to a station goes to whichever active twin at the fire's location has the fewest open items. Compared ignoring case and extra spaces; null = none." }
        startLimit: { type: integer, minimum: 1, maximum: 50, nullable: true, description: "T-36.17 — the start queue: how many tickets are in progress at once. The board shows the oldest that many (rush first) and marks the rest as waiting, last, in order; nothing is held. null = off." }
        shortLabel: { type: string, nullable: true, maxLength: 8, description: "T-36.26 — what heads the station's column on a kitchen screen's Expo list; null = the name's first word." }
        redirectTo: { type: string, nullable: true, description: "T-36.10 — set while the station is closed: the id of the station it sends its new and open tickets to; null = open. Set by PUT /kitchen/stations/{id}/redirect. A station others send their work to cannot be switched off (409 `station_is_redirect_target`)." }
        hasScreen: { type: boolean, nullable: true, description: "T-36.10, on GET /kitchen/stations only — whether a kitchen screen is known to show it (one set to it, or one that showed its ticket in the last 12 hours)." }
      required: [id, name, sortOrder, active]
    PrepStationUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        name: { type: string }
        sortOrder: { type: integer, default: 0 }
        active: { type: boolean, default: true }
        printMode: { type: string, enum: [EVERY_TICKET, IF_SCREEN_MISSES, SCREEN_ONLY], description: "T-5.6 — what the station's printer is for; omitted keeps it (and fallbackSeconds)." }
        fallbackSeconds: { type: integer, minimum: 10, maximum: 600, nullable: true, description: "Under IF_SCREEN_MISSES, how long a ticket waits for a kitchen screen before it prints; null = 60." }
        kind: { type: string, enum: [PREP, BAR, EXPO, PASS], description: "T-36.4 — omitted keeps BOTH the station's kind and its location. A kind that is sent names the place too: `locationId` null then means every location. `400 invalid_station_kind` for another value; `409 station_has_routes` when making a station an EXPO or PASS while a category or dish is still sent to it." }
        locationId: { type: string, nullable: true, description: "T-36.4 — the location the station exists at (one of this business's: `400 unknown_location`); null = every location. Read only when `kind` is sent." }
        twinGroup: { type: string, nullable: true, maxLength: 40, description: "T-36.17 — omitted keeps the group; an empty string clears it; an EXPO or PASS holds none. `400 invalid_twin_group` when longer than 40 characters once trimmed." }
        startLimit: { type: integer, minimum: 0, maximum: 50, nullable: true, description: "T-36.17 — omitted keeps the start queue; 0 turns it off; 1 to 50 sets it. `400 invalid_start_limit` for another value." }
        shortLabel: { type: string, nullable: true, maxLength: 8, description: "T-36.26 — omitted keeps it; an empty string clears it (the name's first word is used). `400 invalid_short_label` when longer than 8 characters once trimmed." }
      required: [name]
    ProductDto:
      type: object
      properties:
        id: { type: string }
        categoryId: { type: string }
        name: { type: string }
        description: "{ type: string, nullable: true }"
        emoji: { type: string, nullable: true }
        imageUrl: { type: string, nullable: true }
        sku: { type: string, nullable: true }
        barcode: { type: string, nullable: true }
        courseType: { type: string }
        productType: { type: string }
        priceCents: { type: integer, format: int64 }
        costCents: { type: integer, format: int64, description: "What it costs the venue. Absent for a caller without VIEW_COST (a server, cashier, bartender, host or screen; T-1.27 review)." }
        vatType: { type: string }
        trackStock: { type: boolean }
        active: { type: boolean }
        sortOrder: { type: integer }
        allergens: { type: array, items: { type: string }, default: [], description: "Allergen names (products.allergens_json), surfaced on the QR menu + KDS." }
        dietaryTags: { type: array, items: { type: string }, default: [], description: "What the dish suits, as the venue marked it (T-6.4): VEGETARIAN, VEGAN, HALAAL, GLUTEN_FREE, NUT_FREE, DAIRY_FREE." }
        prepStationId: { type: string, nullable: true, description: "This dish's own prep station (V250, T-36.2): its ticket goes there whatever its category's station is. Null = the category's station applies." }
        alsoStationIds: { type: array, items: { type: string }, description: "The other stations this dish is also sent to (V254, T-36.3), in the order named: one ticket item to each, each bumped on its own, the dish priced once. Empty = one station only." }
        prepNotes: { type: string, nullable: true, description: "What the kitchen reads about this dish from its ticket (V259, T-36.11), up to 1000 characters. Null = none written." }
        brand: { type: string, nullable: true, description: "Retail metadata (V18, server-only)." }
        supplierId: { type: string, nullable: true, description: "Primary supplier (V18) — feeds PO-from-low-stock grouping." }
        stockUnit: { type: string, nullable: true, enum: [each, g, ml], description: "The unit stock is COUNTED in (V36). Base units only, so on-hand stays an exact integer. Null = undeclared: counted as items until a recipe measures it." }
      required: [id, categoryId, name, courseType, productType, priceCents, vatType, trackStock, active, sortOrder]
    ProductUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        categoryId: { type: string }
        name: { type: string }
        description: "{ type: string, nullable: true }"
        emoji: { type: string, nullable: true, description: "The dish's emoji (T-39.24), trimmed, at most 16 characters (else 400 invalid_emoji). Keep-on-absent on UPDATE; send a blank string to clear it. A guest's menu draws it on a no-photo dish only where the location's `showDishEmoji` is on." }
        imageUrl: { type: string, nullable: true, description: "Keep-on-absent on UPDATE. An https link to a picture (T-41.56) is fetched once from the public web and stored as the dish's photo, exactly as POST /catalogue/products/{id}/photo; the row then holds the photo's own address and the link is not kept. 400 picture_unreachable (We couldn't fetch that picture. Upload it instead, or check the link opens in a browser.) when it cannot be fetched, or redirects to an address that is not public; 400 invalid_image or image_too_large in the upload's words; nothing is written." }
        sku: { type: string, nullable: true }
        barcode: { type: string, nullable: true }
        courseType: { type: string, default: MAIN }
        productType: { type: string, default: ITEM }
        priceCents: { type: integer, format: int64 }
        costCents: { type: integer, format: int64, nullable: true, description: "What the dish costs to make (T-39.24). Stored only for a caller who may read costs (VIEW_COST): what any other role sends is ignored and the stored cost stays (0 on a new dish), and that role's reads carry no `costCents` at all. Keep-on-absent on UPDATE: omitting it keeps the stored cost, never zeroes it. Negative is 400 invalid_cost." }
        vatType: { type: string, default: STANDARD, enum: [STANDARD, ZERO, EXEMPT], description: "The VAT treatment, any case; another value is 400 invalid_vat_type (T-39.24)." }
        trackStock: { type: boolean, default: false }
        active: { type: boolean, default: true }
        sortOrder: { type: integer, nullable: true, description: "Keep-on-absent for updates; inserts default to 0." }
        allergens: { type: array, items: { type: string }, nullable: true, description: "Structured allergen names. Keep-on-absent (null) on UPDATE preserves the stored list; inserts default to empty." }
        dietaryTags: { type: array, items: { type: string }, nullable: true, description: "What the dish suits (T-6.4): VEGETARIAN, VEGAN, HALAAL, GLUTEN_FREE, NUT_FREE, DAIRY_FREE, any case, hyphen or space. Keep-on-absent (null) on UPDATE. 400 unknown_dietary_tag for another word; 400 dietary_refused when the allergens as they will stand contradict one (a nut-free dish listing nuts)." }
        brand: { type: string, nullable: true, description: "Retail metadata (V18). Keep-on-absent; send \"\" to clear." }
        supplierId: { type: string, nullable: true, description: "Primary supplier (V18). Keep-on-absent; send \"\" to clear." }
        stockUnit: { type: string, nullable: true, enum: [each, g, ml], description: "The unit stock is counted in (V36). Keep-on-absent, so a client that does not know about units cannot un-declare one. 400 invalid_stock_unit for a non-base unit; 409 unit_in_use when changing dimension while recipes still measure this product in the old one." }
        prepStationId: { type: string, nullable: true, description: "The dish's own prep station (V250, T-36.2), overriding its category's while that station is on. Keep-on-absent: null leaves it, an empty string clears it. Must be a live station of this tenant (else 400 unknown_station)." }
        alsoStationIds: { type: array, nullable: true, items: { type: string }, description: "The dish's other stations (V254, T-36.3): the dish also fires one ticket item to each, beside its own or its category's station. Keep-on-absent: null leaves them, a list replaces them (an empty list clears them). Each must be a live station of this tenant (else 400 unknown_station); the dish's own station and repeats are dropped." }
        prepNotes: { type: string, nullable: true, description: "The dish's prep notes (V259, T-36.11), trimmed, up to 1000 characters (else 400 prep_notes_too_long). Keep-on-absent: null leaves them, an empty string clears them." }
      required: [categoryId, name, priceCents]
      description: "`emoji`/`imageUrl`/`sku`/`barcode`/`sortOrder` are keep-on-absent: omitting them on an update preserves the stored values."
    ModifierOptionDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        priceDeltaCents: { type: integer, format: int64 }
        sortOrder: { type: integer }
        prepStationId: { type: string, nullable: true, description: "The prep station that makes this option (V265, T-36.8): a fired line carrying it is also sent there, listing only what that station makes. Null = the option rides with its dish." }
      required: [id, name, priceDeltaCents, sortOrder]
    ModifierGroupDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        required: { type: boolean }
        multiSelect: { type: boolean }
        minSelect: { type: integer, default: 0 }
        maxSelect: { type: integer, default: 1 }
        sortOrder: { type: integer, default: 0 }
        options: { type: array, items: { $ref: "#/components/schemas/ModifierOptionDto" } }
      required: [id, name, required, multiSelect, options]
    ImageUploadRequest:
      type: object
      description: Base64 image upload (V16) — location logos and zone floor plans (decoded ≤1 MB). PNG/JPEG/WebP, judged by the bytes; `mime` decides nothing. Dish photos use ProductPhotoUploadRequest.
      properties:
        imageBase64: { type: string, description: "Base64-encoded image bytes." }
        mime: { type: string, default: "image/png", enum: [image/png, image/jpeg, image/webp] }
      required: [imageBase64]
    ProductPhotoUploadRequest:
      type: object
      description: A dish photo (T-4.7). Judged by its bytes, framed by `crop`, shrunk to what a guest's phone needs.
      properties:
        imageBase64: { type: string, description: "Base64-encoded PNG or JPEG bytes (decoded ≤ 10 MB)." }
        mime: { type: string, description: "Advisory only; the server reads the type from the bytes.", enum: [image/png, image/jpeg, image/webp] }
        crop:
          type: object
          nullable: true
          description: The part of the upright picture to keep, as fractions (0..1) of its width and height. Omit it to keep the whole picture.
          properties:
            x: { type: number }
            y: { type: number }
            w: { type: number }
            h: { type: number }
          required: [x, y, w, h]
      required: [imageBase64]
    ProductPhotoResponse:
      type: object
      properties:
        id: { type: string }
        imageUrl: { type: string, nullable: true, description: "What products.image_url now holds (the internal photo path after upload; an external URL or null after delete)." }
      required: [id]
    ProductModifierLinkRequest:
      type: object
      properties:
        groupId: { type: string }
        sortOrder: { type: integer, default: 0 }
      required: [groupId]
    ProductModifierLinkDto:
      type: object
      properties:
        groupId: { type: string }
        sortOrder: { type: integer }
      required: [groupId, sortOrder]
    ModifierOptionUpsert:
      type: object
      properties:
        id: { type: string, nullable: true }
        name: { type: string }
        priceDeltaCents: { type: integer, format: int64, default: 0 }
        sortOrder: { type: integer, default: 0 }
        prepStationId: { type: string, nullable: true, description: "The option's own prep station (V265, T-36.8). Keep-on-absent: null leaves an existing option's station as it is (a new option has none), an empty string clears it. Must be a live station of this tenant (else 400 unknown_station); checked before anything is written." }
      required: [name]
    ModifierGroupUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        name: { type: string }
        required: { type: boolean, default: false }
        multiSelect: { type: boolean, default: false }
        minSelect: { type: integer, default: 0 }
        maxSelect: { type: integer, default: 1 }
        sortOrder: { type: integer, default: 0 }
        options: { type: array, items: { $ref: "#/components/schemas/ModifierOptionUpsert" }, default: [] }
      required: [name]
    TaxRateDto:
      type: object
      properties:
        id: { type: string }
        code: { type: string }
        name: { type: string }
        rateBp: { type: integer, description: "Basis points (e.g. 1500 = 15%)." }
        inclusive: { type: boolean }
        usedBy: { type: integer, description: "How many live products are sold at this rate; it can be deleted only at 0 (D-225)." }
      required: [id, code, name, rateBp, inclusive]
    TaxRateUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        code: { type: string }
        name: { type: string }
        rateBp: { type: integer, minimum: 0, maximum: 10000 }
        inclusive: { type: boolean, default: true }
      required: [code, name, rateBp]

    # ── Staff ──
    StaffDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        role: { type: string }
        email: { type: string, nullable: true }
        phone: { type: string, nullable: true }
        colorHex: { type: string, nullable: true }
        hourlyRateCents: { type: integer, format: int64 }
        active: { type: boolean }
        createdAt: { type: integer, format: int64 }
        updatedAt: { type: integer, format: int64 }
        account: { type: string, nullable: true, enum: [INVITED, SIGNS_IN], description: "Null for a person who signs in with a PIN; INVITED until an email-invited person claims the account (chooses a password from a link, or signs in), then SIGNS_IN." }
        inviteSent: { type: boolean, nullable: true, description: "Only on the answer to an invite: whether the provider took the email." }
      required: [id, name, role, hourlyRateCents, active, createdAt, updatedAt]
    StaffCreateRequest:
      type: object
      properties:
        name: { type: string }
        role: { type: string, description: "One of ADMIN, SUPER_ADMIN, MANAGER, SERVER, CASHIER, BARTENDER, CHEF, HOST, STOCK_CONTROLLER, ACCOUNTANT. At or below the caller's own rank (403 role_escalation_forbidden otherwise). DEVICE is a legal role but never a person's: 400 role_not_for_people." }
        pin: { type: string, nullable: true, description: "4-8 digits (400 validation_error otherwise). Required unless `invite` is true; beside an invite it is optional and gives the same person a PIN for a screen's PIN pad too." }
        email: { type: string, nullable: true, description: "Required for an invite (400 email_required, invalid_email); optional otherwise." }
        phone: { type: string, nullable: true }
        colorHex: { type: string, nullable: true }
        hourlyRateCents: { type: integer, format: int64, default: 0 }
        invite: { type: boolean, default: false, description: "Make a person who signs in with an email instead of a PIN." }
      required: [name, role]
    StaffUpdateRequest:
      type: object
      description: All fields optional — only fields present in the body are updated.
      properties:
        name: { type: string, nullable: true }
        role: { type: string, nullable: true }
        active: { type: boolean, nullable: true }
        email: { type: string, nullable: true }
        phone: { type: string, nullable: true }
        colorHex: { type: string, nullable: true }
        hourlyRateCents: { type: integer, format: int64, nullable: true }
    StaffResetPinRequest:
      type: object
      properties:
        pin: { type: string, description: "4-8 digits." }
      required: [pin]
    ClockInRequest:
      type: object
      properties:
        staffId: { type: string }
        locationId: { type: string }
        openingFloatCents: { type: integer, format: int64, default: 0 }
        id: { type: string, nullable: true, description: "Client-minted shift id; a repeat answers with the shift it already opened (T-3.2)" }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When it happened on the till (server time, ms); within the last 7 days, else 400 invalid_occurred_at. Absent = now." }
      required: [staffId, locationId]
    ClockOutRequest:
      type: object
      properties:
        shiftId: { type: string }
        breakMinutes: { type: integer, default: 0 }
        closingFloatCents: { type: integer, format: int64, nullable: true }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When it happened (server time, ms). Closing a closed shift changes nothing." }
      required: [shiftId]
    DutyOnRequest:
      type: object
      properties:
        id: { type: string, description: "Minted on the device before the first attempt; the idempotency key." }
        locationId: { type: string }
        source: { type: string, enum: [TILL, KDS, PHONE, BACK_OFFICE] }
        staffId: { type: string, nullable: true, description: "Null: the signed-in person themself." }
        occurredAt: { type: integer, format: int64, nullable: true }
        photoBase64: { type: string, nullable: true, description: "The clock-on still, re-encoded by the server; never kept as sent." }
        noPhoto: { type: string, nullable: true, enum: [NO_CAMERA, CAMERA_REFUSED, NOT_TAKEN, UNREADABLE, SWITCHED_OFF] }
      required: [id, locationId, source]
    DutyOnAnswer:
      type: object
      properties:
        id: { type: string }
        onAt: { type: integer, format: int64 }
        alreadyOn: { type: boolean }
      required: [id, onAt, alreadyOn]
    DutyOffRequest:
      type: object
      properties:
        dutyId: { type: string }
        staffId: { type: string, nullable: true }
        occurredAt: { type: integer, format: int64, nullable: true }
      required: [dutyId]
    DutyCorrectionRequest:
      type: object
      properties:
        id: { type: string }
        onAt: { type: integer, format: int64 }
        offAt: { type: integer, format: int64, nullable: true }
        reason: { type: string, minLength: 3, maxLength: 500 }
      required: [id, onAt, reason]
    DutyRowDto:
      type: object
      properties:
        id: { type: string }
        staffId: { type: string }
        staffName: { type: string, nullable: true }
        role: { type: string, nullable: true }
        locationId: { type: string }
        onAt: { type: integer, format: int64 }
        offAt: { type: integer, format: int64, nullable: true }
        source: { type: string }
        correctedFrom: { type: string, nullable: true }
        reason: { type: string, nullable: true }
        recordedBy: { type: string, nullable: true }
        supersededBy: { type: string, nullable: true }
        lateMinutes: { type: integer, nullable: true, description: "Minutes after the rostered start beyond 5; 0 on time; null when not rostered." }
        photo: { type: string, enum: [STORED, DELETED, NONE] }
        createdAt: { type: integer, format: int64 }
      required: [id, staffId, locationId, onAt, source, photo, createdAt]
    OnDutyPerson:
      type: object
      properties:
        staffId: { type: string }
        name: { type: string }
        role: { type: string, nullable: true }
        locationId: { type: string }
        onAt: { type: integer, format: int64 }
        lateMinutes: { type: integer, nullable: true, description: "Never sent by /duty/floor." }
      required: [staffId, name, locationId, onAt]
    DutyMine:
      type: object
      properties:
        open: { allOf: [{ $ref: "#/components/schemas/DutyRowDto" }], nullable: true }
        photosOn: { type: boolean, description: "Whether the business takes a photo at clock-on; off, the device opens no camera." }
    DutyPhotoSetting:
      type: object
      properties:
        "on": { type: boolean }
      required: ["on"]
    DutyLogPage:
      type: object
      properties:
        rows: { type: array, items: { $ref: "#/components/schemas/DutyRowDto" } }
        nextBefore: { type: string, nullable: true }
      required: [rows]
    DutyPhotoRetention:
      type: object
      properties:
        days: { type: integer, minimum: 1, maximum: 365 }
      required: [days]
    ShiftBreakResult:
      type: object
      properties:
        breakMinutes: { type: integer, description: "Break minutes recorded on the shift so far." }
      required: [breakMinutes]
    OpenShiftDto:
      type: object
      properties:
        id: { type: string }
        staffId: { type: string }
        locationId: { type: string }
        clockInAt: { type: integer, format: int64 }
        openingFloatCents: { type: integer, format: int64 }
        staffName: { type: string, nullable: true, description: "Who opened the register (the drawer's person, T-21.6); null when no staff row names them." }
        breakStartedAt: { type: integer, format: int64, nullable: true, description: "When the break now running began (T-25.4); null when none runs." }
      required: [id, staffId, locationId, clockInAt, openingFloatCents]
    ShiftCloseRequest:
      type: object
      description: Optional body for the manager force clock-out. Absent closingFloatCents leaves the stored value untouched.
      properties:
        closingFloatCents: { type: integer, format: int64, nullable: true }
    ShiftCloseResponse:
      type: object
      properties:
        id: { type: string }
        status: { type: string, example: CLOSED }
        clockOutAt: { type: integer, format: int64 }
      required: [id, status, clockOutAt]

    # ── Locations ──
    LocationDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        address: { type: string, nullable: true }
        town: { type: string, nullable: true, maxLength: 60, description: "The venue's own town (T-43.30), shown to a Ruva agent beside the business; null where the venue has not said and the agent is shown what the address ends in." }
        phone: { type: string, nullable: true }
        vatNumber: { type: string, nullable: true }
        timezone: { type: string, example: Africa/Johannesburg }
        currency: { type: string, example: ZAR }
        receiptHeader: { type: string, nullable: true, description: "Receipt branding header lines." }
        receiptFooter: { type: string, nullable: true, description: "Receipt branding footer lines." }
        hasLogo: { type: boolean, description: "True when a logo is stored (fetch via public GET /locations/{id}/logo)." }
        businessType: { type: string, enum: [HOSPITALITY, RETAIL], default: HOSPITALITY, description: "Vertical (V17) — drives POS shop mode." }
        serviceChargeBp: { type: integer, default: 0, description: "Automatic service charge in basis points (T-3.4); 0 = none." }
        serviceChargeMinParty: { type: integer, default: 0, description: "Covers from which the service charge applies." }
        blindCashCount: { type: boolean, default: false, description: "Registers here close by blind count (T-3.6): the X/Z reports and register history withhold the expected cash, cash takings and variance from anyone but a manager." }
        guestsCollectAtCounter: { type: boolean, default: false, description: "Guests collect a dine-in order at the counter (T-5.4), so their phones are offered the buzzer for it. The effective setting: the manager's word, else on for a business with no table-service till and off for one that has." }
        counterPayments: { type: boolean, default: false, description: "Guests may pay at the counter, and the back office closes the order (T-1.20, V146). Off until a manager turns it on; only a business with no till uses it." }
        phoneTabs: { type: boolean, default: false, description: "Guests may open a tab and pay it once on their phone (T-30.14, V156). Only a location with no till can run one; off until a manager turns it on, because nothing holds a guest's card and a guest can leave without paying." }
        phoneTabLimitCents: { type: integer, format: int64, default: 50000, description: "What a phone tab may owe before the next round asks the guest to pay first, in cents; 0 = no credit (T-30.14)." }
        googleReviewUrl: { type: string, nullable: true, description: "The venue's Google review link (T-39.5, V256), offered to every guest who rates, whatever they rated (T-35.21), and on every paid receipt's page and email (T-35.22); null = none." }
        receiptReviewQr: { type: boolean, default: false, description: "A kiosk's printed receipt carries the review link as a QR code under \"Tell others how your visit went\" (T-35.22, V326). Off until a manager turns it on." }
        guestRefundTerms: { type: string, nullable: true, description: "The venue's own refund and cancellation sentence (T-39.3, V263); null = the default sentence every guest reads." }
        guestPrivacyUrl: { type: string, nullable: true, description: "The venue's own privacy notice address (T-39.3, V263); null = Ruva's notice is offered while it is published." }
        collectMaxQuantity: { type: integer, default: 50, minimum: 1, maximum: 9999, description: "The most of one item a click-and-collect order may take here (T-2.54, V261): the EFFECTIVE figure, 50 where the venue has set none." }
        collectMaxQuantitySet: { type: boolean, default: false, description: "Whether the venue has set its own collectMaxQuantity (T-2.54); false = it follows the default." }
        kioskAsksHandover: { type: boolean, default: false, description: "The self-order kiosk here asks \"Eat in\" or \"Take away\" before the menu (T-39.11, V317). Off until a manager turns it on." }
        tableCodesRequired: { type: boolean, default: false, description: "A guest must type the code printed on their table before a tab or pay-at-the-counter order (T-39.9, V312). Off until a manager turns it on." }
        tableCodesRotatedAt: { type: integer, format: int64, nullable: true, description: "When a manager last made new table codes, or null if never. The codes themselves are never returned." }
        tabAlertMinutes: { type: integer, default: 180, minimum: 0, maximum: 1440, description: "Minutes a tab may stay open before a manager's phone is told (T-39.8, V311): the EFFECTIVE figure, 180 where none is set, 0 = the tab alert is off." }
        staggeredFire: { type: boolean, default: false, description: "Staggered fire (T-36.24, V293): each line of one fire starts at the longest prep target of its course on the fire less its own (a drink is never held), so a table's dishes finish together; a kitchen ticket's item then carries `startAfterSec`. Off until a manager turns it on." }
        tillPinnedActions: { type: array, items: { type: string, enum: [print_bill, bill, move, fire, guests] }, maxItems: 3, description: "The Floor ticket actions pinned to the front of the till's bar, in the order drawn (T-43.23, V409). Empty = none pinned." }
        tillFiresAfterPayment: { type: boolean, default: false, description: "A till sale at this location reaches the kitchen once its checkout closes, by the one pay-first rule a guest's QR order reads (T-43.23, V409); a bar tab is never held. Off until a manager turns it on." }
        kitchenHours: { type: array, items: { $ref: "#/components/schemas/KitchenDay" }, description: "The kitchen's hours, Monday first (T-39.20, V301); empty = none set. Set with PUT /locations/{id}/kitchen-hours." }
        showPopular: { type: boolean, default: true, description: "The guest menu shows \"Popular right now\" (T-41.26, V300, D-159): the order of the venue's best sellers, never a figure; off, `/qr/menu` carries no `popular` ids. On until a manager turns it off." }
        guestBookingEmail: { type: boolean, default: true, description: "Guests who are not reached on WhatsApp are emailed their booking's confirmation and its day-before and two-hours reminders (T-27.7, V372). On until a manager turns it off." }
        registeredDevicesOnly: { type: boolean, default: false, description: "Only a manager's account signs in by email and password on a device the business has not registered (T-22.3, V352, D-47); anyone else gets `403 device_not_registered` and is told to ask a manager. A device is registered by a manager's sign-in on it or by pairing. Off until a manager turns it on." }
        showDishEmoji: { type: boolean, default: false, description: "The guest menu draws a dish's emoji on a no-photo tile instead of its two letters (T-39.24, V332). Off until a manager turns it on; a dish with a photo or with no emoji is unchanged. `/qr/menu` carries the result per dish as `tileEmoji`." }
        tableIdleMinutes: { type: integer, default: 90, minimum: 15, maximum: 720, description: "At a venue with no till (T-39.28, V309_92): minutes with nobody ordering or paying after which a table in use frees itself. The EFFECTIVE figure, 90 where none is set." }
        floorCheckOnMinutes: { type: integer, default: 15, minimum: 10, maximum: 60, description: "The till's floor (T-25.2, V380): minutes with nobody ordering at a table after which it reads Check on, and twice that Idle. The EFFECTIVE figure, 15 where none is set. Not tableIdleMinutes." }
      required: [id, name, timezone, currency, hasLogo]
    LocationUpsertRequest:
      type: object
      description: Optional fields are keep-on-absent on UPDATE; on INSERT timezone/currency default to Africa/Johannesburg + ZAR.
      properties:
        id: { type: string, nullable: true, maxLength: 64, description: "Absent = create with a server-minted id. A new location's id is at most 64 characters (`400 invalid_location_id`)." }
        name: { type: string }
        address: { type: string, nullable: true }
        town: { type: string, nullable: true, maxLength: 60, description: "The venue's own town (T-43.30): at most 60 characters after trimming, else `400 invalid_town` with the sentence; an empty string clears it. Keep-on-absent." }
        phone: { type: string, nullable: true }
        vatNumber: { type: string, nullable: true }
        receiptHeader: { type: string, nullable: true }
        receiptFooter: { type: string, nullable: true }
        timezone: { type: string, nullable: true }
        currency: { type: string, nullable: true }
        businessType: { type: string, nullable: true, enum: [HOSPITALITY, RETAIL], description: "Keep-on-absent on update; HOSPITALITY on insert; invalid value → 400 invalid_business_type." }
        serviceChargeBp: { type: integer, nullable: true, minimum: 0, maximum: 10000, description: "Automatic service charge in basis points (T-3.4); 0 = none. Keep-on-absent; out of range → 400 invalid_service_charge." }
        serviceChargeMinParty: { type: integer, nullable: true, minimum: 0, maximum: 100, description: "Covers from which the service charge applies. Keep-on-absent; out of range → 400 invalid_service_charge_party." }
        blindCashCount: { type: boolean, nullable: true, description: "Close registers by blind count (T-3.6). Keep-on-absent; off on insert." }
        guestsCollectAtCounter: { type: boolean, nullable: true, description: "Guests collect a dine-in order at the counter (T-5.4). Keep-on-absent; not chosen (the licence's default applies) until set." }
        counterPayments: { type: boolean, nullable: true, description: "Guests may pay at the counter (T-1.20). Keep-on-absent; off on insert." }
        phoneTabs: { type: boolean, nullable: true, description: "Guests may open a phone tab (T-30.14). Keep-on-absent; off on insert." }
        phoneTabLimitCents: { type: integer, format: int64, nullable: true, description: "The phone-tab limit in cents, 0 to 10000000 (`400 invalid_tab_limit` outside it). Keep-on-absent; 50000 on insert." }
        googleReviewUrl: { type: string, nullable: true, maxLength: 500, description: "The Google review link every guest who rates is offered, whatever they rated (T-39.5, T-35.21): an https link on a Google host (g.page, search.google.com/local, google.com/maps, maps.app.goo.gl, goo.gl/maps); anything else is `400 invalid_review_link` with the sentence to show. Keep-on-absent; an empty string clears it." }
        receiptReviewQr: { type: boolean, nullable: true, description: "Whether a kiosk's printed receipt carries the review link as a QR code (T-35.22). Keep-on-absent; off on insert; clearing googleReviewUrl turns it off." }
        guestRefundTerms: { type: string, nullable: true, maxLength: 500, description: "The refund and cancellation sentence a guest reads before paying and on the receipt (T-39.3): plain text on one line, at most 500 characters, else `400 invalid_refund_terms` with the sentence to show. Keep-on-absent; an empty string clears it (the default sentence applies)." }
        guestPrivacyUrl: { type: string, nullable: true, maxLength: 500, description: "The venue's own privacy notice address (T-39.3): an https address with a dotted host, no credentials or port, else `400 invalid_privacy_link` with the sentence to show. Keep-on-absent; an empty string clears it (Ruva's notice is offered while it is published)." }
        collectMaxQuantity: { type: integer, nullable: true, minimum: 1, maximum: 9999, description: "The most of one item a click-and-collect order may take (T-2.54, D-110): `400 invalid_collect_quantity` with the sentence outside 1 to 9999. Keep-on-absent; 50 where none is set. Table orders and delivery stay at 50; a kiosk's takeaway is held to it where it is below 50 (T-39.18). Needs MANAGE_LOCATIONS." }
        tableCodesRequired: { type: boolean, nullable: true, description: "Ask for the table's printed code before an unpaid order (T-39.9). Keep-on-absent; off on insert. Turning it on gives every table without one a code." }
        collectMaxQuantityReset: { type: boolean, nullable: true, description: "True forgets the venue's own collectMaxQuantity, so it follows the default (50) again (T-2.54). Refused `400 invalid_collect_quantity` when sent with a figure." }
        kioskAsksHandover: { type: boolean, nullable: true, description: "The self-order kiosk asks \"Eat in\" or \"Take away\" before the menu (T-39.11). Keep-on-absent; off on a new location. The guest's choice is the order's `fulfilmentType`, and VAT and the total are the same either way. Needs MANAGE_LOCATIONS." }
        tabAlertMinutes: { type: integer, nullable: true, minimum: 0, maximum: 1440, description: "Minutes a tab may stay open before a manager's phone is told (T-39.8); keep-on-absent, 0 turns the tab alert off, outside 0 to 1440 is `400 invalid_tab_alert`." }
        staggeredFire: { type: boolean, nullable: true, description: "Staggered fire, so a table's dishes finish together (T-36.24). Keep-on-absent; off on insert." }
        tillPinnedActions: { type: array, nullable: true, items: { type: string, enum: [print_bill, bill, move, fire, guests] }, maxItems: 3, description: "The till's pinned Floor actions (T-43.23). Keep-on-absent; more than three, an unknown id or a repeat is 400 `invalid_till_pinned_actions`." }
        tillFiresAfterPayment: { type: boolean, nullable: true, description: "A till sale is sent to the kitchen once paid (T-43.23). Keep-on-absent; off on insert." }
        showPopular: { type: boolean, nullable: true, description: "Whether the guest menu shows \"Popular right now\" (T-41.26, D-159). Keep-on-absent; on on insert." }
        guestBookingEmail: { type: boolean, nullable: true, description: "Whether guests are emailed their booking's confirmation and reminders (T-27.7). Keep-on-absent; on on insert." }
        registeredDevicesOnly: { type: boolean, nullable: true, description: "Whether only a manager's account may sign in on a device the business has not registered (T-22.3, D-47). Keep-on-absent; off on insert." }
        showDishEmoji: { type: boolean, nullable: true, description: "Whether the guest menu draws a dish's emoji where it has no photo (T-39.24). Keep-on-absent; off on insert." }
        tableIdleMinutes: { type: integer, nullable: true, minimum: 15, maximum: 720, description: "At a venue with no till (T-39.28): minutes with nobody ordering or paying after which a table in use frees itself; `400 invalid_table_idle` with the sentence outside 15 to 720. Keep-on-absent; 90 where none is set." }
        floorCheckOnMinutes: { type: integer, nullable: true, minimum: 10, maximum: 60, description: "The till's floor (T-25.2): minutes with nobody ordering at a table after which it reads Check on, and twice that Idle; `400 invalid_floor_check_on` with the sentence outside 10 to 60. Keep-on-absent; 15 where none is set." }
      required: [name]
    TableCodesRotateRequest:
      type: object
      required: [locationId]
      properties:
        locationId: { type: string }
    TableCodesRotated:
      type: object
      required: [tables, rotatedAt]
      properties:
        tables: { type: integer, description: "How many live tables were given a new code." }
        rotatedAt: { type: integer, format: int64, description: "When, in epoch milliseconds. No code is ever in this answer." }
    LocationLogoResponse:
      type: object
      properties:
        id: { type: string }
        hasLogo: { type: boolean }
      required: [id, hasLogo]

    # ── Floor & Tables ──
    TableDto:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        zoneId: { type: string }
        label: { type: string }
        seats: { type: integer }
        shape: { type: string }
        status: { type: string }
        currentOrderId: { type: string, nullable: true }
        guestCount: { type: integer }
        seatedAt: { type: integer, format: int64, nullable: true }
        serverStaffId: { type: string, nullable: true }
        positionX: { type: integer, default: 0 }
        positionY: { type: integer, default: 0 }
      required: [id, locationId, zoneId, label, seats, shape, status, guestCount]
    TableUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        locationId: { type: string }
        zoneId: { type: string }
        label: { type: string, description: "Must be unique per location among live tables (409 duplicate_label)." }
        seats: { type: integer, default: 2 }
        positionX: { type: integer, nullable: true }
        positionY: { type: integer, nullable: true }
        shape: { type: string, nullable: true }
      required: [locationId, zoneId, label]
      description: "`positionX`/`positionY`/`shape` are keep-on-absent: omitting them on an update preserves the stored floor-plan layout (inserts default to 0,0/ROUND)."
    TurnTime:
      type: object
      required: [minutes, source, samples]
      properties:
        minutes: { type: integer, description: Expected minutes seated. }
        source:
          type: string
          enum: [THIS_SIZE, ALL_SIZES, DEFAULT]
          description: Learned from this party size, borrowed from every size, or a starting guess.
        samples: { type: integer, description: Turns the figure was taken from; 0 for a starting guess. }
    TurnTimes:
      type: object
      required: [bands]
      properties:
        bands:
          type: object
          description: Keyed by party band - TWO (1-2), FOUR (3-4), SIX (5-6), LARGE (7+).
          additionalProperties: { $ref: "#/components/schemas/TurnTime" }
    FloorSection:
      type: object
      required: [id, locationId, name, sortOrder, tableIds, staffIds]
      properties:
        id: { type: string }
        locationId: { type: string }
        name: { type: string }
        sortOrder: { type: integer }
        tableIds: { type: array, items: { type: string } }
        staffIds: { type: array, items: { type: string } }
    FloorSectionUpsert:
      type: object
      required: [locationId, name]
      properties:
        id: { type: string, nullable: true, description: Omit to create. }
        locationId: { type: string }
        name: { type: string }
        sortOrder: { type: integer, default: 0 }
        tableIds: { type: array, items: { type: string } }
    SectionStaffRequest:
      type: object
      required: [staffIds]
      properties:
        staffIds: { type: array, items: { type: string } }
    TableSeatRequest:
      type: object
      properties:
        guestCount: { type: integer }
        serverStaffId: { type: string, nullable: true }
      required: [guestCount]
    TableTransferRequest:
      type: object
      properties:
        toTableId: { type: string }
      required: [toTableId]
    TableMergeRequest:
      type: object
      properties:
        intoTableId: { type: string }
      required: [intoTableId]
    ZoneDto:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        name: { type: string }
        sortOrder: { type: integer }
        priceListId: { type: string, nullable: true, description: "The zone's own price level (T-3.4); null = the location's prices." }
      required: [id, locationId, name, sortOrder]
    ZoneUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        locationId: { type: string }
        name: { type: string }
        sortOrder: { type: integer, default: 0 }
      required: [locationId, name]
    ReservationDto:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        tableId: { type: string, nullable: true }
        guestName: { type: string }
        partySize: { type: integer }
        phone: { type: string, nullable: true }
        email: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        reservedForAt: { type: integer, format: int64 }
        durationMinutes: { type: integer }
        status: { type: string }
        guest:
          allOf: [{ $ref: "#/components/schemas/BookingGuest" }]
          description: What the venue knows of the guest (matched by phone, then email). Sent only to a caller holding VIEW_CUSTOMERS, and absent when no single guest matches.
        allergens: { type: array, items: { type: string }, description: "The allergies the guest picked at booking (health information). Sent only to a caller holding MANAGE_RESERVATIONS; absent for anyone else." }
        dietaryNote: { type: string, nullable: true, description: "What the guest wrote about their diet. Sent only to a caller holding MANAGE_RESERVATIONS; absent for anyone else." }
      required: [id, locationId, guestName, partySize, reservedForAt, durationMinutes, status]
    BookingGuest:
      type: object
      description: Personal information. Tags and note are kept on the guest's customer record, so erasing the guest erases them.
      properties:
        customerId: { type: string }
        tags: { type: array, items: { type: string } }
        note: { type: string, nullable: true }
        visits: { type: integer, description: Bookings of this guest that name a paid bill. }
        spendCents: { type: integer, format: int64, description: Those bills' totals, each bill once. }
        lastVisitAt: { type: integer, format: int64, nullable: true }
        name: { type: string, nullable: true, description: The name on the customer's record, so a booking made under another name shows whose record it is. }
      required: [customerId, tags, visits, spendCents]
    GuestTag:
      type: object
      properties:
        id: { type: string }
        label: { type: string, maxLength: 24 }
        kitchen: { type: boolean, description: May this tag print in the header of a seated table's kitchen ticket. }
      required: [id, label, kitchen]
    ReservationUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        locationId: { type: string }
        tableId: { type: string, nullable: true }
        guestName: { type: string }
        partySize: { type: integer }
        phone: { type: string, nullable: true }
        email: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        reservedForAt: { type: integer, format: int64 }
        durationMinutes: { type: integer, default: 90 }
        status: { type: string, default: PENDING }
      required: [locationId, guestName, partySize, reservedForAt]

    # ── Waitlist ──
    WaitlistEntryDto:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        guestName: { type: string }
        partySize: { type: integer }
        phone: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        status: { type: string }
        createdAt: { type: integer, format: int64 }
        position: { type: integer }
        waitedMinutes: { type: integer }
        quotedWaitMinutes: { type: integer, nullable: true, description: "Null when no table seats the party (NO_TABLE)." }
        quoteBasis: { type: string, enum: [TABLES, PER_PARTY, NO_TABLE, NONE], description: "How the quote was reached; NONE on an entry no longer waiting." }
        vip: { type: boolean, description: "Bumped ahead of every party that is not." }
        readyAt: { type: integer, format: int64, nullable: true, description: "When the host said the table was ready." }
        selfJoined: { type: boolean, description: "Joined from the QR code rather than added at the stand." }
      required: [id, locationId, guestName, partySize, status, createdAt, position, waitedMinutes]
    WaitlistVipRequest:
      type: object
      properties:
        vip: { type: boolean }
      required: [vip]
    WaitlistReadyResult:
      type: object
      properties:
        id: { type: string }
        readyAt: { type: integer, format: int64 }
        message: { type: string, enum: [SENT, FAILED, NO_PHONE, NOT_CONFIGURED] }
      required: [id, readyAt, message]
    StationPrinterRequest:
      type: object
      properties:
        printerHost: { type: string, nullable: true, description: "The printer's IP address or host name; blank or null clears it." }
        printerPort: { type: integer, minimum: 1, maximum: 65535, nullable: true, description: "9100 when omitted." }
    TicketIds:
      type: object
      required: [ids]
      properties:
        ids: { type: array, maxItems: 500, items: { type: string } }
    PrintClaim:
      type: object
      description: A kitchen screen's claim on tickets to print (T-1.21, core `PrintClaim`).
      required: [locationId, ids]
      properties:
        locationId: { type: string, description: The location the screen shows. }
        stationId: { type: string, nullable: true, description: The one station the screen shows (what an older screen sends); omitted on an all-stations screen. }
        stationIds: { type: array, maxItems: 24, items: { type: string, maxLength: 64 }, description: "The stations a screen set to several shows (T-36.1); wins over stationId when not empty. Both absent: an all-stations screen. A blank id, an id over 64 characters, more than 24 ids, or a blank stationId is refused with 400 bad_stationIds." }
        ids: { type: array, maxItems: 500, items: { type: string } }
    QrReceiptLink:
      type: object
      required: [url]
      properties:
        url: { type: string, description: The public page of the order's receipt. }
    QrReceiptEmailRequest:
      type: object
      required: [email]
      properties:
        email: { type: string, maxLength: 254 }
    QrReceiptEmailAnswer:
      type: object
      required: [status]
      properties:
        status: { type: string, enum: [NONE, WAITING, SENT, NOT_SET_UP, FAILED, UNSURE] }
    Receipt:
      type: object
      description: A sale's receipt as the receipt page and a printer draw it (core `Receipt`).
      required: [number, openedAt, locationName, items, payments, subtotalCents, discountCents, vatCents, tipCents, roundingCents, totalCents]
      properties:
        number: { type: string }
        openedAt: { type: integer, format: int64 }
        closedAt: { type: integer, format: int64, nullable: true }
        locationName: { type: string }
        locationAddress: { type: string, nullable: true }
        vatNumber: { type: string, nullable: true }
        items:
          type: array
          items:
            type: object
            properties:
              name: { type: string }
              quantity: { type: integer }
              unitPriceCents: { type: integer, format: int64 }
              lineTotalCents: { type: integer, format: int64 }
        payments:
          type: array
          items:
            type: object
            properties:
              method: { type: string }
              amountCents: { type: integer, format: int64 }
              tipCents: { type: integer, format: int64 }
        subtotalCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64 }
        roundingCents: { type: integer, format: int64 }
        serviceChargeCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        guestTerms: { $ref: "#/components/schemas/GuestTerms" }
        review: { $ref: "#/components/schemas/ReceiptReview" }
        offers:
          type: array
          description: "The offers the sale settled, one per offer, each by its name (re-walk RW-G-3): within `discountCents`, which is everything taken off; the rest is what people took off. Empty when no offer applied."
          items:
            type: object
            required: [name, discountCents]
            properties:
              name: { type: string }
              discountCents: { type: integer, format: int64 }
    ReceiptReview:
      type: object
      nullable: true
      description: "The venue's review line under the receipt's footer (T-35.22, core `ReceiptReview`): \"Tell others how your visit went\" and the venue's Google review link, exactly as the venue set it. Present only for a paid sale with something to pay, at a location with a link; never on a refund's own document. Nothing about the guest's rating decides it."
      required: [link]
      properties:
        link: { type: string, description: "The venue's Google review link, unchanged (nothing about the guest is added)." }
        onPaper: { type: boolean, default: false, description: "The venue prints it on a kiosk's receipt as a QR code under the line (V326 `receiptReviewQr`); false = the printed receipt carries no review line." }
    GuestTerms:
      type: object
      nullable: true
      description: "What a guest is told before paying and on the receipt (T-39.3, core `GuestTerms`): who is selling, how to reach them, the refund and cancellation sentence, the privacy notice and the allergen line. The venue's own words where it has set them, else plain defaults."
      required: [sellerName, refundSentence, allergenLine]
      properties:
        sellerName: { type: string, description: "The venue's trading name." }
        vatNumber: { type: string, nullable: true, description: "The location's VAT number when it is registered." }
        address: { type: string, nullable: true }
        phone: { type: string, nullable: true }
        refundSentence: { type: string, description: "The venue's own sentence, else the default." }
        privacyUrl: { type: string, nullable: true, description: "The venue's own privacy notice, else Ruva's while it is published; null when neither exists." }
        allergenLine: { type: string }
    WaitlistJoinRequest:
      type: object
      properties:
        locationId: { type: string }
        guestName: { type: string, maxLength: 100 }
        partySize: { type: integer, minimum: 1, maximum: 20 }
        phone: { type: string, description: "A mobile number; normalised to E.164." }
      required: [locationId, guestName, partySize, phone]
    WaitlistJoinStatus:
      type: object
      properties:
        id: { type: string }
        locationName: { type: string }
        state: { type: string, enum: [WAITING, READY, SEATED, GONE] }
        position: { type: integer, nullable: true }
        quotedWaitMinutes: { type: integer, nullable: true }
        quoteBasis: { type: string, nullable: true, enum: [TABLES, PER_PARTY, NO_TABLE] }
        partySize: { type: integer }
      required: [id, locationName, state, partySize]
    LineMoveRequest:
      type: object
      properties:
        course: { type: string, nullable: true, description: "STARTER, MAIN, DESSERT, DRINK or OTHER; absent keeps the course." }
        seat: { type: integer, nullable: true, description: "The new seat, from 1; absent keeps the seat." }
        shared: { type: boolean, default: false, description: "True makes it a shared plate (no seat)." }
    LineMoveResult:
      type: object
      properties:
        lineId: { type: string }
        seat: { type: integer, nullable: true }
        course: { type: string }
        ticketId: { type: string, nullable: true }
      required: [lineId, course]
    WaitlistAddRequest:
      type: object
      properties:
        locationId: { type: string }
        guestName: { type: string }
        partySize: { type: integer }
        phone: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        id: { type: string, nullable: true, description: "Minted by the till before the first attempt; a request whose id already landed answers with the entry it made (T-3.2)." }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When the party arrived, epoch ms in server time; sets their place in the queue. Absent means now; refused outside the last 7 days." }
      required: [locationId, guestName, partySize]
    WaitlistSeatRequest:
      type: object
      properties:
        tableId: { type: string }
        serverStaffId: { type: string, nullable: true }
      required: [tableId]
    WaitlistRemoveRequest:
      type: object
      properties:
        status: { type: string, default: CANCELLED, description: "CANCELLED or NOSHOW." }

    # ── Orders ──
    OrderDto:
      type: object
      properties:
        id: { type: string }
        transactionNumber: { type: string }
        locationId: { type: string }
        tableId: { type: string, nullable: true }
        customerId: { type: string, nullable: true }
        serverStaffId: { type: string, nullable: true }
        orderType: { type: string }
        status: { type: string }
        covers: { type: integer, nullable: true, description: "Party size on the check (V11); null when unknown (bar/takeaway)." }
        subtotalCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        openedAt: { type: integer, format: int64 }
        closedAt: { type: integer, format: int64, nullable: true }
        courseMode: { type: string, enum: [PARALLEL, MANUAL, SEQUENTIAL, HYBRID], default: PARALLEL, description: "V13 — how the order's courses reach the kitchen." }
        saleKind: { type: string, enum: [STANDARD, LAYBY], default: STANDARD, description: "V18 — laybys stay OPEN accumulating paidCents until settled." }
        activeCourse: { type: string, nullable: true, description: "Course currently on the pass (list route only); null when nothing is firing." }
        completedCourse: { type: string, nullable: true, description: "Last fully-bumped course (list route only)." }
        lastOrderAt: { type: integer, format: int64, nullable: true, description: "When the kitchen last got something for this order (list route only); null when nothing has been sent." }
        allServed: { type: boolean, default: false, description: "Every kitchen ticket for this order has been served (list route only)." }
        origin: { type: string, nullable: true, description: "\"QR\" for guest self-orders (V72), null/omitted for till-authored ones — so the POS can badge self-orders and show their paid state." }
        shareCode: { type: string, nullable: true, pattern: "^[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}$", description: "T-2.79 — the table bill's share code (one order's read only, never the list): guests enter it at the table's QR code (`X-Ruva-Bill-Code`) to open this bill and pay a share. The same code the opener's phone is shown; null when the order is not a table's bill to share, or its code has lapsed." }
        shareCodeWithheld: { type: boolean, default: false, description: "T-2.79 — a table's live bill whose code cannot be shown (its stored code was made under an earlier server key): shareCode is null and the till says so rather than show a code that opens nothing." }
        serviceChargeWaived: { type: boolean, default: false, description: "T-39.17 — the guest asked for the automatic service charge to come off this bill (POST /orders/{id}/service-charge). Every till, the guests' phones and checkout honour it." }
        billVatCents: { type: integer, format: int64, nullable: true, description: "An open bill's VAT as one document with its automatic service charge (D-218): what a presented bill prints beside a total carrying the charge. One order's read only; vatCents stays the header's, which carries none." }
      required: [id, transactionNumber, locationId, orderType, status, subtotalCents, discountCents, vatCents, tipCents, totalCents, paidCents, openedAt]
    OrderServiceChargeRequest:
      type: object
      description: "T-39.17 — only what is given changes; at least one is required (400 nothing_to_change)."
      properties:
        covers: { type: integer, nullable: true, minimum: 1, maximum: 999, description: "The bill's party size, which its automatic service charge is priced for. Outside 1..999, 400 invalid_covers." }
        waived: { type: boolean, nullable: true, description: "The guest opts out of the automatic service charge (true), or back in (false)." }
    OrderCreateRequest:
      type: object
      properties:
        locationId: { type: string }
        tableId: { type: string, nullable: true }
        customerId: { type: string, nullable: true }
        serverStaffId: { type: string, nullable: true }
        cashierStaffId: { type: string, nullable: true }
        orderType: { type: string, default: DINE_IN }
        notes: { type: string, nullable: true }
        deviceId: { type: string }
      required: [locationId, deviceId]
    OrderLineModifier:
      type: object
      properties:
        groupId: { type: string }
        optionId: { type: string }
        nameSnapshot: { type: string }
        priceDeltaCents: { type: integer, format: int64, description: "Not believed: the line is charged the catalogue's current figure for this option. An option this business does not offer (or has switched off, or in another group) is refused 400 unknown_modifier; one in a group the product does not carry 400 modifier_not_allowed; the same option twice 400 modifier_duplicate; two from a single-choice group 400 single_select_group (the guest's QR door judges options the same way)." }
      required: [groupId, optionId, nameSnapshot, priceDeltaCents]
    OrderLineRequest:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        nameSnapshot: { type: string }
        courseType: { type: string, default: MAIN }
        quantity: { type: integer, default: 1 }
        unitPriceCents: { type: integer, format: int64, description: "Fallback only — the server re-prices from the catalogue." }
        vatType: { type: string, default: STANDARD }
        modifiers: { type: array, items: { $ref: "#/components/schemas/OrderLineModifier" }, default: [] }
        discountCents: { type: integer, format: int64, default: 0, description: "Taken off this line. Never negative (400 discount_negative) and never above the line's goods, quantity times unit price plus modifiers (400 discount_above_gross) — and a product marked never discountable (a gift card, a deposit, a levy) has no goods to discount, so any discount on it is refused the same way (T-2.34). Above 0 it needs a manager: the caller when they are one, else the manager named in approverStaffId (400 discount_needs_manager). Recorded in the discount log against that manager." }
        note: { type: string, nullable: true }
        seatNumber: { type: integer, nullable: true, description: "1..N; null = shared (F-05)." }
        priceOverrideCents: { type: integer, format: int64, nullable: true, description: "A typed open price (T-3.4). Charged only for an open-price product with a manager named in approverStaffId; otherwise 400 open_price_needs_manager, price_not_open, open_price_not_positive or open_price_too_high." }
        approverStaffId: { type: string, nullable: true, description: "The manager who approved priceOverrideCents or discountCents; must be an active manager of this tenant. Named alone it is no approval for a caller who is not a manager (T-2.49): that caller sends discountApproval / openPriceApproval." }
        discountApproval: { type: string, nullable: true, description: "For a caller who is not a manager (T-2.49): the approval POST /staff/verify-manager-pin issued for this order, DISCOUNT and exactly discountCents, naming approverStaffId. Spent once. Missing, 400 manager_approval_needed; unknown, used, expired, for another order, kind or amount, or its approver no longer an active manager here, 400 manager_approval_not_valid." }
        openPriceApproval: { type: string, nullable: true, description: "As discountApproval, for priceOverrideCents as an OPEN_PRICE approval." }
      required: [productId, nameSnapshot, unitPriceCents]
    OrderLineDto:
      type: object
      properties:
        id: { type: string }
        productId: { type: string }
        name: { type: string }
        quantity: { type: integer }
        unitPriceCents: { type: integer, format: int64 }
        lineTotalCents: { type: integer, format: int64 }
        seatNumber: { type: integer, nullable: true, description: "1..N; null = shared (F-05)." }
        courseType: { type: string }
        note: { type: string, nullable: true }
        voided: { type: boolean }
        comped: { type: boolean }
        ageRestrictedYears: { type: integer, nullable: true, description: "T-37.1 - the age this line is sold from (its product's own, else its category's); null when none. A till asks for the age check by it before any tender." }
      required: [id, productId, name, quantity, unitPriceCents, lineTotalCents, courseType, voided, comped]
    OrderLinesResponse:
      type: object
      properties:
        orderId: { type: string }
        status: { type: string }
        subtotalCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/OrderLineDto" } }
        priceLevel: { type: string, nullable: true, description: "The price list pricing this order's lines now (T-3.4): its table's zone's, else the location's; null = the products' own prices." }
        guestTipCents: { type: integer, format: int64, default: 0, description: "T-37.2 — a guest's tip already on this open bill (an order added to the table with a tip). Checkout charges it, so the till collects it with the goods." }
        guestPayingCents: { type: integer, format: int64, default: 0, description: "T-41.29 — what guests are paying on this open bill on their phones right now (payments started within the last 15 minutes and not yet finished). The till asks before any tender: wait, or charge only what is left after it." }
        covers: { type: integer, nullable: true, description: "T-39.17 — the bill's party size, which the till prices its automatic service charge for (as checkout and the guests' phones do); null when none was given, so none is charged." }
        serviceChargeWaived: { type: boolean, default: false, description: "T-39.17 — the guest opted out of the automatic service charge on this bill." }
        saleKind: { type: string, default: STANDARD, description: "T-21.6 — the sale's kind (STANDARD, LAYBY, SPECIAL_ORDER or SERVICE_ORDER). A lay-by's, special order's or repair's bill is paid only through its own page, so a till offers no tender on one." }
        salesChannel: { type: string, nullable: true, enum: [TILL, QR, KIOSK], description: "The channel this bill's offers are priced on: QR or KIOSK for a bill a guest's phone or a kiosk opened, TILL for a till's own. A till bound to the bill prices its cart on it." }
      required: [orderId, status, subtotalCents, vatCents, discountCents, totalCents, paidCents, lines]
    OrderCustomerAttachRequest:
      type: object
      properties:
        customerId: { type: string }
      required: [customerId]
    PaymentLeg:
      type: object
      properties:
        method: { type: string, description: "A tender: CASH | YOCO_CARD | TAP_TO_PAY | CARD_TERMINAL | CARD | EFT | GIFT_CARD | HOUSE_ACCOUNT | STORE_CREDIT | ROOM_CHARGE | SNAPSCAN | ZAPPER (SASSA and VOUCHER only on an older till's sale). A counter door takes CASH, CARD, EFT or YOCO_CARD; a lay-by those and CARD_TERMINAL or TAP_TO_PAY; anything else there is 400 invalid_method." }
        amountCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64, default: 0 }
        tenderedCents: { type: integer, format: int64, nullable: true }
        providerReference: { type: string, nullable: true }
        last4: { type: string, nullable: true }
      required: [method, amountCents]
    CheckoutRequest:
      type: object
      properties:
        orderId: { type: string, description: "Must match the {id} path parameter." }
        payments: { type: array, items: { $ref: "#/components/schemas/PaymentLeg" } }
        tipCents: { type: integer, format: int64, default: 0 }
        tipStaffId: { type: string, nullable: true }
        serviceCharge: { type: string, enum: [NOT_OFFERED, AUTOMATIC, WAIVED], default: NOT_OFFERED, description: "The automatic service charge (T-3.4). A till settling a seated table sends AUTOMATIC, or WAIVED when the guest opted out; every other door leaves NOT_OFFERED." }
        expectedServiceChargeCents: { type: integer, format: int64, nullable: true, description: "The service charge the till showed. A different figure at checkout → 409 service_charge_changed." }
        ageCheck: { type: object, nullable: true, description: "T-37.1 - the cashier's confirmation that the buyer is of age (an alcohol line, or a product with its own age); `atMs` when. Asked once per sale. A sale with an age-restricted line and none is refused `409 age_check_required`, whose message names the age asked. The server stores it with the sale as surface TILL and the signed-in person as who confirmed, whatever `surface` and `staffId` say.", properties: { surface: { type: string, enum: [TILL, QR, KIOSK, ONLINE_STORE] }, staffId: { type: string, nullable: true }, atMs: { type: integer, format: int64, nullable: true } }, required: [surface] }
        roundingCents: { type: integer, format: int64, default: 0, description: "D-166 - the cash rounding the customer agreed to, recorded as the sale's own line; 0 (the default) is the exact amount. Checkout never rounds by itself. Only the 5c above or below what the cash pays (the bill less its non-cash legs and their tips, a tip left in cash included) is accepted; anything else is `400 invalid_rounding`, whose message says what may be agreed or to take the exact amount." }
      required: [orderId, payments]
    CheckoutResult:
      type: object
      properties:
        orderId: { type: string }
        transactionNumber: { type: string }
        subtotalCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        paymentIds: { type: array, items: { type: string } }
        journalEntryId: { type: string }
        serviceChargeCents: { type: integer, format: int64, description: "Inside totalCents, VAT included (T-3.4)." }
        roundingCents: { type: integer, format: int64, description: "The cash rounding the customer agreed to, inside totalCents (D-166); 0 for the exact amount." }
        beyondTheBillAsChangeCents: { type: integer, format: int64, description: "What the cash legs took beyond the bill, recorded as their change: hand it back. 0 when the legs came to the bill." }
        keptApartCents: { type: integer, format: int64, description: "What a card a terminal already approved took beyond the bill, kept apart for a refund (PAID_TWICE) and flagged: never charge it again. 0 when none." }
        kitchenTickets: { type: array, items: { $ref: "#/components/schemas/TicketRef" }, description: "The kitchen tickets this checkout sent (T-43.23): a Send a counter till held until the bill was paid, for the till to print by each station's print mode, as it prints a Send. Empty otherwise." }
      required: [orderId, transactionNumber, subtotalCents, vatCents, discountCents, tipCents, totalCents, paidCents, paymentIds, journalEntryId]
    FireRequest:
      type: object
      properties:
        course: { type: string, default: ALL, description: "STARTER | MAIN | DESSERT | DRINK | SIDE | ALL" }
        rush: { type: boolean, default: false }
        firedByStaffId: { type: string, nullable: true }
        station: { type: string, nullable: true, description: "Override; otherwise resolved per-product." }
    TicketRef:
      type: object
      properties:
        ticketId: { type: string }
        station: { type: string, nullable: true }
        items: { type: integer }
      required: [ticketId, items]
    StationMoveRequest:
      type: object
      properties:
        toStationId: { type: string, description: "A live station of this business that is not closed." }
        lineIds: { type: array, items: { type: string }, nullable: true, description: "The check lines (dishes) to move; omitted or null moves the whole ticket." }
        opId: { type: string, maxLength: 100, nullable: true, description: "Minted by the screen before it sends: a retry with the same id lands once. The server mints one when it is left out." }
      required: [toStationId]
    StationMoved:
      type: object
      properties:
        ticketId: { type: string }
        stationId: { type: string, nullable: true }
        station: { type: string, nullable: true }
        printerHost: { type: string, nullable: true }
        printerPort: { type: integer, nullable: true }
        printMode: { type: string, enum: [EVERY_TICKET, IF_SCREEN_MISSES, SCREEN_ONLY] }
        fallbackSeconds: { type: integer, nullable: true }
      required: [ticketId]
    StationMoveResult:
      type: object
      properties:
        applied: { type: boolean, description: "False when the op had already landed, or the dishes were already at the station." }
        tickets: { type: array, items: { $ref: "#/components/schemas/StationMoved" }, description: "The tickets that now hold what moved." }
      required: [applied, tickets]
    StationRedirectRequest:
      type: object
      properties:
        toStationId: { type: string, nullable: true, description: "Where the closed station's work goes; null reopens it." }
    StationRedirectResult:
      type: object
      properties:
        stationId: { type: string }
        redirectTo: { type: string, nullable: true }
        changed: { type: boolean, description: "False when the station already sent its work there: nothing was moved." }
        moved: { type: array, items: { $ref: "#/components/schemas/StationMoved" }, description: "Every open ticket the redirect carried to the landing station." }
      required: [stationId, changed, moved]
    FireResult:
      type: object
      properties:
        tickets: { type: array, items: { $ref: "#/components/schemas/TicketRef" } }
        itemCount: { type: integer }
      required: [tickets, itemCount]
    SplitRequest:
      type: object
      properties:
        orderId: { type: string, description: "Must match the {id} path parameter." }
        method: { type: string, description: "EVEN | BY_ITEM | BY_SEAT | CUSTOM" }
        guestCount: { type: integer, minimum: 2, maximum: 50 }
        itemAssignments: { type: object, additionalProperties: { type: integer }, nullable: true, description: "lineId → portion (1..guestCount). Required for BY_ITEM." }
        customAmounts: { type: array, items: { type: integer, format: int64 }, nullable: true, description: "Size = guestCount, cents per portion. Required for CUSTOM." }
      required: [orderId, method, guestCount]
    SplitPortion:
      type: object
      properties:
        portion: { type: integer }
        amountCents: { type: integer, format: int64 }
        lineIds: { type: array, items: { type: string }, default: [] }
      required: [portion, amountCents]
    SplitResult:
      type: object
      properties:
        splitId: { type: string }
        orderId: { type: string }
        method: { type: string }
        portions: { type: array, items: { $ref: "#/components/schemas/SplitPortion" } }
        totalCents: { type: integer, format: int64 }
      required: [splitId, orderId, method, portions, totalCents]
    VoidRequest:
      type: object
      properties:
        transactionId: { type: string }
        lineId: { type: string, nullable: true, description: "Omit to void the whole order." }
        reason: { type: string }
        approvedByStaffId: { type: string }
        approval: { type: string, nullable: true, description: "For a caller who is not a manager (T-2.49): the approval POST /staff/verify-manager-pin issued for this order, line, kind and amount (a VOID's amount is 0), naming approvedByStaffId; spent once. Missing, 400 manager_approval_needed; not valid, 400 manager_approval_not_valid. A manager's own call needs none." }
      required: [transactionId, reason, approvedByStaffId]
    WalkOutRequest:
      type: object
      properties:
        transactionId: { type: string }
        reasonCode: { type: string, description: "A code from GET /walk-outs/reasons." }
        note: { type: string, nullable: true, maxLength: 200, description: "Required when the reason says so." }
        id: { type: string, nullable: true, description: "Minted by the caller once; a retry carrying it closes the bill once." }
      required: [transactionId, reasonCode]
    WalkOutResult:
      type: object
      properties:
        id: { type: string }
        transactionId: { type: string }
        lossCents: { type: integer, format: int64, description: "What was owed and will not be paid: the bill's total." }
        replayed: { type: boolean, default: false }
      required: [id, transactionId, lossCents]
    WalkOutReason:
      type: object
      properties:
        code: { type: string }
        label: { type: string }
        requiresNote: { type: boolean, default: false }
      required: [code, label]
    CompRequest:
      type: object
      properties:
        transactionId: { type: string }
        lineId: { type: string }
        reason: { type: string }
        amountCents: { type: integer, format: int64 }
        approvedByStaffId: { type: string }
        approval: { type: string, nullable: true, description: "For a caller who is not a manager (T-2.49): the approval POST /staff/verify-manager-pin issued for this order, line, kind and amount (a VOID's amount is 0), naming approvedByStaffId; spent once. Missing, 400 manager_approval_needed; not valid, 400 manager_approval_not_valid. A manager's own call needs none." }
      required: [transactionId, lineId, reason, amountCents, approvedByStaffId]
    DiscountApplyRequest:
      type: object
      properties:
        transactionId: { type: string }
        lineId: { type: string, nullable: true }
        discountType: { type: string }
        value: { type: integer, format: int64 }
        amountCents: { type: integer, format: int64 }
        reasonCode: { type: string }
        reasonNote: { type: string, nullable: true }
        approvedByStaffId: { type: string, nullable: true }
        approval: { type: string, nullable: true, description: "For a caller who is not a manager (T-2.49): the approval POST /staff/verify-manager-pin issued for this order, line, kind and amount (a VOID's amount is 0), naming approvedByStaffId; spent once. Missing, 400 manager_approval_needed; not valid, 400 manager_approval_not_valid. A manager's own call needs none." }
      required: [transactionId, discountType, value, amountCents, reasonCode]

    # ── Kitchen ──
    KitchenItemDto:
      type: object
      properties:
        name: { type: string }
        quantity: { type: integer }
        note: { type: string, nullable: true }
        lineId: { type: string, nullable: true, description: "The check line this plate is (T-1.19); stable across voids and edits. Omitted on a ticket fired before lines carried it." }
        voidedAt: { type: integer, format: int64, nullable: true, description: "Epoch millis the line was voided after it was sent (T-1.19) — strike it, do not cook it. The line stays in `items`, so `doneIndexes` still point true. Omitted when not voided." }
        changedAt: { type: integer, format: int64, nullable: true, description: "Epoch millis the line was changed after it was sent (T-1.19): moved to another seat or course. Omitted when unchanged." }
        was: { type: string, nullable: true, description: "What a changed line was before (T-1.19): \"Seat 2\", \"Shared\", \"Course STARTER\"." }
        startAfterSec: { type: integer, nullable: true, minimum: 1, maximum: 7200, description: "Staggered fire (T-36.24): seconds after the ticket fired that this line should start, so it finishes with the longest dish of its course fired beside it (a drink is never held). Read against the ticket's own age; omitted when the line starts at once. The ticket's `targetSec` counts it: a held line is due at its wait plus its own prep." }
        sentBy: { type: string, nullable: true, description: "Who sent the line (T-1.19): the person signed in at the till that fired it, else the order's waiter. Omitted for a guest's own QR order." }
        alsoAt: { type: array, items: { type: string }, description: "The other stations that make their own copy of this line (T-36.3), by name: a dish sent to several stations is one item on each station's ticket, with the same lineId. Empty or omitted when only this station makes it." }
        check: { type: string, nullable: true, description: "The check the line is on when the bill was split by item or seat before sending (T-1.19), e.g. \"Check 2\"." }
      required: [name, quantity]
    KitchenTicketDto:
      type: object
      properties:
        id: { type: string }
        tableLabel: { type: string, nullable: true }
        courseType: { type: string }
        status: { type: string }
        rush: { type: boolean }
        firedAt: { type: integer, format: int64, description: "Epoch millis the ticket fired — clients can tick age locally." }
        elapsedSec: { type: integer, description: "Server-computed age ((now - firedAt)/1000) at response time." }
        server: { type: string, nullable: true }
        itemsSummary: { type: string, description: "Human-readable one-liner (back-compat); prefer `items`." }
        items:
          type: array
          items: { $ref: "#/components/schemas/KitchenItemDto" }
        station: { type: string, nullable: true, description: "Prep station display name (V12); legacy/fallback tickets carry a code: BAR | HOT | PASTRY | MAIN." }
        stationId: { type: string, nullable: true, description: "Resolved prep-station id (V12) — drives station filtering; null for legacy/fallback tickets." }
        transactionNumber: { type: string, nullable: true, description: "Snapshot from the backing transaction." }
        callNumber: { type: string, nullable: true, description: "The number an offline kiosk order gave its guest (\"F7\"); the ticket is called by it instead of the transaction number's sequence. Null for any other order." }
        orderType: { type: string, nullable: true, description: "DINE_IN | TAKEAWAY | BAR_TAB | ... from the backing transaction." }
        allergens: { type: array, items: { type: string } }
        fulfilmentType: { type: string, nullable: true, description: "Pickup indicator (V10): DINE_IN | TAKEAWAY. Null = eat-in." }
        scheduledForMillis: { type: integer, format: int64, nullable: true, description: "Scheduled pickup time (epoch millis) for a takeaway order-for-later; null = as-soon-as-ready." }
        covers: { type: integer, nullable: true, description: "Guest count on the check (V11); null when unknown (bar/takeaway)." }
        autoFired: { type: boolean, description: "Fired with no till behind it — SEQUENTIAL course auto-advance (V14), a guest's QR or kiosk order, a delivery or a course the kitchen fired (T-1.21). A kitchen screen prints these, claimed once through /kitchen/tickets/print-claims." }
        origin: { type: string, nullable: true, enum: [TILL, KIOSK, QR, DELIVERY], description: "Where the backing order was rung: TILL, KIOSK, a guest's own QR order (V72), or DELIVERY — a delivery platform's order (T-36.9). The KDS badges and filters by it. Omitted with no order behind the ticket." }
        deliveryPlatform: { type: string, nullable: true, description: "On a DELIVERY ticket: the platform as the venue named it on its delivery account (T-36.9). Omitted on every other channel." }
        deliveryRef: { type: string, nullable: true, description: "On a DELIVERY ticket: the platform's short reference for the order, the one on the bag. Omitted when the platform sent none." }
        deliveryExpectedAt: { type: integer, format: int64, nullable: true, description: "On a DELIVERY ticket: when the platform's driver is expected, epoch millis. Omitted when the platform did not say; never estimated." }
        readyAt: { type: integer, format: int64, nullable: true, description: "When the pass first had the food (V15): set by /ready, backfilled by bump/serve. Omitted when null." }
        bumpedAt: { type: integer, format: int64, nullable: true, description: "When the kitchen bumped it. Omitted when null." }
        servedAt: { type: integer, format: int64, nullable: true, description: "When the floor confirmed delivery (V15). Null/omitted = still to run." }
        calledAt: { type: integer, format: int64, nullable: true, description: "When an expo or pass called the order (V271, T-36.5). Omitted until it has; where a location has no expo, nothing ever sets it." }
        seenAt: { type: integer, format: int64, nullable: true, description: "When a kitchen screen first showed the ticket (V128, T-5.6). Omitted until one has; the till says Not seen yet of a fired line whose ticket has none after half a minute (T-25.2)." }
        itemReadyAt: { type: object, additionalProperties: { type: integer, format: int64 }, description: "Items marked ready at the pass before the ticket was (V279, T-36.16): item position (as text) to when it was first marked. Once the ticket is ready every item is. Omitted when none." }
        arrivedAt: { type: integer, format: int64, nullable: true, description: "When the order's takeaway guest said they had arrived (V278, T-36.23); the same on every ticket of the order. Omitted until they have." }
        arrivalNote: { type: string, nullable: true, description: "The short note they left with it (\"blue Polo, bay 4\"); the guest's words, shown on the kitchen's own screens only." }
        doneIndexes: { type: array, items: { type: integer }, description: "Shared per-item prep ticks (V15) — indexes into `items`. Omitted when empty." }
        heldCourse: { type: string, nullable: true, enum: [STARTER, MAIN, SIDE, DESSERT], description: "The food course this ticket's paced (SEQUENTIAL or HYBRID), still-open order is holding back — what `/fire-next` would send (T-5.4). Omitted when nothing is held." }
        transactionId: { type: string, description: "The check the ticket was fired from (T-5.7). A till keeps its own copy of the board under it, so the pass survives the line dropping." }
        round: { type: integer, nullable: true, description: "Which send of its order this ticket is (T-1.19): 1, 2, 3…; every station's ticket from one send shares it, and a repeat delivery of an offline ticket keeps it. Omitted on tickets fired before it was recorded." }
        addedToOpenOrder: { type: boolean, description: "True from round 2 on: more food for an order already in the kitchen (\"Round 2 · added to T7\")." }
        orderProgress:
          description: >
            How far each station is with this ticket's order (T-36.6), in the same answer as the ticket so the pass asks nothing per
            order. Present on the `board` and `expo` views, over EVERY station's tickets of the order (not only the ones the screen is
            set to); the LAN hub carries it too, so it works offline. Absent on the `recall` view and from an older server.
          allOf: [ { $ref: "#/components/schemas/OrderProgress" } ]
        payAtCounter: { type: boolean, description: "True while the ticket's order waits to be paid at the counter (T-41.112): a guest's order at a venue with no till whose location takes payment at the counter, sent to the kitchen unpaid. False once the counter takes it (the boards hear `kitchen.ticket_changed`), and for a phone tab, an order paid on a phone and any till venue's order. Omitted when false. Never on the Ready to collect TV's answer." }
      required: [id, courseType, status, rush, firedAt, elapsedSec, itemsSummary]
    StationProgress:
      type: object
      properties:
        station: { type: string, nullable: true }
        stationId: { type: string, nullable: true }
        tickets: { type: integer, description: "This station's tickets for the order." }
        ticketsDone: { type: integer, description: "Of those, how many reached the pass (READY or later), were served, or had every line voided." }
        ticketsBumped: { type: integer, description: "Of those, how many the kitchen has bumped off its board, or were served (T-36.6)." }
        items: { type: integer, description: "Lines this station makes for the order, a voided line left out (T-36.6)." }
        itemsDone: { type: integer, description: "Of those, how many are ticked or made; every line of a ticket that reached the pass counts (T-36.6)." }
        complete: { type: boolean }
      required: [tickets, ticketsDone, complete]
    OrderProgress:
      type: object
      properties:
        orderId: { type: string }
        stations:
          type: array
          description: Every station with a ticket for the order, unfinished first.
          items: { $ref: "#/components/schemas/StationProgress" }
        stationsDone: { type: integer }
        stationsTotal: { type: integer }
        allDone: { type: boolean, description: "Every station is done; false for an order with no ticket." }
      required: [orderId, stations, stationsDone, stationsTotal, allDone]

    # ── Tabs ──
    TabDto:
      type: object
      properties:
        id: { type: string }
        label: { type: string }
        transactionId: { type: string }
        status: { type: string }
        openedAt: { type: integer, format: int64 }
        customerId: { type: string, nullable: true }
        preauthAmountCents: { type: integer, format: int64, nullable: true }
      required: [id, label, transactionId, status, openedAt]
    TabOpenRequest:
      type: object
      properties:
        locationId: { type: string }
        label: { type: string }
        customerId: { type: string, nullable: true }
        customerPhone: { type: string, nullable: true }
        serverStaffId: { type: string, nullable: true }
        orderType: { type: string, default: BAR_TAB }
        deviceId: { type: string }
        tabId:
          type: string
          pattern: '^[A-Za-z0-9_-]{8,64}$'
          description: The id the client minted for this tab, sent on the first attempt and every retry. A retry of the same open is answered with the tab it opened; a different open under the same id is 409 id_conflict.
      required: [locationId, label, deviceId]
    TabPreauthRequest:
      type: object
      properties:
        amountCents: { type: integer, format: int64 }
        yocoCheckoutId: { type: string, nullable: true }
      required: [amountCents]
    TabSettleRequest:
      type: object
      properties:
        payments: { type: array, items: { $ref: "#/components/schemas/PaymentLeg" } }
        tipCents: { type: integer, format: int64, default: 0 }
        serviceCharge: { type: string, enum: [NOT_OFFERED, AUTOMATIC, WAIVED], default: NOT_OFFERED, description: "As on CheckoutRequest (FD-73)." }
        expectedServiceChargeCents: { type: integer, format: int64, nullable: true, description: "The service charge the till showed; a different figure → 409 service_charge_changed." }
        ageCheck: { type: object, nullable: true, description: "T-37.1 - the cashier's confirmation that the buyer is of age (an alcohol line, or a product with its own age); `atMs` when. Asked once per sale. A sale with an age-restricted line and none is refused `409 age_check_required`, whose message names the age asked. The server stores it with the sale as surface TILL and the signed-in person as who confirmed, whatever `surface` and `staffId` say.", properties: { surface: { type: string, enum: [TILL, QR, KIOSK, ONLINE_STORE] }, staffId: { type: string, nullable: true }, atMs: { type: integer, format: int64, nullable: true } }, required: [surface] }
      required: [payments]

    # ── Payments / Refunds ──
    PaymentRequest:
      type: object
      properties:
        transactionId: { type: string }
        method: { type: string, description: "YOCO_CARD | CASH | EFT | SASSA | SNAPSCAN | ZAPPER | VOUCHER" }
        amountCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64, default: 0 }
        tenderedCents: { type: integer, format: int64, nullable: true }
        providerReference: { type: string, nullable: true }
        last4: { type: string, nullable: true }
        idempotencyKey: { type: string, nullable: true, description: "Client-generated key; a retried request with the same key replays the first result instead of charging twice." }
      required: [transactionId, method, amountCents]
    PaymentResponse:
      type: object
      properties:
        paymentId: { type: string }
        status: { type: string }
        providerReference: { type: string, nullable: true }
        checkoutUrl: { type: string, nullable: true, description: "Yoco — URL the cashier must redirect to." }
        qrPayload: { type: string, nullable: true, description: "SnapScan / Zapper QR string." }
        expiresAt: { type: integer, format: int64, nullable: true }
        receiptUrl: { type: string, nullable: true, description: "Signed public digital-receipt link, set once captured." }
      required: [paymentId, status]
    BillPayLinkResponse:
      type: object
      properties:
        payUrl: { type: string, nullable: true, description: "The guest pay page of the table bill, its share code in the fragment; null when no QR should print." }
    ReceiptLinkResponse:
      type: object
      properties:
        transactionNumber: { type: string, description: "The number the server holds for this sale." }
        url: { type: string, description: "Signed public digital-receipt link." }
      required: [transactionNumber, url]
    RefundRequest:
      type: object
      properties:
        transactionId: { type: string }
        amountCents: { type: integer, format: int64, nullable: true, description: "Omit for a full refund." }
        reason: { type: string }
        staffId: { type: string, description: "Who is refunding: a cash refund comes out of their open register when it is at the sale's location, none when it is at another (T-41.39). The back office sends none." }
        toStoreCredit: { type: boolean, default: false, description: "V18: skip the provider and credit the sale's customer instead (400 store_credit_needs_customer when none attached)." }
        refundId: { type: string, maxLength: 64, nullable: true, description: "Minted by the client before its first attempt. Sent again, it answers the refund already made (`replayed: true`) instead of making a second." }
        creditedAtHotel: { type: boolean, default: false, description: "The hotel's reception already credited the guest's folio by hand: the ROOM_CHARGE leg is recorded and no credit is sent. Only for a sale whose room charge Ruva does not hold (a walk-in from a till before T-2.38); 409 room_credited_by_ruva where it does, 400 invalid_hotel_credit for a sale not charged to a room." }
      required: [transactionId, reason, staffId]
    SalesOrderRow:
      type: object
      properties:
        id: { type: string }
        number: { type: string }
        openedAt: { type: integer, format: int64 }
        closedAt: { type: integer, format: int64, nullable: true }
        tableName: { type: string, nullable: true }
        orderType: { type: string }
        channel: { type: string, enum: [QR, KIOSK, TILL], description: "Where the order came in: a guest's own phone, a self-order kiosk, or the till. A client should read a word it does not know as TILL." }
        itemCount: { type: integer }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64, description: "Captured payments, tips included." }
        refundedCents: { type: integer, format: int64 }
        standing: { type: string, enum: [OPEN, NEEDS_ATTENTION, PAID, PART_REFUNDED, REFUNDED, VOIDED, AT_COUNTER, UNPAID, PAID_TWICE], description: "AT_COUNTER (T-1.20) is a guest's order waiting to be paid at the counter, placed today; UNPAID is the same from an earlier trading day. PAID_TWICE (T-30.14) is an order a guest's payment reached after it was paid another way or voided: the money is recorded, not added to the bill, and owed back to the guest until its refund check is answered." }
        heldRefundCents:
          type: integer
          format: int64
          description: >-
            What Yoco reports it refunded on this order and Ruva has not booked (refused here, or held because it may be
            one of Ruva's own); such an order is listed under the `attention` filter. Never refund it again here.
        unpaidRefundCents:
          type: integer
          format: int64
          description: >-
            What Yoco did not pay or confirm of Ruva's own refunds of this order (failed or refused — already taken back off
            the books — or never confirmed); such an order is listed under the `attention` filter until its refund checks are answered.
        paidTwiceCents:
          type: integer
          format: int64
          default: 0
          description: >-
            A guest's payment taken after this order was paid another way or voided (payment status PAID_TWICE): never part of
            `paidCents`, owed back to the guest; listed under `attention` until its refund check ("Refunded to the guest") is answered.
      required: [id, number, openedAt, orderType, channel, itemCount, totalCents, paidCents, refundedCents, standing]
    CounterPaymentRequest:
      type: object
      properties:
        method: { type: string, enum: [CASH, COUNTER_CARD, COUNTER_EFT] }
        expectedTotalCents: { type: integer, format: int64, description: "What the desk showed as to be taken (`CounterOrder.toTakeCents`); a different figure now is `409 order_total_changed` and nothing is booked." }
        roundingCents: { type: integer, format: int64, default: 0, description: "D-166 - the cash rounding the customer agreed to, one of `CounterOrder.cashRounding`; 0 takes the exact amount. Anything else, or any rounding by card or EFT, is `400 invalid_rounding`." }
      required: [method, expectedTotalCents]
    CounterBankRequest:
      type: object
      properties:
        id: { type: string, maxLength: 64, description: "Minted once per attempt, so a retry is the same banking." }
        locationId: { type: string }
      required: [id, locationId]
    CounterOrder:
      type: object
      properties:
        id: { type: string }
        number: { type: string }
        locationId: { type: string }
        openedAt: { type: integer, format: int64 }
        tableName: { type: string, nullable: true }
        itemCount: { type: integer }
        totalCents: { type: integer, format: int64, description: "The bill, the whole of it." }
        pastTradingDay: { type: boolean, default: false }
        tabName: { type: string, nullable: true, description: "A guest's phone tab (T-30.14): the name it was opened under; null for any other order." }
        tabPhone: { type: string, nullable: true, description: "The phone number it was opened under (E.164), to ring when it is left unpaid; masked to its last three digits for a caller without SETTLE_COUNTER_ORDER." }
        paidCents: { type: integer, format: int64, default: 0, description: "What guests already paid of a phone tab on their phones; the counter takes `totalCents - paidCents` (T-30.14)." }
        held: { allOf: [{ $ref: "#/components/schemas/HeldPayment" }], nullable: true, description: "A payment started on a guest's phone and not finished, holding the order (T-30.14); null when none is." }
        cashRounding: { type: object, nullable: true, description: "D-166 - the cash roundings the customer may agree to on `totalCents - paidCents` (what the desk takes, a guest's tip included): `upCents` to the 5c above, `downCents` (negative) to the 5c below. Null when there is nothing to round. The desk asks the exact amount and offers these only on the customer's agreement.", properties: { upCents: { type: integer, format: int64 }, downCents: { type: integer, format: int64 } }, required: [upCents, downCents] }
      required: [id, number, locationId, openedAt, itemCount, totalCents]
    HeldPayment:
      type: object
      properties:
        paymentId: { type: string }
        amountCents: { type: integer, format: int64, description: "What the guest was asked for, tip included." }
        method: { type: string, enum: [YOCO_CARD, PAYFAST, SNAPSCAN] }
        startedAt: { type: integer, format: int64 }
        mayAskNow: { type: boolean, description: "Whether `check-payment` asks the provider yet (15 minutes after it was started)." }
        words: { type: string, description: "The desk's sentence about it." }
      required: [paymentId, amountCents, method, startedAt, mayAskNow, words]
    PaymentCheckAnswer:
      type: object
      properties:
        outcome: { type: string, enum: [CAPTURED, RELEASED, MOVED] }
        words: { type: string }
      required: [outcome, words]
    CounterCash:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
        recordedCents: { type: integer, format: int64, description: "Cash the counter recorded." }
        bankedCents: { type: integer, format: int64, description: "Of it, what was marked banked." }
        refundedCents: { type: integer, format: int64, default: 0, description: "Of it, what was paid back to guests in cash (read from the refunds' journals on cash on hand). Not yet banked = recorded − refunded − banked." }
      required: [locationId, locationName, recordedCents, bankedCents]
    CounterDesk:
      type: object
      properties:
        orders: { type: array, items: { $ref: "#/components/schemas/CounterOrder" } }
        cash: { type: array, items: { $ref: "#/components/schemas/CounterCash" } }
        mayAct: { type: boolean, default: false, description: "The caller holds SETTLE_COUNTER_ORDER." }
        paidTwice:
          type: array
          description: Guests' payments taken after their order was paid another way or voided, not yet refunded (T-30.14), oldest first.
          items:
            type: object
            properties:
              orderId: { type: string }
              number: { type: string }
              paymentId: { type: string }
              amountCents: { type: integer, format: int64 }
              method: { type: string, description: "YOCO_CARD, PAYFAST or SNAPSCAN." }
              words: { type: string, description: "The sentence the desk shows: what to refund, and how to say it was." }
            required: [orderId, number, paymentId, amountCents, method, words]
    SalesOrderPage:
      type: object
      properties:
        rows: { type: array, items: { $ref: "#/components/schemas/SalesOrderRow" } }
        nextCursor: { type: string, nullable: true }
        counts:
          type: object
          properties:
            all: { type: integer }
            paid: { type: integer }
            open: { type: integer }
            attention: { type: integer }
            refunded: { type: integer }
            notClosed: { type: integer, description: "Of attention, paid orders that did not close." }
            paidTwice: { type: integer, description: "Of attention and not notClosed, orders a guest paid twice; the rest have a refund to check." }
      required: [rows, counts]
    SalesOrderDetail:
      type: object
      properties:
        order: { $ref: "#/components/schemas/SalesOrderRow" }
        lines:
          type: array
          items:
            type: object
            properties:
              name: { type: string }
              quantity: { type: integer }
              lineTotalCents: { type: integer, format: int64 }
              voided: { type: boolean }
              comped: { type: boolean }
        payments:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              method: { type: string }
              amountCents: { type: integer, format: int64 }
              tipCents: { type: integer, format: int64 }
              status: { type: string }
              at: { type: integer, format: int64 }
        refunds:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              number: { type: string }
              amountCents: { type: integer, format: int64 }
              at: { type: integer, format: int64 }
              reason: { type: string, nullable: true }
        subtotalCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64 }
        roundingCents: { type: integer, format: int64, default: 0, description: "A cash rounding the customer agreed to (D-166), inside the order's total; 0 for the exact amount." }
        receiptUrl: { type: string, nullable: true, description: "The guest's signed receipt link; null while the order is open, and for a caller without TILL_SELL (who may not mint one at the till either)." }
        refundChecks:
          type: array
          description: What a person must still check about this order's refunds, oldest first; answered by `POST /sales/orders/{id}/refund-checks`.
          items:
            type: object
            properties:
              id: { type: string }
              amountCents: { type: integer, format: int64 }
              message: { type: string, description: "What happened." }
              remedy: { type: string, description: "What to do." }
              answers:
                type: array
                items:
                  type: object
                  properties:
                    code: { type: string, enum: [PAID_CASH, PAID_EFT, REFUNDED_AGAIN, YOCO_PAID, YOCO_DID_NOT_PAY, RECORD, CHECKED, PAYS_BACK] }
                    label: { type: string }
                  required: [code, label]
            required: [id, amountCents, message, remedy, answers]
        cancellable: { type: boolean, default: false, description: "A guest's order waiting only on a payment started on their phone, nothing taken (D-208): `POST /sales/orders/{id}/cancel` may cancel it. Worked out by the server." }
      required: [order, lines, payments, refunds, subtotalCents, discountCents, vatCents, tipCents]
    ProviderRefund:
      type: object
      properties:
        paymentId: { type: string }
        method: { type: string }
        providerRefundId: { type: string, nullable: true }
        status:
          type: string
          description: |
            The provider's own (`succeeded`, `pending`); `MANUAL` (a person pays it back: cash, EFT, SnapScan, a card with no
            provider call — a card machine says "Refund it on the card machine."); `STORE_CREDIT`;
            `UNCONFIRMED` (sent to Yoco, no answer to trust — booked like `pending`, check Yoco before refunding again);
            `FAILED` (refused outright). This is the status when the refund was made: Yoco's later `refund.succeeded` /
            `refund.failed` for a `pending` or `UNCONFIRMED` leg is read back into the order's `refundChecks`, not here.
        note: { type: string, nullable: true, description: "What a person must still do for this leg." }
      required: [paymentId, method, status]
    RefundResult:
      type: object
      properties:
        refundTransactionId: { type: string }
        refundNumber: { type: string }
        amountCents: { type: integer, format: int64 }
        providerRefunds: { type: array, items: { $ref: "#/components/schemas/ProviderRefund" } }
        journalEntryId: { type: string }
        originalStatus: { type: string }
        exchangeAppliedCents: { type: integer, format: int64, default: 0 }
        toTenderCents: { type: integer, format: int64, default: 0 }
        toStoreCreditCents: { type: integer, format: int64, default: 0 }
        exchangeOrderId: { type: string, nullable: true }
        exchangeDueCents: { type: integer, format: int64, default: 0 }
        exchangeSettled: { type: boolean, default: false }
        replayed: { type: boolean, default: false, description: "An earlier refund under the same refundId, answered again with the same legs." }
        notice: { type: string, nullable: true, description: "The legs' notes as one sentence; null when nothing more is needed." }
      required: [refundTransactionId, refundNumber, amountCents, providerRefunds, journalEntryId, originalStatus]
    ReturnLineRequest:
      type: object
      properties:
        lineId: { type: string, description: "A line of the original sale." }
        quantity: { type: integer, description: "Units coming back, at least 1 and no more than are still out." }
        disposition: { type: string, enum: [RESTOCK, WRITE_OFF], default: RESTOCK }
      required: [lineId, quantity]
    ReturnRequest:
      type: object
      properties:
        returnId: { type: string, description: "Minted by the caller; the same id again answers the same return." }
        originalTransactionId: { type: string }
        lines: { type: array, items: { $ref: "#/components/schemas/ReturnLineRequest" } }
        reasonCode: { type: string, enum: [CHANGED_MIND, FAULTY, WRONG_ITEM, NOT_AS_DESCRIBED, DAMAGED, OTHER] }
        note: { type: string, nullable: true, description: "Required with OTHER." }
        refundTo: { type: string, enum: [ORIGINAL, STORE_CREDIT], default: ORIGINAL }
        exchangeOrderId: { type: string, nullable: true, description: "An open order holding the replacement items." }
        staffId: { type: string, nullable: true, description: "Who is taking the return: cash given back comes out of their open register when it is at the sale's location, none when it is at another (T-41.39)." }
      required: [returnId, originalTransactionId, lines, reasonCode]
    ReturnProviderRefund:
      type: object
      properties:
        paymentId: { type: string }
        method: { type: string }
        status: { type: string, description: "e.g. succeeded, MANUAL (cash or a portal refund), STORE_CREDIT, RESTORED (back on the gift card, store credit or house account it came from), NOT_OWED (the part of a gift card's or store credit's share the balance never gave the sale: nothing is owed for it, T-21.7), FAILED. A gift card or store-credit leg partly restored is two entries for one payment." }
        note: { type: string, nullable: true, description: "The sentence for the person at the till: where a stored-value share went, or why part of it went nowhere." }
        amountCents: { type: integer, format: int64, nullable: true, description: "This entry's part of the refund; absent from an older server." }
      required: [paymentId, method, status]
    ReturnResult:
      type: object
      properties:
        refundTransactionId: { type: string }
        refundNumber: { type: string }
        refundCents: { type: integer, format: int64, description: "The return's whole value." }
        exchangeAppliedCents: { type: integer, format: int64, default: 0 }
        toTenderCents: { type: integer, format: int64, default: 0 }
        toStoreCreditCents: { type: integer, format: int64, default: 0 }
        exchangeOrderId: { type: string, nullable: true }
        exchangeDueCents: { type: integer, format: int64, default: 0, description: "What the customer still pays on the exchange order." }
        exchangeSettled: { type: boolean, default: false }
        providerRefunds: { type: array, items: { $ref: "#/components/schemas/ReturnProviderRefund" } }
        replayed: { type: boolean, default: false }
      required: [refundTransactionId, refundNumber, refundCents]
    ReturnableSale:
      type: object
      properties:
        transactionId: { type: string }
        transactionNumber: { type: string }
        status: { type: string }
        closedAt: { type: integer, format: int64, nullable: true }
        customerId: { type: string, nullable: true }
        customerName: { type: string, nullable: true }
        totalCents: { type: integer, format: int64 }
        refundedCents: { type: integer, format: int64, description: "What earlier refunds of this sale gave back." }
        lines: { type: array, items: { $ref: "#/components/schemas/ReturnableLine" } }
        payments: { type: array, items: { $ref: "#/components/schemas/ReturnablePayment" } }
      required: [transactionId, transactionNumber, status, totalCents, refundedCents, lines]
    ReturnableLine:
      type: object
      properties:
        lineId: { type: string }
        productId: { type: string }
        name: { type: string }
        quantity: { type: integer }
        returnedQuantity: { type: integer }
        lineValueCents: { type: integer, format: int64, description: "The line's worth after the order discount." }
        voided: { type: boolean, default: false }
      required: [lineId, productId, name, quantity, returnedQuantity, lineValueCents]
    ReturnablePayment:
      type: object
      properties:
        method: { type: string }
        amountCents: { type: integer, format: int64 }
      required: [method, amountCents]

    # ── Webhooks ──
    WebhookAck:
      type: object
      properties:
        received: { type: boolean, default: true }
        eventId: { type: string, nullable: true }

    # ── Sync ──
    SyncMutation:
      type: object
      properties:
        id: { type: string }
        entityType: { type: string }
        entityId: { type: string }
        operation: { type: string }
        payloadJson: { type: string, description: "JSON-encoded entity payload." }
        deviceId: { type: string }
        enqueuedAt: { type: integer, format: int64 }
      required: [id, entityType, entityId, operation, payloadJson, deviceId, enqueuedAt]
    SyncPushRequest:
      type: object
      properties:
        mutations: { type: array, items: { $ref: "#/components/schemas/SyncMutation" } }
      required: [mutations]
    SyncResult:
      type: object
      properties:
        id: { type: string }
        accepted: { type: boolean }
        error: { type: string, nullable: true }
      required: [id, accepted]
    SyncPushResponse:
      type: object
      properties:
        results: { type: array, items: { $ref: "#/components/schemas/SyncResult" } }
      required: [results]
    SyncEntity:
      type: object
      properties:
        entityType: { type: string }
        entityId: { type: string }
        payloadJson: { type: string }
        syncVersion: { type: integer, format: int64 }
      required: [entityType, entityId, payloadJson, syncVersion]
    SyncPullResponse:
      type: object
      properties:
        entities: { type: array, items: { $ref: "#/components/schemas/SyncEntity" }, default: [] }
        nextCursor: { type: integer, format: int64 }
        staffDigest: { type: string, nullable: true, description: "The staff rows as this puller is sent them, digested; sent back as `staffDigest`, an unchanged staff table is not re-sent (T-2.21)." }
        guestTypes: { type: array, items: { type: string }, nullable: true, description: "The guest types this puller is sent (T-1.27); a till keeps no other." }
        pinPadClosed: { type: string, nullable: true, enum: [device_not_registered], description: "Why this person's PIN pad was sent no PIN hash (T-22.3 round 3, P2-4): `device_not_registered` where the device's location has \"registered devices only\" on and the device, held by a person who is not a manager, is not registered. The till says so on its pad and counts no PIN. Absent when the pad is open." }
      required: [nextCursor]
    SyncQueueCount:
      type: object
      properties:
        pending: { type: integer }
        failed: { type: integer }
      required: [pending, failed]

    # ── Reports ──
    HourlyBucket:
      type: object
      properties:
        hour: { type: integer }
        revenueCents: { type: integer, format: int64 }
        ordersCount: { type: integer }
      required: [hour, revenueCents, ordersCount]
    TopProduct:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        quantity: { type: integer }
        revenueCents: { type: integer, format: int64 }
      required: [productId, name, quantity, revenueCents]
    DashboardReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        revenueCents: { type: integer, format: int64 }
        coversCount: { type: integer }
        averageCheckCents: { type: integer, format: int64 }
        tipsCents: { type: integer, format: int64 }
        activeTables: { type: integer }
        hourlyRevenue: { type: array, items: { $ref: "#/components/schemas/HourlyBucket" } }
        paymentMix: { type: object, additionalProperties: { type: integer, format: int64 } }
        topProducts: { type: array, items: { $ref: "#/components/schemas/TopProduct" } }
        netSalesCents: { type: integer, format: int64, description: "Sales less their VAT (T-14.2)." }
        vatCents: { type: integer, format: int64 }
        refundsCents: { type: integer, format: int64, description: "Refunds made in the period, already off revenueCents." }
        salesDefinition: { type: string }
        previous: { $ref: "#/components/schemas/DashboardComparison" }
        weekBefore: { $ref: "#/components/schemas/DashboardComparison" }
      required: [periodStart, periodEnd, revenueCents, coversCount, averageCheckCents, tipsCents, activeTables, hourlyRevenue, paymentMix, topProducts]
    DashboardComparison:
      type: object
      description: "A period set beside the dashboard's, totalled the same way: `previous` is the same-length period just before it, `weekBefore` the same window a week earlier (the same day last week, on a day's dashboard). Each carries the change on each figure in basis points of the earlier one (T-14.2, T-4.11). A change is absent or null when the earlier figure was nil."
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        revenueCents: { type: integer, format: int64 }
        coversCount: { type: integer }
        averageCheckCents: { type: integer, format: int64 }
        tipsCents: { type: integer, format: int64 }
        revenueChangeBp: { type: integer, format: int64, nullable: true }
        coversChangeBp: { type: integer, format: int64, nullable: true }
        averageCheckChangeBp: { type: integer, format: int64, nullable: true }
        tipsChangeBp: { type: integer, format: int64, nullable: true }
        hourlyRevenue: { type: array, description: "That period's sales and order count for each hour of the day (0-23), the same shape as the dashboard's own hourlyRevenue, so a client can draw one over the other.", items: { $ref: "#/components/schemas/HourlyBucket" } }
        totalledUntil: { type: integer, format: int64, description: "Where the totals and changes stop. While the dashboard's period is still running it is the same moment of this period as now (at 11:00 today, last week's day up to 11:00), so a day is never set against a whole one; otherwise periodEnd. hourlyRevenue always covers the whole period (T-41.11)." }
      required: [periodStart, periodEnd, revenueCents, coversCount, averageCheckCents, tipsCents]
    XReport:
      type: object
      properties:
        shiftId: { type: string }
        openedAt: { type: integer, format: int64 }
        asOf: { type: integer, format: int64 }
        locked: { type: boolean, default: false }
        ordersCount: { type: integer }
        grossCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        discountsCents: { type: integer, format: int64 }
        refundsCents: { type: integer, format: int64 }
        cashRefundsCents: { type: integer, format: int64, nullable: true, default: 0, description: "T-41.39 - cash handed back by refunds made at this register, whichever register rang the sale (`refundsCents` is the refunds of this register's sales); expectedCashCents is less it. Withheld — absent — with expectedCashCents." }
        voidsCents: { type: integer, format: int64 }
        compsCents: { type: integer, format: int64 }
        tipsCents: { type: integer, format: int64 }
        paymentMix: { type: object, additionalProperties: { type: integer, format: int64 } }
        openingFloatCents: { type: integer, format: int64, default: 0 }
        paidInCents: { type: integer, format: int64, default: 0 }
        paidOutCents: { type: integer, format: int64, default: 0 }
        expectedCashCents: { type: integer, format: int64, nullable: true, description: "openingFloat + cash sales + agreed cash rounding + paid-in − paid-out − cash refunds. Withheld — absent — when the venue closes by blind count and the caller is not a manager. The CASH entry of paymentMix is withheld with it." }
        cashRoundingCents: { type: integer, format: int64, nullable: true, default: 0, description: "The cash roundings customers agreed to on this register's cash sales (D-166; 0 when none was — the drawer then expects the exact cash). Each sale records its rounding once, on the drawer of its last cash leg. Withheld — absent — with expectedCashCents." }
        blind: { type: boolean, default: false, description: "True when a blind count withheld this report's cash figures from the caller (V95 locations.blindCashCount)." }
        netSalesCents: { type: integer, format: int64, description: "Sales less refunds less VAT (T-14.2); grossCents is sales as rung, tips not included." }
        salesDefinition: { type: string }
        walkOutsCents: { type: integer, format: int64, default: 0, description: "Bills closed because the guest left without paying (T-37.5), at what was owed: a loss, apart from voidsCents and in no sales figure." }
      required: [shiftId, openedAt, asOf, ordersCount, grossCents, vatCents, discountsCents, refundsCents, voidsCents, compsCents, tipsCents, paymentMix]
    ZReportRequest:
      type: object
      properties:
        shiftId: { type: string }
        closingFloatCents: { type: integer, format: int64 }
        approverStaffId: { type: string }
        countedBreakdownJson: { type: string, nullable: true, description: "Denomination count at close — JSON map of denomination-cents to qty, e.g. {\"20000\":3}" }
      required: [shiftId, closingFloatCents, approverStaffId]
    CashMovementRequest:
      type: object
      properties:
        movementType: { type: string, enum: [PAID_IN, PAID_OUT, NO_SALE] }
        amountCents: { type: integer, format: int64, default: 0, description: "Positive; must be 0 for NO_SALE, >0 otherwise" }
        reason: { type: string }
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true, description: "Defaults to the shift's staffer" }
        id: { type: string, nullable: true, description: "Client-minted movement id; a repeat answers with the movement already recorded (T-3.2). Never one starting `cash-refund-` (400 invalid_movement_id)." }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When it happened on the till (server time, ms); within the last 7 days. Absent = now." }
        approverStaffId: { type: string, nullable: true, description: "A NO_SALE by anyone who is not a manager (T-2.49): the manager the approval names." }
        approval: { type: string, nullable: true, description: "A NO_SALE by anyone who is not a manager (T-2.49): the NO_SALE approval POST /staff/verify-manager-pin issued, spent once with the movement by the user and device that asked for it. Missing, 400 manager_approval_needed; not valid, 400 manager_approval_not_valid. A queued no-sale whose approval was standing when the drawer opened but lapsed before it landed is recorded and flagged (audit cash_movement.no_sale_approved_late), not refused." }
      required: [movementType, reason]
    CashMovementDto:
      type: object
      properties:
        id: { type: string }
        shiftId: { type: string }
        locationId: { type: string }
        staffId: { type: string, nullable: true }
        movementType: { type: string, enum: [PAID_IN, PAID_OUT, NO_SALE, CASH_REFUND], description: "CASH_REFUND (T-41.39): cash a refund handed back at this register; `reason` is the refund's number, `note` its reason." }
        amountCents: { type: integer, format: int64 }
        reason: { type: string }
        note: { type: string, nullable: true }
        occurredAt: { type: integer, format: int64 }
      required: [id, shiftId, locationId, movementType, amountCents, reason, occurredAt]
    LaybyPolicyDto:
      type: object
      properties:
        minDepositBp: { type: integer, minimum: 0, maximum: 9000, default: 0, description: "Smallest deposit, as a share of the price in basis points (1000 = 10%)." }
        cancelFeeBp: { type: integer, minimum: 0, maximum: 100, default: 0, description: "Fee kept on cancellation, in basis points of the price; at most 1%." }
    LaybyCollectRequest:
      type: object
      properties:
        byStaffId: { type: string }
    LaybyCollectResponse:
      type: object
      properties:
        orderId: { type: string }
        collectedAt: { type: integer, format: int64 }
      required: [orderId, collectedAt]
    LaybyCancelRequest:
      type: object
      properties:
        refundTo: { type: string, enum: [CASH, STORE_CREDIT] }
        byStaffId: { type: string }
      required: [refundTo]
    LaybyCancelResponse:
      type: object
      properties:
        orderId: { type: string }
        paidCents: { type: integer, format: int64 }
        feeCents: { type: integer, format: int64 }
        refundCents: { type: integer, format: int64 }
        refundTo: { type: string, enum: [CASH, STORE_CREDIT] }
      required: [orderId, paidCents, feeCents, refundCents, refundTo]
    ReadyBoardDto:
      type: object
      properties:
        locationId: { type: string }
        ready:
          type: array
          items:
            type: object
            properties:
              pickupNumber: { type: string, description: "The order's daily sequence without leading zeros — what the guest was shown." }
              readyAt: { type: integer, format: int64 }
            required: [pickupNumber, readyAt]
      required: [locationId, ready]
    ReadyTvDto:
      type: object
      properties:
        locationId: { type: string }
        preparing:
          type: array
          description: "Pickup numbers of orders still being made, oldest first."
          items: { type: string }
        ready:
          type: array
          items:
            type: object
            properties:
              pickupNumber: { type: string }
              readyAt: { type: integer, format: int64 }
            required: [pickupNumber, readyAt]
        venueName: { type: string, nullable: true, description: "T-36.26 — the location's name, which the TV shows over its numbers. Numbers stay bare here; the TV writes them \"#42\"." }
      required: [locationId, preparing, ready]
    TipPolicyDto:
      type: object
      properties:
        mode: { type: string, enum: [DIRECT, POOLED, ROLE_SHARES], default: DIRECT }
        tipOuts: { type: array, items: { $ref: "#/components/schemas/TipOutRuleDto" } }
        roleShares: { type: array, items: { $ref: "#/components/schemas/TipRoleShareDto" }, description: "Each role's share of the pool; only with ROLE_SHARES, and they add up to 10 000 basis points." }
    TipRoleShareDto:
      type: object
      properties:
        role: { type: string, description: "A staff role held by people (not DEVICE)." }
        shareBp: { type: integer, minimum: 1, maximum: 10000, description: "Share of the pool, in basis points (7000 = 70%)." }
      required: [role, shareBp]
    MyTips:
      type: object
      description: "One person's own line of a location's tips report for a period: theirs and nobody else's (T-35.7). `payoutCents` is `earnedCents` less the tip-out given, plus the tip-out received, plus the share of the pool."
      properties:
        locationId: { type: string }
        fromMs: { type: integer, format: int64 }
        untilMs: { type: integer, format: int64 }
        mode: { type: string, enum: [DIRECT, POOLED, ROLE_SHARES] }
        minutesWorked: { type: integer, format: int64 }
        earnedCents: { type: integer, format: int64 }
        tipOutGivenCents: { type: integer, format: int64 }
        tipOutReceivedCents: { type: integer, format: int64 }
        poolCents: { type: integer, format: int64 }
        payoutCents: { type: integer, format: int64 }
      required: [locationId, fromMs, untilMs, mode]
    TipOutRuleDto:
      type: object
      properties:
        role: { type: string, description: "A staff role held by people (not DEVICE)." }
        rateBp: { type: integer, minimum: 1, maximum: 5000, description: "Share of the floor's tips, in basis points (200 = 2%)." }
      required: [role, rateBp]
    TipShareDto:
      type: object
      properties:
        staffId: { type: string }
        staffName: { type: string }
        role: { type: string }
        minutesWorked: { type: integer, format: int64 }
        earnedCents: { type: integer, format: int64 }
        tipOutGivenCents: { type: integer, format: int64 }
        tipOutReceivedCents: { type: integer, format: int64 }
        poolCents: { type: integer, format: int64 }
        payoutCents: { type: integer, format: int64, description: "What this person is owed." }
        tipOutNetCents: { type: integer, format: int64, description: "Tip-outs received less given." }
      required: [staffId, staffName, role, minutesWorked, earnedCents, tipOutGivenCents, tipOutReceivedCents, poolCents, payoutCents]
    TipsReportDto:
      type: object
      properties:
        locationId: { type: string }
        fromMs: { type: integer, format: int64 }
        untilMs: { type: integer, format: int64 }
        policy: { $ref: "#/components/schemas/TipPolicyDto" }
        totalCents: { type: integer, format: int64 }
        heldCents: { type: integer, format: int64, description: "Pooled tips nobody was on shift to share — for a manager to pay by hand." }
        shares: { type: array, items: { $ref: "#/components/schemas/TipShareDto" } }
        notes: { type: array, items: { type: string } }
        carriedBackCents: { type: integer, format: int64, description: "Refunded tips that were taken before the period, so they come off nothing in it (T-35.7)." }
      required: [locationId, fromMs, untilMs, policy, totalCents, heldCents, shares]
    ConcessionsReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        salesCents: { type: integer, format: int64 }
        lineDiscountCents: { type: integer, format: int64 }
        billDiscountCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        compedCents: { type: integer, format: int64 }
        compedLines: { type: integer }
        voidedLinesCents: { type: integer, format: int64 }
        voidedLines: { type: integer }
        voidedBillsCents: { type: integer, format: int64 }
        voidedBills: { type: integer }
        voidsCents: { type: integer, format: int64 }
        voidCount: { type: integer }
        walkedOutBills: { type: integer, default: 0, description: "Bills a manager closed because the guest left without paying (T-37.5); never also in voidedBills." }
        walkedOutCents: { type: integer, format: int64, default: 0, description: "What was owed on them: a loss, in none of sales, voids, tips or takings." }
        salesDefinition: { type: string }
      required: [periodStart, periodEnd, salesCents, discountCents, compedCents, voidsCents]
    ShiftSummaryDto:
      type: object
      properties:
        id: { type: string }
        staffId: { type: string }
        locationId: { type: string }
        clockInAt: { type: integer, format: int64 }
        clockOutAt: { type: integer, format: int64, nullable: true }
        status: { type: string }
        openingFloatCents: { type: integer, format: int64 }
        expectedCashCents: { type: integer, format: int64, nullable: true, description: "Withheld — absent — when the venue closes by blind count and the caller is not a manager." }
        countedCashCents: { type: integer, format: int64, nullable: true }
        cashVarianceCents: { type: integer, format: int64, nullable: true, description: "Withheld — absent — when the venue closes by blind count and the caller is not a manager." }
        zReportGenerated: { type: boolean, default: false }
        paidInCents: { type: integer, format: int64, default: 0 }
        paidOutCents: { type: integer, format: int64, default: 0 }
      required: [id, staffId, locationId, clockInAt, status, openingFloatCents]
    VariantDto:
      type: object
      properties:
        id: { type: string }
        productId: { type: string }
        name: { type: string }
        priceDeltaCents: { type: integer, format: int64, description: "Signed delta off the parent product price" }
        sku: { type: string, nullable: true }
        sortOrder: { type: integer, default: 0 }
        active: { type: boolean, default: true }
      required: [id, productId, name, priceDeltaCents]
    VariantUpsertRequest:
      type: object
      properties:
        id: { type: string, nullable: true }
        name: { type: string }
        priceDeltaCents: { type: integer, format: int64, default: 0 }
        sku: { type: string, nullable: true, description: "Keep-on-absent on update; blank clears" }
        sortOrder: { type: integer, nullable: true, description: "Keep-on-absent on update" }
        active: { type: boolean, default: true }
      required: [name]
    LabelSheetRequest:
      type: object
      properties:
        items: { type: array, items: { $ref: "#/components/schemas/LabelSheetItem" } }
      required: [items]
    LabelSheetItem:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        copies: { type: integer, default: 1, minimum: 1, maximum: 100 }
      required: [productId]
    LaybyOpenRequest:
      type: object
      properties:
        customerId: { type: string, nullable: true, description: "Falls back to the order's attached customer" }
        deposit: { $ref: "#/components/schemas/PaymentLeg" }
        byStaffId: { type: string, nullable: true }
        ageCheck: { type: object, nullable: true, description: "T-37.1 - the age check, made when the lay-by is opened and before its deposit: required when a line is age-restricted (`409 age_check_required` without it). Kept on the lay-by, so the instalment that settles it does not ask again. Recorded as TILL and the signed-in person.", properties: { surface: { type: string, enum: [TILL, QR, KIOSK, ONLINE_STORE] }, staffId: { type: string, nullable: true }, atMs: { type: integer, format: int64, nullable: true } }, required: [surface] }
    LaybyPaymentRequest:
      type: object
      properties:
        leg: { $ref: "#/components/schemas/PaymentLeg" }
        byStaffId: { type: string, nullable: true }
      required: [leg]
    LaybyPaymentResponse:
      type: object
      properties:
        orderId: { type: string }
        paidCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        balanceDueCents: { type: integer, format: int64 }
        settled: { type: boolean, description: "True once instalments cover the total — the sale is now PAID" }
      required: [orderId, paidCents, totalCents, balanceDueCents, settled]
    StoreCreditBalance:
      type: object
      properties:
        customerId: { type: string }
        storeCreditCents: { type: integer, format: int64 }
        drawnWithTheSale: { type: boolean, description: "True: the sale draws this balance in its own commit (T-21.7), so a till takes it as a leg of the bill and sends no draw first. Absent from an older server." }
        drawnForBillCents: { type: integer, format: int64, description: "What the bill named by ?bill= has drawn on this balance already, as checkout counts it (T-21.6 review 7 follow-up F2). 0 with no bill named." }
      required: [customerId, storeCreditCents]
    StoreCreditAdjustRequest:
      type: object
      properties:
        deltaCents: { type: integer, format: int64, description: "Signed; non-zero" }
        reason: { type: string }
        byStaffId: { type: string, nullable: true }
      required: [deltaCents, reason]
    StoreCreditRedeemRequest:
      type: object
      properties:
        amountCents: { type: integer, format: int64, minimum: 1 }
        orderId: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
      required: [amountCents]
    StoreCreditMovementDto:
      type: object
      properties:
        id: { type: string }
        customerId: { type: string }
        deltaCents: { type: integer, format: int64 }
        reason: { type: string }
        referenceId: { type: string, nullable: true }
        staffId: { type: string, nullable: true }
        occurredAt: { type: integer, format: int64 }
      required: [id, customerId, deltaCents, reason, occurredAt]
    StockTransferDto:
      type: object
      properties:
        id: { type: string }
        transferNumber: { type: string }
        status: { type: string, enum: [DRAFT, IN_TRANSIT, RECEIVED, CANCELLED] }
        fromLocationId: { type: string }
        toLocationId: { type: string }
        sentAt: { type: integer, format: int64, nullable: true }
        receivedAt: { type: integer, format: int64, nullable: true }
        notes: { type: string, nullable: true }
        createdByStaffId: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/StockTransferLineDto" } }
      required: [id, transferNumber, status, fromLocationId, toLocationId, createdAt]
    StockTransferLineDto:
      type: object
      properties:
        id: { type: string }
        productId: { type: string }
        productName: { type: string, nullable: true }
        quantityUnits: { type: integer, format: int64 }
        receivedUnits: { type: integer, format: int64, default: 0 }
      required: [id, productId, quantityUnits]
    StockTransferCreateRequest:
      type: object
      properties:
        fromLocationId: { type: string }
        toLocationId: { type: string }
        lines:
          type: array
          items:
            type: object
            properties:
              productId: { type: string }
              quantityUnits: { type: integer, format: int64, minimum: 1 }
            required: [productId, quantityUnits]
        notes: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
      required: [fromLocationId, toLocationId, lines]
    StockTransferReceiveRequest:
      type: object
      properties:
        receiveAll: { type: boolean, default: true, description: "True receives every line in full, ignoring lines[]" }
        lines:
          type: array
          items:
            type: object
            properties:
              lineId: { type: string }
              receivedUnits: { type: integer, format: int64, minimum: 0 }
            required: [lineId, receivedUnits]
        opId: { type: string, nullable: true, description: "Minted by the device before the first attempt (T-8.1). The same op arriving again — a retry or an outbox replay — moves stock once; reused for other work it is refused `op_id_conflict`. Absent: answered as before, not replay-safe." }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When the work happened, in server time. Absent means now; kept when within the last 7 days, otherwise refused `invalid_occurred_at`." }
        byStaffId: { type: string, nullable: true }
    StockTransferSendRequest:
      type: object
      properties:
        opId: { type: string, nullable: true, description: "Minted by the device before the first attempt (T-8.1). The same op arriving again — a retry or an outbox replay — moves stock once; reused for other work it is refused `op_id_conflict`. Absent: answered as before, not replay-safe." }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When the work happened, in server time. Absent means now; kept when within the last 7 days, otherwise refused `invalid_occurred_at`." }
        byStaffId: { type: string, nullable: true }
    ProductsReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        rows: { type: array, items: { $ref: "#/components/schemas/ProductsReportRow" } }
        totalQuantity: { type: integer, format: int64 }
        totalRevenueCents: { type: integer, format: int64 }
        totalCostCents: { type: integer, format: int64, nullable: true }
        totalMarginCents: { type: integer, format: int64, nullable: true }
        totalMarginPctBp: { type: integer, format: int64, nullable: true }
      required: [periodStart, periodEnd, rows]
    ProductsReportRow:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        categoryId: { type: string, nullable: true }
        categoryName: { type: string, nullable: true }
        brand: { type: string, nullable: true }
        quantity: { type: integer, format: int64 }
        revenueCents: { type: integer, format: int64 }
        costCents: { type: integer, format: int64, description: "Recipe-aware unit cost × quantity" }
        marginCents: { type: integer, format: int64 }
      # costCents and marginCents are withheld from non-managers — a supplier's terms are
      # not a cashier's business — and are omitted from the payload rather than zeroed,
      # because a zero is a figure somebody quotes. Managers get both.
        marginPctBp: { type: integer, format: int64, nullable: true, description: "Margin as basis points of net sales (manager-only)." }
      required: [productId, name, quantity, revenueCents]
    CustomersReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        totalSalesCount: { type: integer }
        salesWithCustomer: { type: integer }
        uniqueCustomers: { type: integer }
        newCustomers: { type: integer, description: "First-ever sale falls inside the window" }
        returningCustomers: { type: integer }
        averageBasketCents: { type: integer, format: int64 }
        averageBasketWithCustomerCents: { type: integer, format: int64 }
        repeatRatePercent: { type: integer, description: "Share of window customers with 2+ sales in the window" }
        topCustomers: { type: array, items: { $ref: "#/components/schemas/TopCustomerRow" } }
        attachRatePercent: { type: integer, description: "Sales with a customer attached, as a percentage of sales." }
      required: [periodStart, periodEnd, totalSalesCount, salesWithCustomer, uniqueCustomers, newCustomers, returningCustomers, averageBasketCents, averageBasketWithCustomerCents, repeatRatePercent, topCustomers]
    TopCustomerRow:
      type: object
      properties:
        customerId: { type: string }
        name: { type: string }
        salesCount: { type: integer }
        revenueCents: { type: integer, format: int64 }
        lastSaleAt: { type: integer, format: int64 }
      required: [customerId, name, salesCount, revenueCents, lastSaleAt]
    InventoryAgingReport:
      type: object
      properties:
        locationId: { type: string }
        olderThanDays: { type: integer }
        rows: { type: array, items: { $ref: "#/components/schemas/InventoryAgingRow" } }
      required: [locationId, olderThanDays, rows]
    InventoryAgingRow:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        onHandUnits: { type: integer, format: int64 }
        stockValueCents: { type: integer, format: int64 }
        lastSoldAt: { type: integer, format: int64, nullable: true, description: "Null = never sold" }
        daysSinceLastSale: { type: integer, nullable: true }
      # stockValueCents is stock at cost: manager-only, and omitted otherwise. The row
      # order is gated with it — sorting by value hands over the cost ranking with the
      # numbers filed off.
      required: [productId, name, onHandUnits]
    ZReport:
      type: object
      properties:
        xReport: { $ref: "#/components/schemas/XReport" }
        cashDropCents: { type: integer, format: int64 }
        journalEntryId:
          type: string
          nullable: true
          deprecated: true
          description: Always null. The Z-report posts no journal of its own; each sale in the shift carries its own POS_SALE journal, and the Z-report posts any that are missing.
        expectedCashCents: { type: integer, format: int64, nullable: true, description: "Withheld — absent — when the venue closes by blind count and the caller is not a manager. The figure is still stored on the shift." }
        cashVarianceCents: { type: integer, format: int64, nullable: true, description: "Withheld — absent — when the venue closes by blind count and the caller is not a manager; only a manager sees the variance." }
      required: [xReport, cashDropCents]
    Vat201Report:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        standardSalesCents: { type: integer, format: int64 }
        standardOutputVatCents: { type: integer, format: int64 }
        zeroRatedSalesCents: { type: integer, format: int64 }
        exemptSalesCents: { type: integer, format: int64 }
        totalSalesCents: { type: integer, format: int64 }
        inputVatCents: { type: integer, format: int64, description: "Input tax from approved supplier tax invoices held in the period (the later of the invoice's date and its approval), less approved credit notes held in it. Never from goods received; nothing from a supplier with no VAT number." }
        vatPayableCents: { type: integer, format: int64 }
        receivedNoInvoice:
          type: array
          description: Goods received in the period with no approved supplier tax invoice yet. They claim no input tax.
          items:
            type: object
            properties:
              receiptId: { type: string }
              grnNumber: { type: string }
              supplierId: { type: string }
              supplierName: { type: string, nullable: true }
              receivedAt: { type: integer, format: int64 }
              valueCents: { type: integer, format: int64, description: "What the delivery was worth; shown, never claimed." }
            required: [receiptId, grnNumber, supplierId, receivedAt, valueCents]
        receivedNoInvoiceCut: { type: boolean, description: "True when receivedNoInvoice lists only the first of more open deliveries (200)." }
        notClaimed:
          type: array
          description: Approved supplier documents whose tax is not claimed on this return, and deliveries of a purchase straddling 1 December 2026, each with why; a delivery only while no tax invoice held from that day names its purchase. A credit note listed claimed_on_delivery, straddles_switch or unnamed_beside_deliveries is taken off all the same.
          items:
            type: object
            properties:
              invoiceId: { type: string }
              invoiceNumber: { type: string }
              docType: { type: string, enum: [INVOICE, CREDIT_NOTE, DELIVERY], description: "DELIVERY: a delivery of a purchase straddling 1 December 2026, listed by itself; invoiceId is its receipt id and invoiceNumber its GRN number." }
              supplierId: { type: string }
              supplierName: { type: string, nullable: true }
              taxCents: { type: integer, format: int64, description: "As printed; negative for a credit note. A delivery's is the VAT in its accepted units." }
              reason: { type: string, enum: [no_supplier_vat_number, no_vendor, past_five_years, claimed_on_delivery, straddles_switch, unnamed_beside_deliveries] }
            required: [invoiceId, invoiceNumber, docType, supplierId, taxCents, reason]
      required: [periodStart, periodEnd, standardSalesCents, standardOutputVatCents, zeroRatedSalesCents, exemptSalesCents, totalSalesCents, inputVatCents, vatPayableCents]
    HeatmapCell:
      type: object
      properties:
        hour: { type: integer }
        revenueCents: { type: integer, format: int64 }
      required: [hour, revenueCents]
    HeatmapRow:
      type: object
      properties:
        dayOfWeek: { type: integer, description: "0=Sunday .. 6=Saturday" }
        buckets: { type: array, items: { $ref: "#/components/schemas/HeatmapCell" } }
      required: [dayOfWeek, buckets]
    HeatmapReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        rows: { type: array, items: { $ref: "#/components/schemas/HeatmapRow" } }
      required: [periodStart, periodEnd, rows]
    QrInsightsBucket:
      type: object
      description: One day's (key is the ISO day) or one table's (key is the table id, empty for no table) scans and QR orders.
      properties:
        key: { type: string }
        label: { type: string }
        scans: { type: integer, format: int64 }
        orders: { type: integer }
        conversionBp: { type: integer, format: int64, nullable: true, description: "Orders per scan in basis points; null with no scans." }
        salesCents: { type: integer, format: int64 }
      required: [key, label, scans, orders, salesCents]
    QrInsights:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        ordersToDate: { type: integer, description: "QR orders so far, counted up to 20." }
        ready: { type: boolean, description: "False until the venue's first 20 QR orders." }
        scans: { type: integer, format: int64 }
        orders: { type: integer }
        conversionBp: { type: integer, format: int64, nullable: true }
        salesCents: { type: integer, format: int64 }
        averageOrderCents: { type: integer, format: int64 }
        paidToReadySeconds: { type: integer, format: int64, nullable: true }
        paidToReadyOrders: { type: integer }
        ratingTenths: { type: integer, nullable: true, description: "Average rating in tenths: 43 is 4.3 of 5." }
        ratingCount: { type: integer }
        peakHour: { type: integer, nullable: true }
        days: { type: array, items: { $ref: "#/components/schemas/QrInsightsBucket" } }
        tables: { type: array, items: { $ref: "#/components/schemas/QrInsightsBucket" } }
        hours:
          type: array
          items:
            type: object
            properties:
              hour: { type: integer }
              orders: { type: integer }
              salesCents: { type: integer, format: int64 }
        bestSellers:
          type: array
          items:
            type: object
            properties:
              productId: { type: string }
              name: { type: string }
              units: { type: integer, format: int64 }
              revenueCents: { type: integer, format: int64 }
        salesDefinition: { type: string }
      required: [periodStart, periodEnd, ordersToDate, ready, scans, orders, salesCents, averageOrderCents, paidToReadyOrders, ratingCount]
    ServerPerformanceRow:
      type: object
      properties:
        staffId: { type: string }
        staffName: { type: string, nullable: true, description: "Resolved staff display name; null if the staff row no longer exists." }
        ordersCount: { type: integer }
        grossCents: { type: integer, format: int64 }
        tipsCents: { type: integer, format: int64 }
        avgCheckCents: { type: integer, format: int64 }
      required: [staffId, ordersCount, grossCents, tipsCents, avgCheckCents]
    ServerPerformanceReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        rows: { type: array, items: { $ref: "#/components/schemas/ServerPerformanceRow" } }
      required: [periodStart, periodEnd, rows]
    MenuEngineeringItem:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        unitsSold: { type: integer, format: int64 }
        grossRevenueCents: { type: integer, format: int64 }
        costCents: { type: integer, format: int64, description: "Recipe-derived (or product) cost × units." }
        marginCents: { type: integer, format: int64 }
        marginPct: { type: number, format: double }
        unitMarginCents: { type: integer, format: int64 }
        popularityRank: { type: integer, description: "1 = most units sold." }
        quadrant: { type: string, description: "STAR | PLOWHORSE | PUZZLE | DOG" }
      # The quadrant is the point of this report for floor staff — it says which dish to
      # recommend — so it is served to everybody. The money is not: costCents, marginCents,
      # unitMarginCents and marginPct are manager-only. marginPct is withheld too, because a
      # percentage plus a price is a cost.
      required: [productId, name, unitsSold, grossRevenueCents, popularityRank, quadrant]
    MenuEngineeringReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        locationId: { type: string, nullable: true }
        medianUnitsSold: { type: integer, format: int64 }
        medianUnitMarginCents: { type: integer, format: int64 }
        items: { type: array, items: { $ref: "#/components/schemas/MenuEngineeringItem" } }
      # medianUnitMarginCents is a margin in cents and would have defeated the gate.
      required: [periodStart, periodEnd, medianUnitsSold, items]
    PacingStat:
      type: object
      properties:
        avgMs: { type: integer, format: int64 }
        p90Ms: { type: integer, format: int64 }
        count: { type: integer }
      required: [avgMs, p90Ms, count]
    PacingStationStat:
      type: object
      properties:
        station: { type: string }
        avgFireToBumpMs: { type: integer, format: int64 }
        p90FireToBumpMs: { type: integer, format: int64 }
        ticketCount: { type: integer }
      required: [station, avgFireToBumpMs, p90FireToBumpMs, ticketCount]
    PacingCourseStat:
      type: object
      properties:
        courseType: { type: string }
        avgFireToBumpMs: { type: integer, format: int64 }
        p90FireToBumpMs: { type: integer, format: int64 }
        ticketCount: { type: integer }
      required: [courseType, avgFireToBumpMs, p90FireToBumpMs, ticketCount]
    KitchenTimes:
      type: object
      required: [fired, finished, judged, late]
      properties:
        fired: { type: integer, description: Tickets fired. }
        finished: { type: integer, description: Tickets plated or bumped. }
        judged: { type: integer, description: "Finished tickets, plus open ones already past their target." }
        late: { type: integer }
        avgPrepSec: { type: integer, nullable: true }
        p90PrepSec: { type: integer, nullable: true, description: Nearest-rank 90th percentile of finished tickets. }
    KitchenReport:
      type: object
      required: [periodStart, periodEnd, defaultLateMinutes, overall, stations, items, hours]
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        locationId: { type: string, nullable: true }
        defaultLateMinutes: { type: integer, description: Minutes a ticket with no target of its own is held to. }
        overall: { $ref: "#/components/schemas/KitchenTimes" }
        stations:
          type: array
          items: { type: object, properties: { station: { type: string }, times: { $ref: "#/components/schemas/KitchenTimes" } } }
        items:
          type: array
          items: { type: object, properties: { productId: { type: string, nullable: true }, name: { type: string }, times: { $ref: "#/components/schemas/KitchenTimes" } } }
        hours:
          type: array
          description: 24 entries, hour 0–23 in Africa/Johannesburg.
          items: { type: object, properties: { hour: { type: integer }, times: { $ref: "#/components/schemas/KitchenTimes" } } }
        staff:
          type: array
          description: Who bumped the tickets, most bumps first (T-36.13). Absent from an older server.
          items:
            type: object
            required: [kind, name, bumped]
            properties:
              kind: { type: string, enum: [PERSON, SCREEN, ACCOUNT, UNRECORDED] }
              id: { type: string, nullable: true, description: "The staff member's or the screen's id; null for ACCOUNT and UNRECORDED." }
              name: { type: string, description: "A staff member's display name, or the screen's own name." }
              bumped: { type: integer }
              avgBumpSec: { type: integer, nullable: true }
              slowestBumpSec: { type: integer, nullable: true }
    KioskSlide:
      type: object
      required: [id, locationId, url, dwellSeconds, sortOrder, byteSize]
      properties:
        id: { type: string }
        locationId: { type: string }
        url: { type: string, description: "Public, relative to the API origin." }
        dwellSeconds: { type: integer }
        altText: { type: string, nullable: true }
        sortOrder: { type: integer }
        byteSize: { type: integer }
        unpublished: { type: boolean, default: false, description: "No kiosk is shown it: stored before T-2.13 and refused by, or not yet through, the re-encode." }
    FloorLayout:
      type: object
      description: One level of a floor (core `FloorLayout`). Elements are told apart by `type`.
      required: [locationId, elements]
      properties:
        version: { type: integer, example: 2 }
        locationId: { type: string }
        level: { type: integer, description: "0 is the ground floor, up to 20." }
        levelName: { type: string, nullable: true }
        elements:
          type: array
          items:
            type: object
            description: |
              `table` (id = the table's id; x, y, w, h, rotation, shape ROUND|SQUARE|RECT|BOOTH|BAR_SEAT, seats[{number, angle}]),
              `wall` (x1, y1, x2, y2, thickness), `label` (x, y, text, rotation) or `decor` (kind, x, y, w, h, rotation).
            required: [type, id]
            properties:
              type: { type: string, enum: [table, wall, label, decor] }
              id: { type: string }
    UpsellRule:
      type: object
      required: [id, suggestProductId]
      properties:
        id: { type: string, description: Ignored on create. }
        triggerProductId: { type: string, nullable: true }
        triggerCategoryId: { type: string, nullable: true }
        suggestProductId: { type: string }
        message: { type: string, nullable: true, maxLength: 80 }
        priority: { type: integer, default: 0 }
        active: { type: boolean, default: true }
    PacingReport:
      type: object
      properties:
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        locationId: { type: string, nullable: true }
        availableMetrics: { type: array, items: { type: string } }
        unavailableMetrics: { type: array, items: { type: string } }
        seatedToFirstOrder: { $ref: "#/components/schemas/PacingStat" }
        orderToFire: { $ref: "#/components/schemas/PacingStat" }
        fireToBump: { $ref: "#/components/schemas/PacingStat" }
        orderToSettle: { $ref: "#/components/schemas/PacingStat" }
        slowestStations: { type: array, items: { $ref: "#/components/schemas/PacingStationStat" } }
        slowestCourses: { type: array, items: { $ref: "#/components/schemas/PacingCourseStat" } }
        longIdleOccupiedTables: { type: integer }
        idleThresholdMinutes: { type: integer }
      required: [periodStart, periodEnd, availableMetrics, unavailableMetrics, orderToFire, fireToBump, orderToSettle, slowestStations, slowestCourses, longIdleOccupiedTables, idleThresholdMinutes]
    DiscountLogEntry:
      type: object
      properties:
        id: { type: string }
        transactionId: { type: string }
        discountType: { type: string }
        amountCents: { type: integer, format: int64 }
        reasonCode: { type: string }
        reasonNote: { type: string, nullable: true }
        approvedByStaffId: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
      required: [id, transactionId, discountType, amountCents, reasonCode, createdAt]
    VoidLogEntry:
      type: object
      properties:
        id: { type: string }
        transactionId: { type: string }
        lineId: { type: string, nullable: true }
        reason: { type: string }
        approvedByStaffId: { type: string }
        voidedAt: { type: integer, format: int64 }
        walkOutReasonCode: { type: string, nullable: true, description: "Set when the bill was closed as a walk-out (T-37.5): the shrinkage reason's code. Null for a void." }
      required: [id, transactionId, reason, approvedByStaffId, voidedAt]
    CompLogEntry:
      type: object
      properties:
        id: { type: string }
        transactionId: { type: string }
        lineId: { type: string }
        reason: { type: string }
        amountCents: { type: integer, format: int64 }
        approvedByStaffId: { type: string }
        compedAt: { type: integer, format: int64 }
      required: [id, transactionId, lineId, reason, amountCents, approvedByStaffId, compedAt]

    # ── Ledgr ──
    JournalGenerateRequest:
      type: object
      properties:
        transactionIds: { type: array, items: { type: string } }
      required: [transactionIds]
    JournalLineDto:
      type: object
      properties:
        accountCode: { type: string }
        debitCents: { type: integer, format: int64 }
        creditCents: { type: integer, format: int64 }
        memo: { type: string, nullable: true }
      required: [accountCode, debitCents, creditCents]
    JournalEntryDto:
      type: object
      properties:
        id: { type: string }
        description: "{ type: string }"
        postedAt: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/JournalLineDto" } }
      required: [id, description, postedAt, lines]
    JournalGenerateResponse:
      type: object
      properties:
        entries: { type: array, items: { $ref: "#/components/schemas/JournalEntryDto" } }
        generated: { type: integer }
        skipped: { type: integer }
      required: [entries, generated, skipped]

    # ── Loyalty & Vouchers ──
    VoucherDto:
      type: object
      properties:
        id: { type: string }
        code: { type: string }
        description: "{ type: string }"
        discountType: { type: string, description: "PERCENT (basis points) | FIXED (cents)" }
        discountValue: { type: integer, format: int64 }
        minSpendCents: { type: integer, format: int64 }
        maxUses: { type: integer, format: int64, nullable: true }
        usesCount: { type: integer, format: int64 }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        active: { type: boolean }
      required: [id, code, description, discountType, discountValue, minSpendCents, usesCount, active]
    VoucherCreateRequest:
      type: object
      properties:
        code: { type: string }
        description: "{ type: string }"
        discountType: { type: string, description: "PERCENT | FIXED" }
        discountValue: { type: integer, format: int64 }
        minSpendCents: { type: integer, format: int64, default: 0 }
        maxUses: { type: integer, format: int64, nullable: true }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        customerId: { type: string, nullable: true }
      required: [code, description, discountType, discountValue]
    VoucherUpdateRequest:
      type: object
      description: "Partial voucher edit (BO-F27). All fields keep-on-absent; `code` is immutable."
      properties:
        description: "{ type: string, nullable: true }"
        discountType: { type: string, nullable: true, description: "PERCENT | FIXED" }
        discountValue: { type: integer, format: int64, nullable: true }
        minSpendCents: { type: integer, format: int64, nullable: true }
        maxUses: { type: integer, format: int64, nullable: true }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        active: { type: boolean, nullable: true }
    VoucherRedeemRequest:
      type: object
      properties:
        code: { type: string }
        transactionId: { type: string }
        byStaffId: { type: string, nullable: true }
      required: [code, transactionId]
    VoucherRedeemResult:
      type: object
      properties:
        voucherId: { type: string }
        discountCents: { type: integer, format: int64 }
      required: [voucherId, discountCents]

    # ── Gift Cards ──
    GiftCardDto:
      type: object
      properties:
        id: { type: string }
        code: { type: string }
        initialCents: { type: integer, format: int64 }
        balanceCents: { type: integer, format: int64 }
        issuedToName: { type: string, nullable: true }
        issuedToEmail: { type: string, nullable: true }
        issuedToPhone: { type: string, nullable: true }
        issuedAt: { type: integer, format: int64 }
        expiresAt: { type: integer, format: int64, nullable: true }
        voided: { type: boolean }
        notes: { type: string, nullable: true }
        voidedAt: { type: integer, format: int64, nullable: true, description: When a manager voided the card; null while it is live. }
        voidedCents: { type: integer, format: int64, nullable: true, description: The balance the void took to zero. }
        expiredAt: { type: integer, format: int64, nullable: true, description: When the card expired and its leftover was released to breakage; null while it is live. }
        expiredCents: { type: integer, format: int64, nullable: true, description: What was left on the card when it expired. }
        handBack: { type: string, nullable: true, enum: [REFUND, TRANSFER, WITHDRAW], description: How a void handed the value back. }
        paidBy: { type: string, nullable: true, enum: [CASH, CARD, EFT, COMPLIMENTARY], description: What paid for the card (a replacement keeps its original's); null when not on record. Decides how it may be voided. }
        fundingOnRecord: { type: boolean, description: "False for a card nothing shows was paid for (issued before what paid for a card was kept, with no product): it is only moved to a new card." }
        tillSaleOnRecord: { type: boolean, description: "For a card with no funding on record: whether a till sale looks to have sold it (a paid stored-value line at its face value within a day of issue). A hint for the declaration, never booked by." }
        handBackTender: { type: string, nullable: true, enum: [CASH, CARD, EFT], description: The tender a REFUND was paid by. }
        replacementCode: { type: string, nullable: true, description: The code of the card a TRANSFER moved the value to. }
        expired: { type: boolean, description: "Whether the card is past its expiry now (swept, its date, or three years from issue): the server's verdict." }
        drawnWithTheSale: { type: boolean, description: "True: the sale draws this balance in its own commit (T-21.7), so a till takes it as a leg of the bill and sends no draw first. Absent from an older server." }
        drawnForBillCents: { type: integer, format: int64, description: "What the bill named by ?bill= has drawn on this balance already, as checkout counts it (T-21.6 review 7 follow-up F2). 0 with no bill named." }
      required: [id, code, initialCents, balanceCents, issuedAt, voided]
    GiftCardFundingRequest:
      type: object
      properties:
        paidBy: { type: string, enum: [SOLD_AT_TILL, CASH, CARD, EFT, COMPLIMENTARY], description: How the card was funded. Said once. }
      required: [paidBy]
    GiftCardVoidRequest:
      type: object
      properties:
        handBack: { type: string, enum: [REFUND, TRANSFER, WITHDRAW], description: How the value goes back to the holder. WITHDRAW only for a complimentary card. }
        tender: { type: string, nullable: true, enum: [CASH, CARD, EFT], description: Required for REFUND. }
      required: [handBack]
    GiftCardIssueRequest:
      type: object
      properties:
        initialCents: { type: integer, format: int64 }
        issuedToName: { type: string, nullable: true }
        issuedToEmail: { type: string, nullable: true }
        issuedToPhone: { type: string, nullable: true }
        expiresAt: { type: integer, format: int64, nullable: true, description: "Not sooner than three years from issue (400 gift_card_expiry_too_soon); left out, it is three years." }
        issuedByStaffId: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        paidBy: { type: string, nullable: true, enum: [CASH, CARD, EFT, COMPLIMENTARY], description: "What the buyer paid with, so the card's value is booked against it (Gift Cards Outstanding); COMPLIMENTARY means no money was taken and it is booked against Sales Discounts. Required: left out, the issue is refused 400 `paid_by_required` with the sentence to show; sent beside `productId`, 400 `paid_by_with_product`." }
        productId: { type: string, nullable: true, description: "A stored-value product the card was sold as in a sale (zero-rated or exempt); that sale booked the money, so `paidBy` is not sent with it." }
      required: [initialCents]
    GiftCardRedeemRequest:
      type: object
      properties:
        code: { type: string }
        amountCents: { type: integer, format: int64 }
        transactionId: { type: string, description: "The bill the card pays: the open order's id, or WALK_IN." }
        drawId: { type: string, nullable: true, description: "This payment's id, kept across its retries and new for the next payment; the card is drawn once per card and drawId." }
      required: [code, amountCents, transactionId]
    GiftCardRedeemResult:
      type: object
      properties:
        giftCardId: { type: string }
        redeemedCents: { type: integer, format: int64 }
        remainingCents: { type: integer, format: int64 }
      required: [giftCardId, redeemedCents, remainingCents]
    GiftCardPage:
      type: object
      properties:
        items: { type: array, items: { $ref: "#/components/schemas/GiftCardDto" } }
        total: { type: integer, format: int64 }
        limit: { type: integer }
        offset: { type: integer, format: int64 }
      required: [items, total, limit, offset]

    # ── House Accounts ──
    HouseAccountDto:
      type: object
      properties:
        id: { type: string }
        customerId: { type: string, nullable: true }
        companyName: { type: string, nullable: true }
        contactName: { type: string, nullable: true }
        contactEmail: { type: string, nullable: true }
        contactPhone: { type: string, nullable: true }
        creditLimitCents: { type: integer, format: int64 }
        balanceCents: { type: integer, format: int64 }
        status: { type: string }
        drawnWithTheSale: { type: boolean, description: "True: the sale draws this balance in its own commit (T-21.7), so a till takes it as a leg of the bill and sends no draw first. Absent from an older server." }
        drawnForBillCents: { type: integer, format: int64, description: "What the bill named by ?bill= has drawn on this balance already, as checkout counts it (T-21.6 review 7 follow-up F2). 0 with no bill named." }
      required: [id, creditLimitCents, balanceCents, status]
    HouseAccountCreateRequest:
      type: object
      properties:
        customerId: { type: string, nullable: true }
        companyName: { type: string, nullable: true }
        contactName: { type: string, nullable: true }
        contactEmail: { type: string, nullable: true }
        contactPhone: { type: string, nullable: true }
        creditLimitCents: { type: integer, format: int64, default: 0 }
    HouseAccountChargeRequest:
      type: object
      properties:
        accountId: { type: string }
        amountCents: { type: integer, format: int64 }
        transactionId: { type: string, nullable: true, description: "The sale the charge pays. Required from a current till; only an older till's signed-in device may leave it out, and its charge is flagged." }
        memo: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
      required: [accountId, amountCents]
    StatementLineDto:
      type: object
      properties:
        postedAt: { type: integer, format: int64 }
        kind: { type: string, enum: [CHARGE, PAYMENT, REFUND], description: "REFUND: a refund of a sale charged to the account, taken off what it owes (T-21.3)." }
        reference: { type: string, nullable: true }
        memo: { type: string, nullable: true }
        chargeCents: { type: integer, format: int64 }
        paymentCents: { type: integer, format: int64 }
        refundCents: { type: integer, format: int64 }
        balanceCents: { type: integer, format: int64 }
      required: [postedAt, kind, balanceCents]
    AccountStatementDto:
      type: object
      properties:
        accountId: { type: string }
        accountName: { type: string }
        month: { type: string }
        periodStart: { type: integer, format: int64 }
        periodEnd: { type: integer, format: int64 }
        openingCents: { type: integer, format: int64 }
        chargesCents: { type: integer, format: int64 }
        paymentsCents: { type: integer, format: int64 }
        closingCents: { type: integer, format: int64 }
        refundsCents: { type: integer, format: int64, description: "What refunds of sales charged to the account took off it this month (T-21.3); not payments received." }
        creditLimitCents: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/StatementLineDto" } }
        contactEmail: { type: string, nullable: true }
        contactPhone: { type: string, nullable: true }
      required: [accountId, accountName, month, openingCents, closingCents, lines]
    SendStatementRequest:
      type: object
      properties:
        month: { type: string, example: "2026-09" }
        channel: { type: string, enum: [EMAIL, WHATSAPP] }
        to: { type: string, nullable: true }
      required: [month, channel]
    SendStatementResponse:
      type: object
      properties:
        sent: { type: boolean }
        status: { type: string, description: "sent | email_not_configured | whatsapp_not_configured | provider_refused | provider_no_answer (the email service never answered: it may have gone)" }
        message: { type: string }
      required: [sent, status, message]
    HouseAccountSettlementRequest:
      type: object
      properties:
        accountId: { type: string }
        amountCents: { type: integer, format: int64 }
        paymentId: { type: string, nullable: true }
        memo: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
        method: { type: string, enum: [CASH, CARD, EFT], description: "How the payment arrived; decides the account it debits (cash 1000, card 1010, bank 1050) against Debtors Control 1040 (T-4.4)." }
      required: [accountId, amountCents, method]
    HouseAccountPostingDto:
      type: object
      properties:
        id: { type: string }
        accountId: { type: string }
        transactionId: { type: string, nullable: true }
        paymentId: { type: string, nullable: true }
        postingType: { type: string }
        amountCents: { type: integer, format: int64 }
        memo: { type: string, nullable: true }
        postedAt: { type: integer, format: int64 }
      required: [id, accountId, postingType, amountCents, postedAt]

    # ── Inventory ──
    EightySixEntry:
      type: object
      properties:
        id: { type: string }
        productId: { type: string }
        locationId: { type: string }
        productName: { type: string, nullable: true, description: "The dish's name, so a screen with no catalogue (the kitchen display) can say what is off." }
        reason: { type: string, nullable: true }
        eightySixedAt: { type: integer, format: int64 }
        byStaffId: { type: string, nullable: true, description: "Who 86'd it. Omitted for a screen signed in as itself." }
      required: [id, productId, locationId, eightySixedAt]
    EightySixRequest:
      type: object
      properties:
        productId: { type: string }
        locationId: { type: string }
        reason: { type: string, nullable: true, maxLength: 200, description: "Why it is off. Required; at most 200 characters (400 reason_required / reason_too_long)." }
        byStaffId: { type: string, nullable: true }
        id: { type: string, nullable: true, description: "Minted by the till before the first attempt; a request whose id already landed changes nothing (T-3.2)." }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When it happened, epoch ms in server time; absent means now. Refused outside the last 7 days." }
      required: [productId, locationId]
    ClearEightySixRequest:
      type: object
      properties:
        productId: { type: string }
        locationId: { type: string }
        byStaffId: { type: string, nullable: true }
        occurredAt: { type: integer, format: int64, nullable: true, description: "Clears only the 86s made at or before this time (epoch ms, server time); absent means now." }
      required: [productId, locationId]
    WastageRequest:
      type: object
      properties:
        productId: { type: string }
        locationId: { type: string }
        quantityUnits: { type: integer, format: int64 }
        reason: { type: string, nullable: true }
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
        variantId: { type: string, nullable: true, description: "Variant wasted; absent wastes the product's own stock." }
        id: { type: string, nullable: true, description: "Minted by the till before the first attempt; a request whose id already landed changes nothing (T-3.2)." }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When it happened, epoch ms in server time; absent means now. Refused outside the last 7 days." }
      required: [productId, locationId, quantityUnits]
    LowStockEntry:
      type: object
      properties:
        productId: { type: string }
        onHandUnits: { type: integer, format: int64 }
        reorderPointUnits: { type: integer, format: int64 }
        variantId: { type: string, nullable: true, description: "Set when the threshold is on a variant (V19)." }
      required: [productId, onHandUnits, reorderPointUnits]
    CountedStock:
      type: object
      required: [locationId]
      properties:
        locationId: { type: string }
        tills:
          type: array
          items: { type: string }
        onHand:
          type: object
          additionalProperties: { type: integer, format: int64 }
        needs:
          type: object
          additionalProperties:
            type: object
            additionalProperties: { type: integer, format: int64 }
        names:
          type: object
          additionalProperties: { type: string }
        asOf:
          type: integer
          format: int64
          description: The server's time when it read the count; 0 from an older server.
    VariantGrid:
      type: object
      properties:
        productId: { type: string }
        locationId: { type: string }
        tracksStock: { type: boolean }
        axes:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              name: { type: string }
              values:
                type: array
                items:
                  type: object
                  properties:
                    id: { type: string }
                    value: { type: string }
                  required: [id, value]
            required: [id, name, values]
        cells:
          type: array
          items:
            type: object
            properties:
              variantId: { type: string }
              coordinates: { type: object, additionalProperties: { type: string }, description: "Axis id to value id." }
              onHand: { type: integer, format: int64, nullable: true, description: "Null when the product does not track stock." }
            required: [variantId, coordinates]
      required: [productId, locationId, tracksStock, axes, cells]
    WhereIsLocation:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
        onHandUnits: { type: integer, format: int64 }
      required: [locationId, locationName, onHandUnits]
    WhereIsEntry:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true, description: "Set when this row is a variant." }
        name: { type: string, description: "Display label, e.g. \"Tee — Large\"." }
        sku: { type: string, nullable: true }
        totalOnHand: { type: integer, format: int64 }
        locations: { type: array, items: { $ref: "#/components/schemas/WhereIsLocation" } }
      required: [productId, name, totalOnHand]
    ReplenishmentEntry:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        name: { type: string }
        onHandUnits: { type: integer, format: int64 }
        soldInWindow: { type: integer, format: int64 }
        perDayRate: { type: number, description: "Observed units sold per day over the window." }
        coverDays:
          type: integer
          format: int64
          nullable: true
          description: >
            Days the shelf lasts at the observed rate. Omitted when nothing sold — undefined,
            not infinite. See deadStock.
        suggestedOrderUnits: { type: integer, format: int64 }
        deadStock: { type: boolean, description: "On the shelf, nothing sold in the window." }
        tiedUpCents: { type: integer, format: int64, nullable: true, description: "Capital on the shelf, when a cost was captured." }
        reorderPointUnits: { type: integer, format: int64, nullable: true }
      required: [productId, name, onHandUnits, soldInWindow, perDayRate, suggestedOrderUnits, deadStock]
    UsageVarianceEntry:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        name: { type: string }
        explainedBySalesUnits: { type: integer, format: int64, description: "Recipe-exploded for composed dishes." }
        loggedWastageUnits: { type: integer, format: int64, description: "A managed cost, not a mystery." }
        unexplainedUnits: { type: integer, format: int64, description: "Positive = the count found less than the books said." }
        unexplainedCents: { type: integer, format: int64, nullable: true }
        unitCostCents: { type: integer, format: int64, nullable: true }
      required: [productId, name]
    RecipeLineUpsert:
      type: object
      properties:
        ingredientProductId: { type: string }
        quantityUnits: { type: integer, format: int64, description: "Quantity for one BATCH, not one portion." }
        unitLabel: { type: string, default: "g", description: "each | g | kg | ml | cl | l | tsp | tbsp (plus ordinary spellings). Must share a dimension with the ingredient's stockUnit; an undeclared ingredient adopts this line's dimension. 400 unknown_unit / unit_mismatch otherwise." }
      required: [ingredientProductId, quantityUnits]
    RecipeUpsertRequest:
      type: object
      properties:
        productId: { type: string, description: "The dish. Also the recipe's identity — one recipe per product." }
        name: { type: string }
        yieldUnits: { type: integer, default: 1, description: "Portions one batch produces. 1 = quantities are already per portion." }
        outputUnits: { type: integer, format: int64, nullable: true, description: "What one batch produces, in this product's own stock unit (V37) — 4000 for a 4 l batch counted in ml. Omit for anything counted in eaches and it equals yieldUnits. This is the denominator another recipe divides by when it uses this product as an ingredient. 400 invalid_output if < 1." }
        wastePctBp: { type: integer, default: 0, description: "Waste allowance in basis points (1000 = 10%). Max 10000." }
        lines: { type: array, items: { $ref: "#/components/schemas/RecipeLineUpsert" } }
      required: [productId, name, lines]
    RecipeLine:
      type: object
      properties:
        ingredientProductId: { type: string }
        ingredientName: { type: string }
        quantityUnits: { type: integer, format: int64, description: "Per batch, as authored — the number typed, in unitLabel." }
        unitLabel: { type: string }
        baseUnits: { type: integer, format: int64, default: 0, description: "quantityUnits converted to the ingredient's stock unit (V36). This is what deducts." }
        stockUnit: { type: string, default: each, enum: [each, g, ml], description: "The unit the ingredient's stock is counted in." }
        perSaleUnits: { type: integer, format: int64, description: "What one sale deducts, after yield and waste, in stockUnit." }
        perSaleDisplay: { type: string, default: "", description: "perSaleUnits the way a person says it — \"105 g\", \"1.5 kg\"." }
        unitsAgree: { type: boolean, default: true, description: "False on a line authored before V36: the label and the stored deduction disagree, and a human must restate it. Nothing corrects it silently." }
        subRecipe: { type: boolean, default: false, description: "True when this ingredient is itself made here and is not counted (V37): it expands into its own ingredients rather than depleting, so nothing on this line moves. lineCostCents is then what the goods inside it cost." }
        unitCostCents: { type: integer, format: int64, nullable: true }
        lineCostCents: { type: integer, format: int64 }
      required: [ingredientProductId, ingredientName, quantityUnits, unitLabel, perSaleUnits]
    Recipe:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string }
        name: { type: string }
        yieldUnits: { type: integer, description: "Portions one batch makes, as authored." }
        outputUnits: { type: integer, format: int64, default: 1, description: "What one batch produces, in this product's own stock unit (V37) — the denominator a parent recipe divides by. Equal to yieldUnits for anything counted in eaches." }
        wastePctBp: { type: integer }
        costCents: { type: integer, format: int64, description: "Derived server-side: ingredient cost of one portion, sub-recipes rolled up." }
        lines: { type: array, items: { $ref: "#/components/schemas/RecipeLine" } }
        consumes:
          type: array
          default: []
          description: "What one portion really takes off the shelf once sub-recipes are followed (V37). Equals the ingredient list for a simple recipe; for a dish built on uncounted prep items these are the raw goods underneath them, which appear nowhere in `lines`."
          items: { $ref: "#/components/schemas/RecipeConsumption" }
      required: [productId, productName, name, yieldUnits, wastePctBp, costCents, lines]
    AccountingConnection:
      type: object
      properties:
        provider: { type: string, enum: [XERO, SAGE, NONE] }
        organisationRef: { type: string, nullable: true, description: "The provider's id for the books — Xero tenant / Sage business. Not a secret." }
        syncFromDate: { type: string, nullable: true, description: "ISO date. Journals before it are never pushed, so a closed period stays closed." }
        active: { type: boolean }
        salesDetail: { type: string, enum: [EACH, DAILY], default: EACH, description: "How sales reach the package (T-11.1): each sale, or one daily summary per location. A sale is sent once either way." }
        lastBatchAt: { type: integer, format: int64, nullable: true }
        lastError: { type: string, nullable: true }
        credentialsPresent: { type: boolean, default: false, description: "Whether this server holds credentials for the provider. False with an active connection means the token needs renewing." }
        pending: { type: integer, format: int64, default: 0, description: "Claimed but unresolved — retried next run with the same key." }
        posted: { type: integer, format: int64, default: 0 }
        failed: { type: integer, format: int64, default: 0 }
      required: [provider, active]
    AccountingConnectionRequest:
      type: object
      properties:
        provider: { type: string, enum: [XERO, SAGE, NONE], description: "NONE pauses the push without forgetting the settings." }
        organisationRef: { type: string, nullable: true }
        syncFromDate: { type: string, nullable: true, description: "ISO date (yyyy-MM-dd). 400 invalid_date otherwise." }
        active: { type: boolean, default: true }
        salesDetail: { type: string, nullable: true, enum: [EACH, DAILY], description: "EACH sale its own journal, or one DAILY summary per location and closed trading day (T-11.1). Absent keeps what is saved; 400 unknown_sales_detail otherwise." }
      required: [provider]
    AccountingSyncResult:
      type: object
      properties:
        provider: { type: string }
        posted: { type: integer }
        failed: { type: integer, description: "Refused for a reason retrying will not fix." }
        skipped: { type: integer }
        inFlight: { type: integer, description: "Outcome unknown — still claimed, retried next run with the same idempotency key." }
        notConfigured: { type: boolean, default: false }
      required: [provider, posted, failed, skipped, inFlight]
    ServiceCostingLine:
      type: object
      required: [kind, description]
      properties:
        kind: { type: string, enum: [LABOUR, PART] }
        description: "{ type: string, description: What the customer reads. Required even for a part — products get renamed. }"
        productId: { type: string, nullable: true, description: PART only, and required for one — a real catalogue product, so stock moves. }
        variantId: { type: string, nullable: true }
        hoursHundredths: { type: integer, nullable: true, description: LABOUR only. 1.75 h is 175, so no float touches money. }
        rateCentsPerHour: { type: integer, format: int64, nullable: true, description: LABOUR only. }
        quantity: { type: integer, format: int64, nullable: true, description: PART only. }
        unitPriceCents:
          type: integer
          format: int64
          nullable: true
          description: PART — null prices from the catalogue at the job's location and freezes it.
    ServiceCosting:
      type: object
      required: [exists]
      properties:
        id: { type: string, nullable: true }
        exists: { type: boolean, description: false when the job has no sheet yet. }
        serviceOrderId: { type: string, nullable: true }
        actualTotalCents: { type: integer, format: int64, description: Labour plus parts, as the job stands. }
        writeOffCents: { type: integer, format: int64 }
        chargeableCents: { type: integer, format: int64, description: actualTotal minus writeOff — what handover will bill. }
        overrunCents:
          type: integer
          format: int64
          description: How far chargeable exceeds the approved figure. Non-zero blocks handover.
        labourCents: { type: integer, format: int64 }
        partsCents: { type: integer, format: int64 }
        lines:
          type: array
          items: { $ref: "#/components/schemas/ServiceCostingLine" }
    RoomChargeConnection:
      type: object
      required: [connected]
      properties:
        connected: { type: boolean }
        system: { type: string, nullable: true, description: OPERA | MEWS }
        propertyRef: { type: string, nullable: true }
        credentialsPresent:
          type: boolean
          description: Distinguishes "nobody connected it" from "the token expired".
        offered: { type: boolean, description: "Whether the system is one room charge is offered for: proven end to end (T-37.8). False for every system until one is." }
        notOfferedBecause: { type: string, nullable: true, description: "Why room charge is switched off for this venue, in words to read." }
        allowUnverifiedCharge: { type: boolean }
        active: { type: boolean }
    RoomChargeConnectionRequest:
      type: object
      properties:
        system: { type: string, nullable: true, description: OPERA | MEWS | NONE. NONE pauses without forgetting. }
        propertyRef: { type: string, nullable: true }
        allowUnverifiedCharge: { type: boolean }
        active: { type: boolean }
    RoomChargeLookup:
      type: object
      required: [status]
      properties:
        status: { type: string, enum: [OK, REFUSED] }
        room: { type: string }
        guestName: { type: string, nullable: true, description: Read this back to the person in front of you. }
        reservationRef: { type: string, nullable: true }
        notConnected: { type: boolean }
        reason: { type: string, nullable: true }
    RoomChargeRequest:
      type: object
      required: [transactionId, room]
      properties:
        transactionId: { type: string }
        room: { type: string }
        reservationRef: { type: string, nullable: true }
        amountCents: { type: integer, format: int64, nullable: true }
    RoomChargePosting:
      type: object
      required: [transactionId, status]
      properties:
        transactionId: { type: string }
        status: { type: string, enum: [PENDING, POSTED, FAILED, REVERSED] }
        alreadyPosted: { type: boolean, description: A repeat collapsed onto the existing claim; nothing was re-sent. }
        room: { type: string, nullable: true }
        guestName: { type: string, nullable: true }
        verified: { type: boolean, description: false when the PMS could not be reached and the property allows it anyway. }
        verifyNote: { type: string, nullable: true }
        providerRef: { type: string, nullable: true }
        idempotencyKey: { type: string }
        attempts: { type: integer }
        lastError: { type: string, nullable: true }
        postedAt: { type: integer, format: int64, nullable: true }
    ProductFeedStore:
      type: object
      required: [storeId, displayName, provider, feedUrl]
      properties:
        storeId: { type: string }
        displayName: { type: string }
        provider: { type: string, description: SHOPIFY | WOOCOMMERCE }
        feedUrl:
          type: string
          description: >-
            Paste into Merchant Center or Commerce Manager. Non-expiring by design — an expiring
            feed URL takes a shop's Shopping presence dark on a date nobody wrote down.
    ShippingRateBand:
      type: object
      required: [priceCents]
      properties:
        zone: { type: string, nullable: true, description: null applies to every zone. }
        upToG:
          type: integer
          nullable: true
          description: Inclusive gram ceiling. null is the open top ("and above").
        priceCents: { type: integer, format: int64, minimum: 0 }
    ShippingMethod:
      type: object
      required: [id, name, kind, flatCents, active, sortOrder]
      properties:
        id: { type: string }
        name: { type: string }
        kind: { type: string, enum: [FLAT, WEIGHT, ZONE] }
        flatCents: { type: integer, format: int64 }
        freeOverCents:
          type: integer
          format: int64
          nullable: true
          description: Applies only after a band matched, so it never rescues an undeliverable address.
        leadTimeNote: { type: string, nullable: true }
        active: { type: boolean }
        sortOrder: { type: integer }
        bands:
          type: array
          items: { $ref: "#/components/schemas/ShippingRateBand" }
    ShippingMethodRequest:
      type: object
      required: [name, kind]
      properties:
        id: { type: string, nullable: true }
        name: { type: string }
        kind: { type: string, enum: [FLAT, WEIGHT, ZONE] }
        flatCents: { type: integer, format: int64, default: 0 }
        freeOverCents: { type: integer, format: int64, nullable: true }
        leadTimeNote: { type: string, nullable: true }
        active: { type: boolean, default: true }
        sortOrder: { type: integer, default: 0 }
        bands:
          type: array
          description: Replaces every band on the method.
          items: { $ref: "#/components/schemas/ShippingRateBand" }
    ShippingZone:
      type: object
      required: [zone, postcodePrefix]
      properties:
        zone: { type: string }
        postcodePrefix: { type: string, description: The longest matching prefix wins. }
    ShippingQuoteRequest:
      type: object
      properties:
        postcode: { type: string, nullable: true }
        weightG: { type: integer, nullable: true, description: A weighed parcel. Wins over lines. }
        lines:
          type: array
          nullable: true
          description: The basket, so the server weighs it from the catalogue.
          items:
            type: object
            required: [productId, quantity]
            properties:
              productId: { type: string }
              quantity: { type: integer, format: int64 }
        subtotalCents: { type: integer, format: int64, default: 0 }
    ShippingQuoteOption:
      type: object
      required: [methodId, methodName, available]
      properties:
        methodId: { type: string }
        methodName: { type: string }
        priceCents: { type: integer, format: int64, nullable: true }
        free: { type: boolean }
        available: { type: boolean }
        reason:
          type: string
          nullable: true
          enum: [needs_weight, no_band, zone_not_served]
    ShippingQuoteResponse:
      type: object
      required: [options]
      properties:
        zone: { type: string, nullable: true }
        weightG: { type: integer, nullable: true }
        options:
          type: array
          items: { $ref: "#/components/schemas/ShippingQuoteOption" }
    ShipmentRequest:
      type: object
      required: [recipientName, line1, city, postcode]
      properties:
        locationId: { type: string, nullable: true }
        transactionId: { type: string, nullable: true }
        orderRef: { type: string, nullable: true }
        methodId: { type: string, nullable: true }
        recipientName: { type: string }
        phone: { type: string, nullable: true }
        line1: { type: string }
        line2: { type: string, nullable: true }
        city: { type: string }
        postcode: { type: string }
        country: { type: string, nullable: true, default: ZA }
        weightG: { type: integer, nullable: true }
        priceCents:
          type: integer
          format: int64
          nullable: true
          description: What the customer was charged. Omit to derive from the method.
        notes: { type: string, nullable: true }
    Shipment:
      type: object
      required: [id, waybillNo, methodName, recipientName, line1, city, postcode, country, priceCents, status, createdAt]
      properties:
        id: { type: string }
        waybillNo: { type: string, description: 'WB-yyyyMMdd-NNNNNN, unique per tenant.' }
        transactionId: { type: string, nullable: true }
        orderRef: { type: string, nullable: true }
        methodName: { type: string }
        trackingRef: { type: string, nullable: true }
        recipientName: { type: string }
        phone: { type: string, nullable: true }
        line1: { type: string }
        line2: { type: string, nullable: true }
        city: { type: string }
        postcode: { type: string }
        country: { type: string }
        zone: { type: string, nullable: true }
        weightG: { type: integer, nullable: true, description: null means unweighed, not weightless. }
        priceCents: { type: integer, format: int64 }
        status: { type: string, enum: [PENDING, PACKED, SHIPPED, DELIVERED, CANCELLED] }
        notes: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
    AccountingPosting:
      type: object
      properties:
        entryId: { type: string }
        provider: { type: string }
        status: { type: string, enum: [PENDING, POSTED, FAILED, SKIPPED] }
        providerRef: { type: string, nullable: true, description: "Their id for the document — the audit trail from a line here to a line in their ledger." }
        attempts: { type: integer, default: 0 }
        lastError: { type: string, nullable: true }
        postedAt: { type: integer, format: int64, nullable: true }
      required: [entryId, provider, status]
    RecipeConsumption:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string }
        units: { type: integer, format: int64, description: "In the product's stock unit." }
        stockUnit: { type: string, enum: [each, g, ml] }
        display: { type: string, description: "The way a person says it — \"105 g\"." }
        costCents: { type: integer, format: int64, default: 0 }
      required: [productId, productName, units, stockUnit, display]
    AdjustmentRequest:
      type: object
      properties:
        productId: { type: string }
        locationId: { type: string }
        deltaUnits: { type: integer, format: int64 }
        reason: { type: string }
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true, description: "Ignored: who adjusted is the caller." }
        approverPin: { type: string, nullable: true, description: "Another manager's PIN, sent only after a 409 second_approver_required. Never stored or returned." }
      required: [productId, locationId, deltaUnits, reason]

    # ── Reorder engine (V46) ──
    ReorderRule:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        minUnits: { type: integer, format: int64, description: "Floor for the reorder point. The engine may compute a higher trigger from velocity; it never uses a lower one." }
        maxUnits: { type: integer, format: int64, description: "Fill-to level. 0 means unset, and the target then falls out of velocity instead." }
        safetyStockUnits: { type: integer, format: int64 }
        reviewPeriodDays: { type: integer, description: "How long the shop is exposed *before* the next order is placed. Omitting this term is the most common mistake in a reorder formula." }
        active: { type: boolean, description: "False is how a manager says \"do not reorder this\". Deleting the rule is a different act — see DELETE /reorder/rules/{id}." }
        humanOverride: { type: boolean, description: "True pins the numbers: POST /reorder/rules/recalculate counts the rule and skips it." }
        updatedByStaffId: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
        updatedAt: { type: integer, format: int64 }
      required: [id, locationId, productId, productName, minUnits, maxUnits, safetyStockUnits, reviewPeriodDays, active, humanOverride, createdAt, updatedAt]
    ReorderRuleUpsert:
      type: object
      description: >
        A patch keyed on (locationId, productId, variantId). Every field except the key is optional
        and an absent one keeps its stored value rather than clearing it.
      properties:
        locationId: { type: string }
        productId: { type: string }
        variantId: { type: string, nullable: true, description: "Part of the key. Absent addresses the product-level rule, which is a different row from any variant's." }
        minUnits: { type: integer, format: int64, nullable: true }
        maxUnits: { type: integer, format: int64, nullable: true }
        safetyStockUnits: { type: integer, format: int64, nullable: true }
        reviewPeriodDays: { type: integer, nullable: true, description: "At least 1. Defaults to 7 on create." }
        active: { type: boolean, nullable: true, description: "Defaults to true on create." }
        humanOverride: { type: boolean, nullable: true, description: "Defaults to **true** on create through this endpoint — somebody typed these numbers." }
        byStaffId: { type: string, nullable: true }
      required: [locationId, productId]
    ReorderRecalculateRequest:
      type: object
      properties:
        locationId: { type: string }
        windowDays: { type: integer, nullable: true, default: 28, description: "Demand window, clamped to 1-365." }
        createMissing: { type: boolean, nullable: true, default: false, description: "Writes a rule for every SKU with measured demand. Off by default — a bootstrap, not a refresh." }
        byStaffId: { type: string, nullable: true }
      required: [locationId]
    ReorderRecalculateResult:
      type: object
      properties:
        locationId: { type: string }
        windowDays: { type: integer }
        scanned: { type: integer, description: "Cover lines considered." }
        updated: { type: integer }
        created: { type: integer, description: "Always 0 unless createMissing was set." }
        skippedOverridden: { type: integer, description: "Rules a human pinned." }
        skippedInactive: { type: integer, description: "Rules already saying do not reorder this." }
      required: [locationId, windowDays, scanned, updated, created, skippedOverridden, skippedInactive]
    ReorderCoverLine:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        ruleId: { type: string, nullable: true, description: "Absent when this SKU is planned from velocity alone." }
        ruleActive: { type: boolean }
        humanOverride: { type: boolean }
        onHandUnits: { type: integer, format: int64 }
        reservedUnits: { type: integer, format: int64 }
        inboundUnits: { type: integer, format: int64, description: "Outstanding units on SENT and PARTIAL purchase orders only. A DRAFT has not been sent, so nothing is coming." }
        availableUnits: { type: integer, format: int64, description: "onHand - reserved + inbound. Deliberately not floored at zero: an oversold location's shortfall has to include what is already promised and missing." }
        windowDays: { type: integer }
        soldUnits: { type: integer, format: int64 }
        returnedUnits: { type: integer, format: int64 }
        demandUnits: { type: integer, format: int64, description: "Sold less returned. Only this drives velocity." }
        shrinkageUnits: { type: integer, format: int64, description: "Wastage, expiry and RTV. Reported so a buyer can tell \"we sold forty\" from \"we sold twenty and threw twenty away\" — never folded into demand." }
        velocityMilliPerDay: { type: integer, format: int64, description: "Units per day x 1000. An integer, so the arithmetic is exactly reproducible." }
        coverDaysMilli: { type: integer, format: int64, nullable: true, description: "Days of cover x 1000, computed on on-hand rather than available. **Absent when nothing sold in the window** — not a sentinel for infinity." }
        coverDays: { type: integer, nullable: true, description: "coverDaysMilli truncated to whole days, which understates cover and so errs towards ordering sooner." }
        leadTimeDays: { type: integer }
        reviewPeriodDays: { type: integer }
        safetyStockUnits: { type: integer, format: int64 }
        reorderPointUnits: { type: integer, format: int64, description: "Where ordering starts: lead-time demand plus safety stock, floored by the rule's minUnits." }
        targetUnits: { type: integer, format: int64, description: "Where ordering fills to." }
        shortfallUnits: { type: integer, format: int64, description: "target - available, floored at zero. Before pack size and MOQ." }
        supplierId: { type: string, nullable: true }
        supplierName: { type: string, nullable: true }
        supplierSku: { type: string, nullable: true }
        currency: { type: string, nullable: true }
        packSize: { type: integer, nullable: true }
        minOrderQty: { type: integer, nullable: true }
        orderUnits: { type: integer, format: int64, description: "Cases to place. Zero unless status is BELOW_REORDER_POINT." }
        suggestedUnits: { type: integer, format: int64, description: "orderUnits x packSize — the stock units that would arrive, and what goes on the PO line." }
        unitCostCents: { type: integer, format: int64, description: "Pack-derived, rounded up." }
        lineTotalCents: { type: integer, format: int64, description: "unitCostCents x suggestedUnits, which is how every PO line in Ruva is totalled." }
        caseTotalCents: { type: integer, format: int64, description: "What the supplier will actually invoice: whole cases at the case price. Up to (packSize - 1) cents per case below lineTotalCents, because the per-unit cost rounds up. Reconcile against this one." }
        moqForced: { type: boolean, description: "The minimum order quantity forced more than the shortfall needed." }
        packSurplusUnits: { type: integer, format: int64, description: "Stock units above the shortfall, forced by pack size or MOQ." }
        status:
          type: string
          enum: [BELOW_REORDER_POINT, COVERED, NO_SUPPLIER, NO_POLICY, RULE_INACTIVE]
          description: >
            `BELOW_REORDER_POINT` is the only status that orders. `NO_SUPPLIER` needs stock but no
            active supplier lists the SKU, which is a buying decision rather than an arithmetic one.
            `NO_POLICY` has neither measured demand nor a par level, so there is nothing to base an
            order on. `RULE_INACTIVE` is shown rather than hidden, so it is never invisibly excluded.
      required: [productId, productName, ruleActive, humanOverride, onHandUnits, reservedUnits, inboundUnits, availableUnits, windowDays, soldUnits, returnedUnits, demandUnits, shrinkageUnits, velocityMilliPerDay, leadTimeDays, reviewPeriodDays, safetyStockUnits, reorderPointUnits, targetUnits, shortfallUnits, orderUnits, suggestedUnits, unitCostCents, lineTotalCents, caseTotalCents, moqForced, packSurplusUnits, status]
    ReorderCoverResponse:
      type: object
      properties:
        locationId: { type: string }
        windowDays: { type: integer }
        windowFromMs: { type: integer, format: int64 }
        windowToMs: { type: integer, format: int64 }
        totalSkus: { type: integer, description: "Rows matching the filter, before the page limit." }
        suggestionCount: { type: integer, description: "How many lines would be ordered, regardless of the filter applied." }
        lines: { type: array, items: { $ref: "#/components/schemas/ReorderCoverLine" } }
      required: [locationId, windowDays, windowFromMs, windowToMs, totalSkus, suggestionCount, lines]
    GenerateDraftPosRequest:
      type: object
      properties:
        locationId: { type: string }
        windowDays: { type: integer, nullable: true, default: 28 }
        supplierIds: { type: array, nullable: true, items: { type: string }, description: "Narrows generation to these suppliers; empty or absent does all of them." }
        byStaffId: { type: string, nullable: true }
      required: [locationId]
    GeneratedDraft:
      type: object
      properties:
        poId: { type: string }
        poNumber: { type: string }
        supplierId: { type: string }
        created: { type: boolean, description: "False when an open generated draft was reused instead of a new PO being raised." }
        linesAdded: { type: integer }
        linesAlreadyOnDraft: { type: integer, description: "Suggestions skipped because the draft already carried the SKU. Those lines are left untouched, quantity included." }
        addedTotalCents: { type: integer, format: int64 }
        poTotalCents: { type: integer, format: int64 }
      required: [poId, poNumber, supplierId, created, linesAdded, linesAlreadyOnDraft, addedTotalCents, poTotalCents]
    GenerateDraftPosResponse:
      type: object
      properties:
        locationId: { type: string }
        windowDays: { type: integer }
        drafts: { type: array, items: { $ref: "#/components/schemas/GeneratedDraft" } }
        skippedSuppliers:
          type: array
          items: { type: string }
          description: >
            Suppliers whose open draft was sent by somebody else mid-run. Their stock is now inbound,
            so the next run will not suggest it again — reported rather than silently dropped, so a
            buyer is not left wondering where a supplier went.
      required: [locationId, windowDays, drafts]

    # ── Suppliers & Purchasing ──
    SupplierDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        contactName: { type: string, nullable: true }
        contactEmail: { type: string, nullable: true }
        contactPhone: { type: string, nullable: true }
        address: { type: string, nullable: true }
        vatNumber: { type: string, nullable: true }
        paymentTermsDays: { type: integer }
        active: { type: boolean }
      required: [id, name, paymentTermsDays, active]
    SupplierCreateRequest:
      type: object
      properties:
        name: { type: string }
        contactName: { type: string, nullable: true }
        contactEmail: { type: string, nullable: true }
        contactPhone: { type: string, nullable: true }
        address: { type: string, nullable: true }
        vatNumber: { type: string, nullable: true }
        paymentTermsDays: { type: integer, default: 30 }
      required: [name]
    SupplierUpdateRequest:
      type: object
      description: "Partial supplier update incl. `active` (BO-F32). All fields keep-on-absent."
      properties:
        name: { type: string, nullable: true }
        contactName: { type: string, nullable: true }
        contactEmail: { type: string, nullable: true }
        contactPhone: { type: string, nullable: true }
        address: { type: string, nullable: true }
        vatNumber: { type: string, nullable: true }
        paymentTermsDays: { type: integer, nullable: true }
        notes: { type: string, nullable: true }
        active: { type: boolean, nullable: true }
    PoLineRequest:
      type: object
      properties:
        productId: { type: string }
        quantityUnits: { type: integer, format: int64 }
        unitCostCents: { type: integer, format: int64 }
      required: [productId, quantityUnits, unitCostCents]
    PoCreateRequest:
      type: object
      properties:
        supplierId: { type: string }
        locationId: { type: string }
        expectedAt: { type: integer, format: int64, nullable: true }
        notes: { type: string, nullable: true }
        lines: { type: array, items: { $ref: "#/components/schemas/PoLineRequest" } }
        byStaffId: { type: string, nullable: true }
      required: [supplierId, locationId, lines]
    PurchaseOrderDto:
      type: object
      properties:
        id: { type: string }
        poNumber: { type: string }
        supplierId: { type: string }
        locationId: { type: string }
        status: { type: string }
        expectedAt: { type: integer, format: int64, nullable: true }
        receivedAt: { type: integer, format: int64, nullable: true }
        totalCents: { type: integer, format: int64 }
      required: [id, poNumber, supplierId, locationId, status, totalCents]
    PoLineDto:
      type: object
      properties:
        id: { type: string }
        productId: { type: string }
        quantityUnits: { type: integer, format: int64 }
        receivedUnits: { type: integer, format: int64 }
        unitCostCents: { type: integer, format: int64 }
        lineTotalCents: { type: integer, format: int64 }
        sortOrder: { type: integer }
      required: [id, productId, quantityUnits, receivedUnits, unitCostCents, lineTotalCents, sortOrder]
    PurchaseOrderDetailDto:
      type: object
      description: Full PO detail (V16) — header with resolved supplierName plus lines with resolved productName.
      properties:
        id: { type: string }
        poNumber: { type: string }
        supplierId: { type: string }
        supplierName: { type: string, description: "Resolved supplier name (falls back to supplierId if the supplier row is gone)." }
        status: { type: string }
        expectedAt: { type: integer, format: int64, nullable: true }
        notes: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/PoDetailLineDto" } }
      required: [id, poNumber, supplierId, supplierName, status, createdAt, totalCents, lines]
    PoDetailLineDto:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string, description: "Resolved product name (falls back to productId if the product row is gone)." }
        qty: { type: integer, format: int64 }
        unitCostCents: { type: integer, format: int64 }
        lineTotalCents: { type: integer, format: int64 }
        lineId: { type: string, nullable: true, description: "The line's own id; a change sends it back to keep the line." }
        receivedUnits: { type: integer, format: int64, description: "Units already received against the line." }
      required: [productId, productName, qty, unitCostCents, lineTotalCents]
    PoReceiveLine:
      type: object
      properties:
        lineId: { type: string }
        receivedQty: { type: integer, format: int64, description: "Units accepted into stock." }
        damagedUnits: { type: integer, format: int64, default: 0, description: "Units that came off the van unusable (T-8.2): recorded on the goods-received note, never stocked, and they settle the order line." }
        reason: { type: string, nullable: true, description: "Why a line is short or damaged, recorded on the note. Not required by the server." }
      required: [lineId, receivedQty]
    PoReceiveRequest:
      type: object
      properties:
        lines: { type: array, items: { $ref: "#/components/schemas/PoReceiveLine" }, nullable: true, description: "Omit (or send no body) to receive every outstanding unit." }
        batchCodes: { type: object, additionalProperties: { type: string }, nullable: true, description: "Supplier lot codes by PO line id, for batch-tracked products (V23)." }
        expiryDates: { type: object, additionalProperties: { type: integer, format: int64 }, nullable: true, description: "Expiry dates by PO line id, for batch-tracked products." }
        opId: { type: string, nullable: true, description: "Minted by the device before the first attempt (T-8.1). The same op arriving again — a retry or an outbox replay — moves stock once; reused for other work it is refused `op_id_conflict`. Absent: answered as before, not replay-safe." }
        occurredAt: { type: integer, format: int64, nullable: true, description: "When the work happened, in server time. Absent means now; kept when within the last 7 days, otherwise refused `invalid_occurred_at`." }
        byStaffId: { type: string, nullable: true }
    ReceivableOrder:
      type: object
      properties:
        id: { type: string }
        poNumber: { type: string }
        supplierId: { type: string }
        supplierName: { type: string, nullable: true }
        locationId: { type: string }
        status: { type: string, description: "SENT | PARTIAL" }
        expectedAt: { type: integer, format: int64, nullable: true }
        lines: { type: array, items: { $ref: "#/components/schemas/ReceivableLine" } }
      required: [id, poNumber, supplierId, locationId, status, lines]
    ReceivableLine:
      type: object
      properties:
        lineId: { type: string }
        productId: { type: string }
        productName: { type: string, nullable: true }
        variantId: { type: string, nullable: true }
        orderedUnits: { type: integer, format: int64 }
        receivedUnits: { type: integer, format: int64, description: "The line's own received units — what a receipt adds to." }
      required: [lineId, productId, orderedUnits, receivedUnits]

    # ── Pricing ──
    PriceRuleDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        scopeType: { type: string, description: "PRODUCT | CATEGORY | ALL" }
        scopeId: { type: string, nullable: true }
        ruleType: { type: string, description: "PERCENT_OFF | FIXED_OFF | OVERRIDE_PRICE" }
        value: { type: integer, format: int64 }
        daysOfWeek: { type: string }
        startMinute: { type: integer }
        endMinute: { type: integer }
        priority: { type: integer }
        active: { type: boolean }
      required: [id, name, scopeType, ruleType, value, daysOfWeek, startMinute, endMinute, priority, active]
    PriceRuleCreateRequest:
      type: object
      properties:
        name: { type: string }
        scopeType: { type: string, description: "PRODUCT | CATEGORY | ALL" }
        scopeId: { type: string, nullable: true }
        ruleType: { type: string, description: "PERCENT_OFF | FIXED_OFF | OVERRIDE_PRICE" }
        value: { type: integer, format: int64 }
        daysOfWeek: { type: string, default: MTWRFSU }
        startMinute: { type: integer, default: 0 }
        endMinute: { type: integer, default: 1439 }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        priority: { type: integer, default: 0 }
      required: [name, scopeType, ruleType, value]

    # ── Customer QR ──
    QrCategoryDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        courseType: { type: string }
        colorHex: { type: string }
        sortOrder: { type: integer }
        dayparts: { type: array, items: { $ref: "#/components/schemas/Daypart" }, description: "The times of day it is served at THIS location (T-25.7); empty = all day. A category outside them is not in `categories` at all; the windows let a kept menu re-judge itself on the device's clock." }
        afterHours: { type: boolean, default: false, description: "T-41.51 - guests keep ordering from it after the kitchen closes. While `kitchenHours` say closed, a table's and a kiosk's menu shows such categories first and orderable (core `orderableAt`), the rest after them as not available now, and an order of only them is taken." }
      required: [id, name, courseType, colorHex, sortOrder]
    QrModifierOptionDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        priceDeltaCents: { type: integer, format: int64 }
      required: [id, name, priceDeltaCents]
    QrModifierGroupDto:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        required: { type: boolean }
        multiSelect: { type: boolean }
        minSelect: { type: integer }
        maxSelect: { type: integer }
        options: { type: array, items: { $ref: "#/components/schemas/QrModifierOptionDto" } }
      required: [id, name, required, multiSelect, minSelect, maxSelect, options]
    QrProductDto:
      type: object
      properties:
        id: { type: string }
        categoryId: { type: string }
        name: { type: string }
        description: "{ type: string, nullable: true }"
        emoji: { type: string, nullable: true }
        imageUrl: { type: string, nullable: true }
        tileEmoji: { type: string, nullable: true, description: "The emoji a guest's tile draws instead of the dish's letters (T-39.24): the dish's own, only where the location's `showDishEmoji` is on and the dish has one; null otherwise. `emoji` itself is unchanged (the kiosk reads it)." }
        priceCents: { type: integer, format: int64 }
        vatType: { type: string }
        allergens: { type: array, items: { type: string }, default: [], description: "Allergen names from the product record." }
        dietary: { type: array, items: { type: string }, default: [], description: "What the dish suits, as the venue marked it (T-6.4): VEGETARIAN, VEGAN, HALAAL, GLUTEN_FREE, NUT_FREE, DAIRY_FREE. The kiosk filters by these." }
        ageRestrictedYears: { type: integer, nullable: true, description: "T-37.1 - the age this dish is sold from (its own, or its category's); the guest confirms it once, and the order carries `ageConfirmed`." }
        modifierGroups: { type: array, items: { $ref: "#/components/schemas/QrModifierGroupDto" }, default: [] }
      required: [id, categoryId, name, priceCents, vatType]
    QrFeaturesDto:
      type: object
      description: |
        What this venue's QR licence and payment rails let a guest do (V72). The guest UI renders from
        this rather than guessing.
      properties:
        cardCheckout: { type: boolean, default: false, description: "Yoco hosted checkout — 'Pay now' hands back a checkout link." }
        snapscan: { type: boolean, default: false, description: "Static SnapScan QR as a payment surface. False while SnapScan is not offered." }
        payOnline: { type: boolean, default: false, description: "Any online rail at all — false means every order is pay-at-counter." }
        addToTab: { type: boolean, default: false, description: "'Add to my table's bill' — true only for Restaurant-licensed venues." }
        phoneTab: { type: boolean, default: false, description: "The guest may open a tab and pay it once on their phone (T-30.14): a till-less location whose manager switched it on, with an online rail. Send it as `paymentMode: ADD_TO_TAB` with `tabName` and `tabPhone`." }
        takesOrders: { type: boolean, default: true, description: "False where the venue has no way for a guest to pay: no online rail, no pay at the counter, no tab and not the sample café. The guest app says so before a basket is built; `POST /qr/orders` still answers 503 `online_payment_unavailable` (walkthrough 14, G6-3). An older server omits it, which reads as true." }
        phoneTabLimitCents: { type: integer, format: int64, default: 0, description: "What a phone tab may owe before the next round asks the guest to pay first (T-30.14); 0 = no credit, and 0 where no tab is offered." }
        payAtCounter: { type: boolean, default: false, description: "The guest may choose to pay at the counter and the back office takes the payment (T-1.20): a till-less location whose manager switched it on. Send it as `paymentMode: PAY_AT_COUNTER`." }
        kioskMayHold: { type: boolean, default: false, description: "Somebody takes payment at a counter for an order a self-order kiosk keeps while it cannot confirm it (T-26.2): a till, the back office's counter, or the sample café. Where false a kiosk keeps no order to send later, since it would be refused." }
        delivery: { type: boolean, default: false, description: "The location delivers (T-13.3); the guest app offers DELIVERY only when true." }
        driverDirections: { type: boolean, default: false, description: "The location delivers and a courier takes the venue's deliveries (T-37.14): the guest app offers 'Directions for the driver' (`dropoffNotes`) only when true. Where the venue drives its own, an order's `dropoffNotes` are not kept." }
        sample: { type: boolean, default: false, description: "The sample café the public site links to (T-6.5): nothing is charged and no kitchen receives the order. It is offered no payment rail, its orders are placed all the same, its payment screen answers `409 sample_venue`, and its orders are deleted after a day." }
    BrandDto:
      type: object
      properties:
        accentHex: { type: string, nullable: true, example: "#1F6F5C" }
        logoUrl: { type: string, nullable: true, example: "https://example.test/logo.png", description: "On save, an https link to a logo: fetched once and stored as the logo upload (T-41.56), then not kept. Reads back null, or a link stored before T-41.56 not yet copied in (never sent to a guest); the logo is `logoImageUrl`." }
        coverUrl: { type: string, nullable: true, example: "https://example.test/cover.jpg", description: "On save, an https link to a header picture: fetched once and stored as the cover upload (T-41.56), then not kept. Reads back null, or a link stored before T-41.56 not yet copied in (never sent to a guest); the picture is `coverImageUrl`." }
        logoImageUrl: { type: string, nullable: true, readOnly: true, description: "Where the logo is served from, on Ruva's own server: the only logo a guest is sent. Ignored on save." }
        coverImageUrl: { type: string, nullable: true, readOnly: true, description: "Where the header picture is served from, on Ruva's own server: the only one a guest is sent. Ignored on save." }
    BrandImageUpload:
      type: object
      required: [imageBase64]
      properties:
        imageBase64: { type: string, description: The picture's bytes, base64. }
        mime: { type: string, description: Advisory only; the type is read from the bytes., example: image/png }
    BrandImageStored:
      type: object
      properties:
        kind: { type: string, enum: [logo, cover] }
        url: { type: string, nullable: true, example: "/api/v1/brand-images/demo-cape-town/logo?v=1763200000000" }
    DomainStatusDto:
      type: object
      properties:
        host: { type: string, nullable: true, example: "order.example.co.za" }
        recordName: { type: string, nullable: true, example: "_ruva.order.example.co.za" }
        recordValue: { type: string, nullable: true, example: "ruva-verify=3f9c2a" }
        verified: { type: boolean }
        inUse: { type: boolean, description: "Whether new table codes are printed on this host (T-41.103)." }
    WhatsAppUsageView:
      type: object
      description: This month's WhatsApp (T-5.5). Money in cents.
      properties:
        month: { type: string, description: "YYYY-MM, South African time" }
        rateCents: { type: integer, format: int64 }
        locations:
          type: array
          items:
            type: object
            properties:
              locationId: { type: string }
              locationName: { type: string }
              on: { type: boolean, description: "Whether guests are sent WhatsApp from this location. False until someone switches it on (D-132)." }
              messages: { type: integer }
              cents: { type: integer, format: int64 }
        businessMessages: { type: integer, description: "Messages that named no location (a campaign, a statement)." }
        businessCents: { type: integer, format: int64 }
        totalMessages: { type: integer }
        totalCents: { type: integer, format: int64, description: "The bill's WhatsApp line for the month so far." }
      required: [month, rateCents, locations]
    KitchenDay:
      type: object
      description: "One day's kitchen hours at a location (T-39.20, core `KitchenDay`): minutes since the location's local midnight. A close at or before the opening is the next morning's (Friday 18:00 to 02:00 runs into Saturday). A weekday with no entry is a day the kitchen does not open."
      properties:
        weekday: { type: integer, minimum: 1, maximum: 7, description: "ISO: 1 Monday … 7 Sunday." }
        opensAt: { type: integer, minimum: 0, maximum: 1439 }
        closesAt: { type: integer, minimum: 0, maximum: 1439 }
      required: [weekday, opensAt, closesAt]
    KitchenWeek:
      type: object
      properties:
        days: { type: array, items: { $ref: "#/components/schemas/KitchenDay" }, description: "At most one per weekday; empty sets no hours." }
    WhatsAppOrderingView:
      type: object
      properties:
        on: { type: boolean, description: "WhatsApp ordering at this location (off by default)." }
        whatsAppOn: { type: boolean, description: "The location's WhatsApp switch: orders are taken only while it is on too." }
        ready: { type: boolean, description: "Whether this server has an ordering number and a Flow; false = no link is offered." }
        link: { type: string, nullable: true, description: "The chat guests open (Ruva's number, the location's reference already typed), to share or print as a QR code." }
      required: [on, whatsAppOn, ready]
    WhatsAppOrderingChange:
      type: object
      properties:
        on: { type: boolean }
        newLink: { type: boolean, default: false, description: "Mint a new reference: every link and QR code shared before stops opening the menu." }
      required: [on]
    OrderingPaceState:
      type: object
      description: Busy mode at a location (T-1.15); server `OrderingPace` decides every figure.
      properties:
        locationId: { type: string }
        ordering: { type: string, enum: [open, paused] }
        resumeAt: { type: integer, format: int64, nullable: true }
        extraMinutes: { type: integer }
        baseMinutes: { type: integer, description: The location's kitchen notice (order windows' lead minutes). }
        loadMinutes: { type: integer, description: "One per open kitchen ticket, rounded up to 5-minute steps, at most 60." }
        readyInMinutes: { type: integer, description: "base + extra + load: what a guest is told." }
        mayChange: { type: boolean, description: Whether the caller holds PACE_ORDERING. }
      required: [locationId, ordering, extraMinutes, baseMinutes, loadMinutes, readyInMinutes, mayChange]
    QrMenuResponse:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
        categories: { type: array, items: { $ref: "#/components/schemas/QrCategoryDto" } }
        products: { type: array, items: { $ref: "#/components/schemas/QrProductDto" } }
        features: { $ref: "#/components/schemas/QrFeaturesDto" }
        ordering: { type: string, enum: [open, paused], description: "Busy mode (T-1.15): while `paused`, POST /qr/orders is refused `409 ordering_paused`." }
        resumeAt: { type: integer, format: int64, nullable: true, description: "When a pause ends by itself, epoch millis; null while open, or paused until somebody resumes." }
        googleReviewUrl: { type: string, nullable: true, description: "The venue's Google review link (T-39.5): the guest app offers it, in a new tab, after any rating, never only a good one (T-35.21); null offers none." }
        terms: { $ref: "#/components/schemas/GuestTerms" }
        collectMaxQuantity: { type: integer, default: 50, description: "The most of one item a click-and-collect (takeaway) order may take at this venue (T-2.54, D-110): the venue's own setting, else 50. The guest app's takeaway stepper stops at it; a table order stays at 50 and a kiosk's takeaway takes the lower of this and 50 (T-39.18)." }
        readyInMinutes: { type: integer, nullable: true, description: "The wait a guest is told before paying: the location's kitchen notice + the kitchen's extra minutes + one minute per open kitchen ticket, rounded up to 5-minute steps (at most 60); never below the kitchen notice." }
        timezone: { type: string, nullable: true, description: "The location's time zone name (T-25.7), which its categories' times of day are read in." }
        kioskAsksHandover: { type: boolean, default: false, description: "The self-order kiosk asks \"Eat in\" or \"Take away\" before the menu (T-39.11); the choice is sent as the order's `fulfilmentType` (`DINE_IN` or `TAKEAWAY`). A phone ignores it." }
        kitchenHours: { type: array, items: { $ref: "#/components/schemas/KitchenDay" }, description: "The kitchen's hours, Monday first (T-39.20). The guest's menu header reads them in `timezone` with core `KitchenHours.at` and says until when the kitchen takes orders (\"Kitchen open till 22:00\", \"Kitchen closed till 17:00\"); empty = none set, and the header shows only the table. Outside the hours the checkout holds Pay and says when the kitchen takes orders again; POST /qr/orders is refused `409 kitchen_closed` (T-41.40). A takeaway or delivery may still choose a later time inside the hours, and Pay is offered once one is chosen (T-41.42)." }
        popular:
          type: array
          description: "\"Popular right now\" (T-41.26): ids of this menu's dishes guests chose most at this location over the recent weeks (`PopularDishes`): the dish on the most bills first, units breaking a tie, capped; voided and comped lines do not count. Empty until the venue has enough paid bills, and never a dish that is not in `products`."
          items: { type: string }
        upsell:
          type: array
          description: "The venue's checkout suggestions this menu can honour (T-6.3); the device picks up to three with core `Upsell.suggestions`."
          items: { $ref: "#/components/schemas/UpsellRule" }
        attract:
          type: array
          description: "What an idle kiosk loops through, in order (T-6.2); empty draws the plain invitation."
          items:
            type: object
            properties:
              id: { type: string }
              url: { type: string, description: Public picture, relative to the API origin. }
              dwellSeconds: { type: integer }
              altText: { type: string, nullable: true }
      required: [locationId, locationName, categories, products]
    QrOrderLine:
      type: object
      properties:
        productId: { type: string }
        quantity: { type: integer }
        note: { type: string, nullable: true }
        modifierOptionIds: { type: array, items: { type: string }, default: [] }
      required: [productId, quantity]
    OrderWindow:
      type: object
      description: When orders may be collected or delivered, and how many the kitchen takes per slot (T-13.3). Times are minutes from midnight, location time.
      properties:
        slotMinutes: { type: integer, default: 15, minimum: 5, maximum: 240 }
        capacity: { type: integer, nullable: true, minimum: 1, maximum: 10000, description: "Orders per slot, pickup and delivery together; null takes them all." }
        leadMinutes: { type: integer, default: 15, minimum: 0, maximum: 20160, description: "Notice the kitchen needs." }
        deliveryMinutes: { type: integer, default: 30, minimum: 0, maximum: 240, description: "Extra notice for a delivery." }
        openMinute: { type: integer, default: 0, minimum: 0, maximum: 1440 }
        closeMinute: { type: integer, default: 1440, minimum: 0, maximum: 1440 }
        daysAhead: { type: integer, default: 0, minimum: 0, maximum: 13, description: "Days beyond today a guest may order for." }
        fireLeadMinutes: { type: integer, nullable: true, minimum: 0, maximum: 240, description: "Minutes before the time a guest chose that a takeaway or delivery is sent to the kitchen (T-36.21); a location that never set it is 20. Absent or null on a save keeps what is kept; out of range is 400 `fire_lead_out_of_range`. Changing it is audited with the rest of the window." }
    ComingUpOrder:
      type: object
      description: An order a guest placed for later that the kitchen has not been sent yet (T-36.21). Never a guest's phone or details beyond the name it is called by.
      properties:
        orderId: { type: string }
        locationId: { type: string }
        transactionNumber: { type: string, nullable: true }
        pickupName: { type: string, nullable: true }
        fulfilmentType: { type: string, nullable: true }
        scheduledForMillis: { type: integer, format: int64, description: "The time the guest chose." }
        fireAtMillis: { type: integer, format: int64, description: "When it is sent to the kitchen: the chosen time less the location's lead." }
        lines:
          type: array
          items:
            type: object
            properties:
              lineId: { type: string }
              productId: { type: string }
              name: { type: string }
              quantity: { type: integer, default: 1 }
              note: { type: string, nullable: true }
              seat: { type: integer, nullable: true }
              modifiers: { type: array, items: { type: string } }
            required: [lineId, productId, name]
        note: { type: string, nullable: true }
        splitByCourse: { type: boolean, default: true, description: "How the cloud routes a dish with no station: by course, or to the one Kitchen. A kitchen hub firing the order offline routes the same way, so both name the same tickets." }
      required: [orderId, locationId, scheduledForMillis, fireAtMillis]
    OrderSlot:
      type: object
      properties:
        startsAt: { type: integer, format: int64 }
        endsAt: { type: integer, format: int64 }
        capacity: { type: integer, nullable: true }
        booked: { type: integer, default: 0, description: "Orders already in the slot (live count)." }
      required: [startsAt, endsAt]
    OrderSlotsResponse:
      type: object
      properties:
        fulfilment: { type: string, enum: [TAKEAWAY, DELIVERY] }
        slots: { type: array, items: { $ref: "#/components/schemas/OrderSlot" } }
        soonest: { type: integer, format: int64, nullable: true, description: "The slot an as-soon-as-possible order is given; null when none has room, and null while the location's kitchen is closed (T-41.42)." }
        timeZone: { type: string, example: "Africa/Johannesburg" }
      required: [fulfilment, slots, timeZone]
    DeliveryZone:
      type: object
      properties:
        id: { type: string, description: "Ignored on PUT; zones are replaced as a set." }
        name: { type: string }
        postcodePrefixes: { type: array, items: { type: string }, description: "\"80\" covers 8001; the longest matching prefix across all zones wins." }
        feeProductId: { type: string, nullable: true, description: "An active product charged as the fee line; null delivers free." }
        feeCents: { type: integer, format: int64, default: 0, description: "The fee product's price; filled in on GET, ignored on PUT." }
        minimumBasketCents: { type: integer, format: int64, default: 0 }
        freeOverCents: { type: integer, format: int64, nullable: true }
      required: [id, name, postcodePrefixes]
    OrderWindowsSettings:
      type: object
      properties:
        locationId: { type: string }
        window: { $ref: "#/components/schemas/OrderWindow" }
        deliveryEnabled: { type: boolean, default: false }
        zones: { type: array, items: { $ref: "#/components/schemas/DeliveryZone" } }
        saved: { type: boolean, default: false, description: "False until the location has saved its own." }
      required: [locationId]
    DeliveryQuoteResponse:
      type: object
      properties:
        delivers: { type: boolean }
        zoneId: { type: string, nullable: true }
        zoneName: { type: string, nullable: true }
        feeCents: { type: integer, format: int64, default: 0 }
        minimumBasketCents: { type: integer, format: int64, default: 0 }
        shortByCents: { type: integer, format: int64, default: 0 }
        refusal: { type: string, nullable: true, description: "outside_delivery_area or below_delivery_minimum; null when it delivers." }
      required: [delivers]
    QrOrderRequest:
      type: object
      properties:
        locationId: { type: string }
        upsellRuleId: { type: string, nullable: true, description: "The first suggestion this guest was shown (T-6.3): what a client from before T-39.16 sends. Read together with upsellRuleIds." }
        upsellRuleIds: { type: array, items: { type: string }, description: "Every suggestion this guest was shown (T-39.16): up to three at checkout and an \"add a drink?\". Each distinct rule (at most 10) is recorded once for the order; taken or not is judged per rule from the lines. A rule this venue does not have is ignored." }
        clientOrderId: { type: string, nullable: true, description: "Minted on the device (T-6.7); an id already placed here is answered again, never placed twice — to a request carrying its key in X-Ruva-Order-Key; without it, 409 id_conflict." }
        callNumber: { type: string, nullable: true, description: "An offline kiosk order's number (\"F7\"); ignored on this route, honoured on sync." }
        kitchenFired: { type: boolean, default: false, description: "Ignored on this route; on sync, true only when the venue's own screen fired the order's tickets; otherwise the server fires them, unless the order is held for its payment or its time, or has been voided." }
        placedAt: { type: integer, format: int64, nullable: true, description: "Ignored on this route; on sync, when a held order was placed (QueuedTime, within 7 days)." }
        payments: { type: array, items: { $ref: "#/components/schemas/PaymentLeg" }, description: "Ignored on this route; on sync (`kiosk_order`), what the guest paid on the kiosk's own card terminal: `CARD_TERMINAL` or `TAP_TO_PAY` legs with the approval as `providerReference`, each approval once, no `tipCents` and no `tenderedCents` (otherwise 400 `kiosk_payment_not_terminal`). Needs a sign-in that may record a sale (TILL_SELL); settled through checkout with the order, once. Past the grace it keeps the order only within a week of ordering stopping and from a device with no answered push since then, and each one kept is written to the audit log (D-45)." }
        ageConfirmed: { type: boolean, default: false, description: "T-37.1 - the guest's one tick that they are of age. An order with an age-restricted dish and no tick is `409 age_check_required`; the kitchen ticket then reads ID check on collection or at the table. Tobacco is never sold here: `409 tobacco_not_sold_remotely`." }
        tableLabel: { type: string, nullable: true, description: "Table label from the scanned QR code, if any." }
        lines: { type: array, items: { $ref: "#/components/schemas/QrOrderLine" } }
        notes: { type: string, nullable: true }
        tipCents: { type: integer, format: int64, default: 0, description: "Optional guest tip in cents (>= 0); persisted on the order and added to the SnapScan payment amount. Max R10,000." }
        fulfilmentType: { type: string, default: "DINE_IN", enum: [DINE_IN, TAKEAWAY, DELIVERY], description: "DINE_IN needs a table (except from a kiosk, `channel` `KIOSK`, at a location whose kiosk asks eat in or take away and not on a tab: its eat-in is called by number, T-39.11); TAKEAWAY (click-and-collect) makes the table optional; DELIVERY (T-13.3) needs the delivery details." }
        scheduledForMillis: { type: integer, format: int64, nullable: true, description: "Requested pickup or delivery time (epoch millis), placed in the slot starting at or after it (see /qr/slots). Null = the first slot with room." }
        deliveryAddress: { type: string, nullable: true, maxLength: 240, description: "Street address for a DELIVERY order (T-13.3)." }
        deliveryPostcode: { type: string, nullable: true, maxLength: 12, description: "Postcode for a DELIVERY order; chooses the zone, fee and minimum." }
        dropoffNotes: { type: string, nullable: true, maxLength: 200, description: "T-37.14 - a DELIVERY order's directions for the driver, optional plain text. The server cleans it first and counts what it keeps: invisible marks (bidi marks, zero-width characters, tag characters outside an emoji flag, runs of variation selectors, blank fillers) are removed, every line ending becomes one line break, each line is trimmed and blank lines are dropped; so `maxLength` is checked after that, and a padded value may be longer on the wire. At most 5 lines. Sent to the venue's courier only as the booking's drop-off notes, never on a kitchen ticket; kept only where `features.driverDirections` is true, ignored on any other order. `400 dropoff_notes_too_long`, `400 dropoff_notes_too_many_lines`, `400 dropoff_notes_invalid` (a control character other than a line break)." }
        pickupName: { type: string, nullable: true, description: "Collector name for a takeaway order." }
        pickupPhone: { type: string, nullable: true, description: "Collector phone for a takeaway order." }
        tabName: { type: string, nullable: true, description: "Opening a phone tab (T-30.14), with `paymentMode: ADD_TO_TAB`: the name it is opened under. Required to open one." }
        tabPhone: { type: string, nullable: true, description: "The phone number it is opened under; normalised to E.164. Required to open one." }
        tabOrderId: { type: string, nullable: true, description: "A round on a phone tab already open (T-30.14): the tab's order id, opened with the tab's key in `X-Ruva-Order-Key`, or — a friend at the table (T-39.29) — with the tab's share code in `X-Ruva-Bill-Code` and a key of the friend's own." }
        joinerLabel: { type: string, nullable: true, maxLength: 24, description: "A friend adding a round to a shared phone tab (T-43.12): what they call their phone — letters, digits and spaces, never a phone number (`400 tab_label_invalid`). The tab's owner reads the tab's lines under it; none given is `Guest 2`, `Guest 3`… in join order. Ignored on the owner's own rounds and on any other order." }
        tableCode: { type: string, nullable: true, maxLength: 12, description: "The code printed on the table (T-39.9), asked for an unpaid dine-in order where the location switched `tableCodesRequired` on. Case, spaces and dashes are ignored. Never put it in a link." }
        paymentMode: { type: string, default: "PAY_NOW", enum: [PAY_NOW, ADD_TO_TAB, PAY_AT_COUNTER], description: "PAY_NOW settles online immediately; ADD_TO_TAB joins the table's running bill (dine-in, Restaurant-licensed venues only — V72); PAY_AT_COUNTER (T-1.20) is paid at the counter and closed in the back office — only where the menu's features.payAtCounter is true (else 400 counter_not_offered), and never for a DELIVERY (400 counter_not_for_delivery)." }
        channel: { type: string, default: "QR", enum: [QR, KIOSK], description: "The guest surface ordering (T-4.5): a phone or the self-order kiosk. Promotions scoped to a channel read it. TILL is refused with 400 invalid_channel. Naming KIOSK here proves nothing (T-35.14): from 1 February 2027 only an order placed through a paired kiosk's own signed-in door, `POST /api/v1/kiosk/orders`, is free of the per-order fee." }
        guest:
          type: object
          nullable: true
          description: |
            The guest's own details (T-1.16, POPIA), all optional; an order with none is anonymous. A number or an email
            typed here is an unverified claim and never changes a customer the business already holds — unless the guest
            confirmed their email with a one-time code (T-1.24): `emailProof`, from `POST /api/v1/qr/guest/email-code/check`,
            is spent once by the order, and a verified address that is a customer's links the order to them and records the
            guest's own tick for EMAIL. A new guest's opt-in for an address nobody has proved is recorded but held back from
            campaigns until verified. A `400` (`invalid_phone`, `invalid_email`, `guest_name_too_long`,
            `guest_details_unreadable`, `consent_needs_contact`) is refused before the order is placed.
          properties:
            name: { type: string, nullable: true, maxLength: 80 }
            phone: { type: string, nullable: true, description: "A mobile number, read as E.164." }
            email: { type: string, nullable: true, maxLength: 254 }
            marketingConsent: { type: boolean, default: false, description: "The separate, unticked box: Send me news and offers from the venue." }
            feedbackConsent: { type: boolean, default: false, description: "The second, unticked box: Ask me how my visit was. One message about this order, and only this order is asked about; its own consent, not implied by `marketingConsent`. Needs an email or a phone (`feedback_needs_contact`)." }
            emailProof: { type: string, nullable: true, description: "The one-time proof for `email`, from the check route; spent by this order alone." }
      required: [locationId, lines]
    QrOrderResponse:
      type: object
      properties:
        orderId: { type: string, description: "The order to poll. For ADD_TO_TAB this is the TABLE's bill, not a new order." }
        transactionNumber: { type: string }
        subtotalCents: { type: integer, format: int64, description: "This guest's own addition, not the whole bill." }
        vatCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64, default: 0 }
        totalCents: { type: integer, format: int64, description: "subtotal - promotionDiscountCents + tip (the guest's own charge)." }
        promotionDiscountCents: { type: integer, format: int64, default: 0, description: "What the venue's automatic promotions took off this order (T-4.5), evaluated as the till does. Checkout re-evaluates and settles at the same figure. On an ADD_TO_TAB append it is what the offers took off this round's own lines on the guest's channel — the figure the guest's basket showed (core GuestPromotions), never the bill's other lines or a till-only offer; it is kept on the round and added to the bill's offers, so a replay, `GET /qr/rounds/{id}` and checkout count it once. The charge is `totalCents` either way (walkthrough 14, G6-2)." }
        paymentMode: { type: string, default: "PAY_NOW", description: "PAY_NOW | ADD_TO_TAB | PAY_AT_COUNTER, echoed back." }
        settlement: { type: string, default: "ONLINE", description: "ONLINE — pay from the phone now; TABLE_BILL — the till settles it later." }
        checkoutUrl: { type: string, nullable: true, description: "Yoco hosted checkout to redirect the guest to (PAY_NOW with Yoco configured)." }
        billTotalCents: { type: integer, format: int64, nullable: true, description: "The whole table bill after an ADD_TO_TAB append." }
        pollable: { type: boolean, default: true, description: "False when the joined bill is till-authored — its status is not the guest's to poll. Its rounds are: see roundId." }
        roundId: { type: string, nullable: true, description: "The round this placement was (T-13.2); follow it at /api/v1/qr/rounds/{roundId}, on any tab." }
        joinerLabel: { type: string, nullable: true, description: "The label a friend's round on a shared phone tab was put under (T-43.12); send it again with that phone's next round. Null for any other round." }
        scheduledForMillis: { type: integer, format: int64, nullable: true, description: "The slot a collected or delivered order was given (T-13.3) — the time to tell the guest." }
        receiptToken: { type: string, nullable: true, description: "The key this order opens with (T-2.9, T-2.12): send it as the X-Ruva-Order-Key header on GET /api/v1/qr/orders/{orderId}, its /receipt and /payment, and as `key` in the body of its /buzzer and /feedback. The device's own when it sent one on placing; given again only to a replay that presented it. A round added to another bill carries none." }
        roundToken: { type: string, nullable: true, description: "The key this round is followed with (T-2.12): GET /api/v1/qr/rounds/{roundId} with it as X-Ruva-Order-Key. For the round that opened the order it is the order's own receiptToken; a round added to a table's tab, a till's included, has its own, which opens that round and nothing else. In the first answer only." }
        offerBuzzer: { type: boolean, default: false, description: "The guest's phone is offered the buzzer for this order (T-5.4): a takeaway always, a dine-in order where the location says guests collect at the counter, a delivery never. GET /api/v1/qr/rounds/{id} says the same." }
        counterTakesPayment: { type: boolean, default: false, description: "The counter takes this order's payment (T-41.100): a venue with a till, or a counter order the back office closes. False at a venue with no till for an order paid on a phone, whose guest is never sent to the counter to pay." }
        later: { type: boolean, default: false, description: "An order for as soon as possible was given a later slot than the kitchen's notice allows (T-41.44): the sooner ones full, or the pickup hours not open yet or over for today. It waits for scheduledForMillis, and a kiosk tells its guest when it will be ready. A placement answered again says it while the order is still held. False for a time the guest chose and for a dine-in order." }
      required: [orderId, transactionNumber, subtotalCents, vatCents, totalCents]
    QrOrderStatusResponse:
      type: object
      properties:
        id: { type: string }
        status: { type: string }
        kitchenStatus: { type: string, description: "RECEIVED | PREPARING | READY" }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        placedAt: { type: integer, format: int64 }
      required: [id, status, kitchenStatus, totalCents, paidCents, placedAt]
    QrPaymentResponse:
      type: object
      properties:
        mode: { type: string, description: "YOCO (hosted checkout link) | SNAPSCAN | PAY_AT_COUNTER | PAID" }
        url: { type: string, nullable: true, description: "The checkout/payment URL for YOCO and SNAPSCAN modes." }
        qrPngBase64: { type: string, nullable: true, description: "Base64-encoded PNG of `url`, for direct <img>/ImageBitmap use. Present for SNAPSCAN and for YOCO (so a shared kiosk screen can hand the payment to the guest's own phone)." }
        status: { type: string, nullable: true, description: "PENDING | PAID" }
        amountCents: { type: integer, format: int64, nullable: true }
      required: [mode]

    QrRoundLine:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        quantity: { type: integer }
        note: { type: string, nullable: true }
        modifierOptionIds: { type: array, items: { type: string } }
        lineTotalCents: { type: integer, format: int64 }
      required: [productId, name, quantity, lineTotalCents]
    QrRoundStep:
      type: object
      properties:
        stage: { type: string, description: "PLACED | SENT | READY | SERVED" }
        atMillis: { type: integer, format: int64, nullable: true, description: "When the round reached it; null until it has." }
      required: [stage]
    QrArrival:
      type: object
      required: [arrivedAt]
      properties:
        arrivedAt: { type: integer, format: int64, description: "When the FIRST tap was made, in epoch milliseconds (server time)." }
        note: { type: string, nullable: true, description: "The first tap's note, as kept (cleaned, at most 60 characters)." }
        first: { type: boolean, default: true, description: "Whether this call was the first tap; false for a later tap, which changes nothing." }
    PushKindSetting:
      type: object
      required: [kind, label, explains, on]
      properties:
        kind: { type: string, enum: [new_order, table_call, order_ready, payment, booking, takings, stock, approval, stalled_payment] }
        label: { type: string }
        explains: { type: string }
        "on": { type: boolean }
    PushKindChange:
      type: object
      required: [kind, "on"]
      properties:
        kind: { type: string }
        "on": { type: boolean }
    PushPreferences:
      type: object
      properties:
        kinds: { type: array, items: { $ref: "#/components/schemas/PushKindSetting" } }
        devices: { type: integer, description: "How many of the person's phones and browsers are registered." }
        browsers: { type: integer, description: "How many of those are browsers." }
        webPushKey: { type: string, nullable: true, description: "The VAPID public key a browser subscribes under (65-byte P-256 point, base64url); absent when this server sends no browser push." }
    LocationPushKinds:
      type: object
      properties:
        locationId: { type: string }
        kinds: { type: array, items: { $ref: "#/components/schemas/PushKindSetting" } }
    QrRoundResponse:
      type: object
      properties:
        roundId: { type: string }
        orderId: { type: string, description: "The tab the round is on now." }
        placedAt: { type: integer, format: int64 }
        stage: { type: string, description: "The latest of PLACED | SENT | READY | SERVED reached." }
        steps: { type: array, items: { $ref: "#/components/schemas/QrRoundStep" }, description: "All four stages in order." }
        withdrawn: { type: boolean, default: false, description: "Staff took every line of the round off the bill." }
        lines: { type: array, items: { $ref: "#/components/schemas/QrRoundLine" } }
        subtotalCents: { type: integer, format: int64, description: "The round's lines still on the bill." }
        tipCents: { type: integer, format: int64, default: 0 }
        settlement: { type: string, description: "ONLINE | TABLE_BILL" }
        billOpen: { type: boolean, description: "The tab still takes rounds." }
        billPaid: { type: boolean }
        offerBuzzer: { type: boolean, default: false, description: "The guest's phone is offered the buzzer for this round's order (T-5.4), as the location says now: a takeaway always, a dine-in order where guests collect at the counter, a delivery never." }
        cancelMsLeft: { type: integer, format: int64, nullable: true, description: "How long the guest may still cancel this order, in milliseconds as of this answer (T-39.7, `POST /api/v1/qr/orders/{id}/cancel`); absent when they may not." }
        cancelled: { type: boolean, default: false, description: "The order was cancelled or paid back whole — by the guest or the venue; nothing is coming." }
        refunded: { type: boolean, default: false, description: "Of a cancelled order: the card was paid back." }
        courier: { allOf: [{ $ref: "#/components/schemas/QrCourierStatus" }], nullable: true, description: "A delivery in a courier's hands: the stage and the courier's own tracking link (T-37.9). Absent when no courier has the order." }
        offerArrival: { type: boolean, default: false, description: "The round's order is a takeaway to collect, so its phone is offered \"I'm here\" (T-36.23, POST /api/v1/qr/orders/{id}/arrived); false once it is collected or closed." }
        arrivedAt: { type: integer, format: int64, nullable: true, description: "When the guest said they had arrived (the first tap); omitted until they have." }
        arrivalNote: { type: string, nullable: true, description: "The note the guest left with that tap, if any." }
        waitsForPayment: { type: boolean, default: false, description: "The order waits for its payment before the kitchen is sent it (D-195): placed at a venue where the guest pays on their phone, and not paid yet. The kitchen has nothing of it." }
        lapsed: { type: boolean, default: false, description: "The order's payment was never made, so it was closed unpaid and never reached the kitchen (D-195). Nothing was charged; the guest may place it again." }
      required: [roundId, orderId, placedAt, stage, steps, lines, subtotalCents, settlement, billOpen, billPaid]

    QrOrderCancelResponse:
      type: object
      required: [orderId, status]
      properties:
        orderId: { type: string }
        status: { type: string, enum: [CANCELLED] }
        refundedCents: { type: integer, format: int64, default: 0 }
        notice: { type: string, nullable: true, description: "What the guest should still know, such as a refund that has not been confirmed; absent otherwise." }

    GuestBillLine:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        quantity: { type: integer }
        totalCents: { type: integer, format: int64 }
        shareCents: { type: integer, format: int64, description: "The line's part of the bill (a bill discount shared in proportion): what a guest paying for it is charged." }
        taken: { type: boolean, description: "Another guest is paying, or has paid, for it." }
      required: [id, name, quantity, totalCents, shareCents, taken]
    GuestBillResponse:
      type: object
      properties:
        orderId: { type: string }
        status: { type: string, description: "OPEN | FIRED | PAID | VOIDED" }
        lines: { type: array, items: { $ref: "#/components/schemas/GuestBillLine" } }
        dueCents: { type: integer, format: int64, description: "What the bill comes to for its guests: the goods after discounts, the automatic service charge when it applies to the covers (`serviceChargeCents`), plus any tip already on it." }
        paidCents: { type: integer, format: int64 }
        heldCents: { type: integer, format: int64, description: "Shares being paid right now." }
        outstandingCents: { type: integer, format: int64, description: "What a guest may still take." }
        differenceCents: { type: integer, format: int64, description: "+ still due after the guests' payments; − they paid more than the bill (a refund the venue owes)." }
        split: { type: string, nullable: true, description: "REST | EVEN | ITEMS — how the bill is already being split." }
        ways: { type: integer, nullable: true }
        openWays: { type: integer, nullable: true }
        shareCode:
          type: string
          nullable: true
          description: "The bill's share code, `XXXX-XXXX` (T-2.50): only to the phone that opened the bill with the order's key. A phone tab shows one only once its owner shared it (T-39.29, `POST /qr/bills/{orderId}/tab-code`)."
        phoneTab: { type: boolean, default: false, description: "T-39.29 — a guest's phone tab (T-30.14), shared or not: the phone adds rounds to it with the tab's code and a key of its own (a friend) or with the tab's key (the owner), and the owner answers for what is left." }
        serviceChargeCents: { type: integer, format: int64, description: "T-39.17 — the location's automatic service charge inside `dueCents` (0 when none applies to the covers), shown on the guest's bill as its own line. The phones pay it with their shares, and the bill closes with it in its journal." }
        serviceChargeRateBp: { type: integer, default: 0, description: "T-41.29 — the service charge's rate in basis points while it is charged (0 otherwise), so the guest's line reads like the till's: *Service charge (10%)*." }
        rounds:
          type: array
          nullable: true
          description: "A phone tab's lines grouped by the phone that added them (T-43.12), sent only to the phone holding the tab's own key and only once a friend has added a round: the owner's own first (`label` null), then each friend's label in the order they joined. Labels and line ids only — never a phone number."
          items:
            type: object
            properties:
              label: { type: string, nullable: true }
              lineIds: { type: array, items: { type: string } }
      required: [orderId, status, dueCents, paidCents, heldCents, outstandingCents, differenceCents]
    GuestShareRequest:
      type: object
      properties:
        shareId: { type: string, description: "Minted by the phone (8–64 of A-Z a-z 0-9 _ -), so a retry is the same share." }
        mode: { type: string, description: "REST | EVEN | ITEMS" }
        ways: { type: integer, nullable: true, description: "EVEN: 2–20." }
        lineIds: { type: array, items: { type: string }, description: "ITEMS: the lines this guest pays for." }
        tipCents: { type: integer, format: int64, description: "At most the share itself." }
      required: [shareId, mode]
    GuestShareResponse:
      type: object
      properties:
        shareId: { type: string }
        status: { type: string, description: "PENDING | PAID | FAILED" }
        amountCents: { type: integer, format: int64 }
        tipCents: { type: integer, format: int64 }
        payMode: { type: string, description: "YOCO | PAYFAST | SNAPSCAN | PAY_AT_COUNTER" }
        url: { type: string, nullable: true }
        qrPngBase64: { type: string, nullable: true }
        bill: { $ref: "#/components/schemas/GuestBillResponse" }
      required: [shareId, status, amountCents, tipCents, payMode, bill]

    # ── Booking ──
    BookingSlotDto:
      type: object
      properties:
        atMillis: { type: integer, format: int64, description: "Slot start (epoch millis, Africa/Johannesburg wall-clock)." }
        label: { type: string, description: "\"HH:mm\" local display label." }
        available: { type: boolean }
        remainingSeats: { type: integer, nullable: true, description: "Seats left in the window; null when the location has no tables configured." }
        durationMinutes: { type: integer, nullable: true, description: "How long the table is held: the venue's turn time for this party size." }
        unavailable: { type: string, enum: [FULL, CLOSED, PAST], nullable: true, description: "Why a time is not offered, as a guest may read it: FULL whether pacing, the covers cap or the tables made it so. Absent on a time that can be booked." }
        nearestBeforeAt: { type: integer, format: int64, nullable: true, description: "On a full time: the nearest bookable start before it on the same day." }
        nearestAfterAt: { type: integer, format: int64, nullable: true, description: "On a full time: the nearest bookable start after it on the same day." }
      required: [atMillis, label, available]
    AvailabilityDay:
      type: object
      properties:
        date: { type: string, format: date }
        closed: { type: boolean }
        slots: { type: array, items: { $ref: "#/components/schemas/BookingSlotDto" } }
      required: [date, closed, slots]
    AvailabilityRangeResponse:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
        from: { type: string, format: date }
        partySize: { type: integer }
        durationMinutes: { type: integer }
        days: { type: array, items: { $ref: "#/components/schemas/AvailabilityDay" } }
      required: [locationId, locationName, from, partySize, durationMinutes, days]
    BookingBlackout:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        date: { type: string, format: date }
        reason: { type: string, nullable: true }
      required: [id, locationId, date]
    DashboardAlertsResponse:
      type: object
      properties:
        alerts:
          type: array
          items:
            type: object
            properties:
              kind: { type: string, enum: [SYNC_REFUSED, PAYOUT_GAP, DEPOSIT_REFUND_TO_CHECK, DEPOSIT_UNSPENT, DEVICE_SILENT, EIGHTY_SIXED, LOW_STOCK] }
              count: { type: integer }
              examples: { type: array, items: { type: string }, description: "Up to five, by name." }
              sentence: { type: string }
              remedy: { type: string }
            required: [kind, count, examples, sentence, remedy]
        asOf: { type: integer, format: int64 }
      required: [alerts, asOf]
    DepositRefundsToCheck:
      type: object
      properties:
        items:
          type: array
          items:
            type: object
            properties:
              id: { type: string, description: "What dealt-with takes." }
              says: { type: string, description: "The line the alert shows for it." }
              why: { type: string, enum: [UNCONFIRMED, FAILED, NOT_OURS] }
              check: { type: string, description: "For an UNCONFIRMED Yoco refund: the amount, date and checkout id to look up in Yoco's portal; blank otherwise." }
              canConfirm: { type: boolean, description: "True when confirmed-refunded takes it (an UNCONFIRMED Yoco refund)." }
            required: [id, says, why]
        asOf: { type: integer, format: int64 }
      required: [items, asOf]
    DepositRefundConfirmed:
      type: object
      properties:
        id: { type: string, maxLength: 200 }
      required: [id]
    DepositRefundDealtWith:
      type: object
      properties:
        id: { type: string, maxLength: 200 }
        reason: { type: string, maxLength: 300, description: "What was done about it; required." }
      required: [id, reason]
    DeviceSyncHealth:
      type: object
      properties:
        deadLetters: { type: integer, minimum: 0 }
        pending: { type: integer, minimum: 0 }
        screenLock: { type: string, description: "How firmly this screen is held on its surface: locked, pinned or open. Optional; a word the server does not know is ignored." }
        oldestSaleAt: { type: integer, format: int64, nullable: true, description: "When the oldest sale, ticket payment or kiosk order still held was queued (server time); an older till's only word (T-35.5)." }
        clockOffsetMs: { type: integer, format: int64, nullable: true, description: "Server time minus the device's clock as it last measured it; past five minutes either way the device and its paid sales are flagged (T-35.5)." }
        locationId: { type: string, nullable: true, description: "The location the device trades at now (T-35.5)." }
        heldSales:
          type: array
          nullable: true
          description: "The sales the device holds by the location each was rung at, the oldest at each (server time); the day's close of that location waits for them (T-35.5)."
          items:
            type: object
            properties:
              locationId: { type: string }
              oldestAt: { type: integer, format: int64 }
            required: [locationId, oldestAt]
        surface: { type: string, nullable: true, description: "What the device shows now (pos, kds, kiosk, admin, customer-display, ready-tv); absent at the Hub or from an older app. A check-in saying pos is what a till is billed by (T-23.9)." }
      required: [deadLetters, pending]
    BookingAvailabilityResponse:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
        date: { type: string, description: "yyyy-MM-dd echoed back." }
        partySize: { type: integer }
        slots: { type: array, items: { $ref: "#/components/schemas/BookingSlotDto" } }
        brandAccentHex: { type: string, nullable: true, description: "The venue's brand colour (#rrggbb) the widget draws in; absent when none is set." }
        closed: { type: boolean, description: "The date takes no bookings at all (a closed date or a weekday with no hours); slots is then empty." }
        guestTerms: { allOf: [{ $ref: "#/components/schemas/GuestTerms" }], nullable: true, description: "What the guest is told about the venue (who it is, its privacy notice): the booking form shows the privacy line beside the allergies it asks for." }
      required: [locationId, locationName, date, partySize, slots]
    BookingWhyAnswer:
      type: object
      properties:
        date: { type: string }
        time: { type: string }
        partySize: { type: integer }
        available: { type: boolean }
        reason: { type: string, enum: [PACING, COVERS, NO_TABLE, BLACKOUT, OUTSIDE_SERVICE, TOO_LATE], nullable: true }
        words: { type: string }
        setting: { type: string, nullable: true, description: "What would change the reason." }
        nearest: { type: array, items: { $ref: "#/components/schemas/BookingSlotDto" } }
      required: [date, time, partySize, available, words, nearest]
    BookingEnquiryAnswered:
      type: object
      required: [id, status]
      properties:
        id: { type: string }
        status: { type: string, enum: [ACCEPTED, DECLINED] }
        guestToldBy: { type: string, nullable: true, enum: [WHATSAPP, EMAIL], description: "How the guest was sent the answer; null when nothing could be sent." }
        reservationId: { type: string, nullable: true }
        reservationStatus: { type: string, nullable: true, description: "`CONFIRMED`, or `PENDING` while a deposit is owed." }
        noTableFree: { type: boolean }
        deposit:
          type: object
          nullable: true
          properties:
            amountCents: { type: integer, format: int64 }
            payUrl: { type: string, nullable: true }
            holdUntil: { type: integer, format: int64 }
            status: { type: string }
    BookingReservationRequest:
      type: object
      properties:
        locationId: { type: string }
        guestName: { type: string }
        partySize: { type: integer, description: "1..20." }
        reservedForAt: { type: integer, format: int64, description: "Requested time (epoch millis) — use an availability slot's atMillis." }
        durationMinutes: { type: integer, default: 90, deprecated: true, description: "Ignored since T-12.1: the stay is the venue's turn time for the party, returned in the response." }
        phone: { type: string, nullable: true, description: "Required unless email is given." }
        email: { type: string, nullable: true, description: "Required unless phone is given." }
        notes: { type: string, nullable: true }
        allergens: { type: array, items: { type: string }, description: "Allergies the guest names, from the menu's closed list (Gluten, Shellfish, Egg, Fish, Peanuts, Soya, Dairy, Tree nuts, Celery, Mustard, Sesame, Sulphites, Lupin, Molluscs). Health information: held with the booking, shown to the host and on the kitchen ticket of the party's sitting, erased with the guest, never sent to Google or used for marketing. A name off the list is `400 invalid_allergy`." }
        dietaryNote: { type: string, nullable: true, maxLength: 200, description: "Anything else the kitchen should know about the guest's diet; kept and used as `allergens` is." }
        requestId: { type: string, nullable: true, description: "16 to 128 characters the widget mints once per submit and sends again on every retry of it: a request whose id already made a booking at this location is answered with that booking. A second party on the same phone or email is a booking of its own." }
      required: [locationId, guestName, partySize, reservedForAt]
    BookingReservationResponse:
      type: object
      properties:
        id: { type: string }
        status: { type: string, description: "Always PENDING on create; a paid deposit confirms it." }
        reservedForAt: { type: integer, format: int64 }
        durationMinutes: { type: integer }
        partySize: { type: integer }
        guestName: { type: string }
        deposit: { $ref: "#/components/schemas/BookingDepositAsk" }
        manageToken:
          type: string
          description: "The guest's own key to the booking (sent in `X-Ruva-Booking-Key` to `GET /api/v1/booking/manage`). Absent on a replayed double-submit."
        allergens: { type: array, items: { type: string }, description: "The allergies the booking holds, in the menu's words and order." }
      required: [id, status, reservedForAt, durationMinutes, partySize, guestName]
    BookingDepositAsk:
      type: object
      description: "A booking's deposit. Pay at `payUrl` before `holdUntil`, or the booking is released."
      properties:
        amountCents: { type: integer, format: int64 }
        payUrl: { type: string, description: "Absent once paid, or while the card rail is down (the manage page offers it again)." }
        holdUntil: { type: integer, format: int64 }
        status: { type: string, enum: [PENDING, CAPTURED, APPLIED, SETTLED, EXPIRED, FAILED] }
      required: [amountCents, holdUntil, status]
    BookingManageView:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        locationName: { type: string }
        guestName: { type: string }
        partySize: { type: integer }
        reservedForAt: { type: integer, format: int64 }
        status: { type: string }
        deposit: { $ref: "#/components/schemas/BookingDepositAsk" }
        freeUntil: { type: integer, format: int64, description: "Until when cancelling or moving is free; absent when the venue keeps nothing." }
        cancelRefundCents: { type: integer, format: int64 }
        cancelKeptCents: { type: integer, format: int64 }
        changeRefusal: { type: string }
        moveRefusal: { type: string }
      required: [id, locationId, locationName, guestName, partySize, reservedForAt, status]
    BookingMoveRequest:
      type: object
      properties:
        reservedForAt: { type: integer, format: int64 }
      required: [reservedForAt]
    BookingCancelResult:
      type: object
      properties:
        status: { type: string }
        refundCents: { type: integer, format: int64 }
        keptCents: { type: integer, format: int64 }
        refundByHand: { type: boolean, description: "The venue returns it from its payment dashboard (a PayFast refund PayFast can pay only into a bank account, or a venue with no account connected)." }
      required: [status, refundCents, keptCents]
    BookingPolicy:
      type: object
      properties:
        depositPerCoverCents: { type: integer, format: int64 }
        depositFromParty: { type: integer }
        holdMinutes: { type: integer }
        freeCancelHours: { type: integer }
        lateFeePerCoverCents: { type: integer, format: int64, description: "Never more than the deposit per guest." }
        noShowGraceMinutes: { type: integer }
    BookingPolicyView:
      type: object
      properties:
        locationId: { type: string }
        policy: { $ref: "#/components/schemas/BookingPolicy" }
        depositRail: { type: string, enum: [YOCO, PAYFAST] }
      required: [locationId, policy]
    BookingWidgetDto:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
        enabled: { type: boolean, description: "Whether this branch is taking bookings from the public widget." }
        bookingUrl:
          type: string
          description: "The value to paste into Google's “Make a reservation” link."
          example: "https://ruva.example/book?loc=loc-main"
        embedSnippet:
          type: string
          description: "The <iframe> a venue pastes into its own website."
        scriptSnippet:
          type: string
          description: "The one-line <script> embed: places the same frame and sizes it to the form."
          example: "<script src=\"https://ruva.example/site/assets/ruva-book.js\" data-loc=\"loc-main\" async></script>"
        slug:
          type: string
          description: "The page's address, `bookingUrl`'s last part. Absent when the business is at its address ceiling and this location has none."
        addressNote:
          type: string
          description: "Why there is no `slug`: the business holds 25 booking page addresses across its locations. Absent when the page has an address."
      required: [locationId, locationName, enabled, bookingUrl, embedSnippet]
    BookingWidgetUpdateRequest:
      type: object
      properties:
        locationId: { type: string }
        enabled: { type: boolean }
      required: [locationId, enabled]

    # ── Checklists ──
    IdResponse:
      type: object
      properties:
        id: { type: string }
      required: [id]
    ChecklistItemDto:
      type: object
      properties:
        id: { type: string }
        label: { type: string }
        sortOrder: { type: integer }
      required: [id, label, sortOrder]
    ChecklistDto:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string, nullable: true, description: "Null = applies to every location." }
        title: { type: string }
        recurrence: { type: string, description: "DAILY | WEEKLY | NONE" }
        active: { type: boolean }
        items: { type: array, items: { $ref: "#/components/schemas/ChecklistItemDto" } }
      required: [id, title, recurrence, active, items]
    ChecklistItemUpsert:
      type: object
      properties:
        id: { type: string, nullable: true, description: "Present = update that item; absent = insert a new item." }
        label: { type: string }
        sortOrder: { type: integer, default: 0 }
      required: [label]
    ChecklistUpsertRequest:
      type: object
      properties:
        locationId: { type: string, nullable: true }
        title: { type: string }
        recurrence: { type: string, default: "DAILY", enum: [DAILY, WEEKLY, NONE] }
        active: { type: boolean, default: true }
        items: { type: array, items: { $ref: "#/components/schemas/ChecklistItemUpsert" } }
      required: [title]
    ChecklistRunItemDto:
      type: object
      properties:
        itemId: { type: string }
        label: { type: string }
        sortOrder: { type: integer }
        done: { type: boolean }
        doneByStaffId: { type: string, nullable: true }
        doneAt: { type: integer, format: int64, nullable: true }
        note: { type: string, nullable: true }
      required: [itemId, label, sortOrder, done]
    ChecklistRunDto:
      type: object
      properties:
        id: { type: string }
        checklistId: { type: string }
        title: { type: string }
        businessDate: { type: string, description: "yyyy-MM-dd (Africa/Johannesburg)." }
        status: { type: string, description: "OPEN | COMPLETE" }
        doneCount: { type: integer }
        totalCount: { type: integer }
        items: { type: array, items: { $ref: "#/components/schemas/ChecklistRunItemDto" } }
      required: [id, checklistId, title, businessDate, status, doneCount, totalCount, items]
    ChecklistItemMarkRequest:
      type: object
      properties:
        done: { type: boolean }
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true, description: "Optional staff id (validated) for shared terminals; defaults to the caller." }
        doneAt: { type: integer, format: int64, nullable: true, description: "When the item was ticked, epoch ms in server time; a tick made offline keeps its own time. Absent means now; refused outside the last 7 days." }
      required: [done]
    ChecklistItemMarkResponse:
      type: object
      properties:
        runId: { type: string }
        itemId: { type: string }
        done: { type: boolean }
        runStatus: { type: string, description: "OPEN | COMPLETE" }
        doneCount: { type: integer }
        totalCount: { type: integer }
      required: [runId, itemId, done, runStatus, doneCount, totalCount]
    ChecklistSummarySendResponse:
      type: object
      properties:
        businessDate: { type: string, description: "yyyy-MM-dd (Africa/Johannesburg)." }
        locationId: { type: string, nullable: true }
        recipients: { type: array, items: { type: string }, description: "The location's own list, or the business's active managers when it names none." }
        checklistsCompleted: { type: integer }
        checklistsOpen: { type: integer }
        totalItems: { type: integer }
        doneItems: { type: integer }
        subject: { type: string }
        status: { type: string, description: "sent | already_done_today | email_not_configured | no_recipient | send_failed" }
        sent: { type: boolean }
        alreadyDone: { type: boolean, description: "True when the morning (or an earlier press) had already sent the day's digest." }
        textBody: { type: string, description: "Rendered plain-text summary (echoed for dev verification)." }
        htmlBody: { type: string, nullable: true, description: "Rendered HTML summary." }
      required: [businessDate, recipients, checklistsCompleted, checklistsOpen, totalItems, doneItems, subject, status, sent, textBody]

    # ── Stocktake sessions (V20) ──
    OpenCountRequest:
      type: object
      properties:
        locationId: { type: string }
        scopeType: { type: string, enum: [ALL, CATEGORY, SUPPLIER, PRODUCTS], default: ALL }
        scopeIds: { type: array, nullable: true, items: { type: string }, description: "Required unless scopeType is ALL." }
        blind: { type: boolean, default: false, description: "Hide expected quantities from the counter until review." }
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
      required: [locationId]
    OpenCountResponse:
      type: object
      properties:
        id: { type: string }
        reference: { type: string, description: "e.g. `SC-20260804-000001`." }
        lineCount: { type: integer }
        blind: { type: boolean }
      required: [id, reference, lineCount, blind]
    SubmitCountRequest:
      type: object
      properties:
        counts: { type: array, items: { $ref: "#/components/schemas/SubmitCountLine" } }
        byStaffId: { type: string, nullable: true }
        countedAt: { type: integer, format: int64, nullable: true, description: "When these were counted, in server time (T-8.1). Absent means now; outside the last 7 days refused `invalid_occurred_at`." }
      required: [counts]
    SubmitCountLine:
      type: object
      properties:
        productId: { type: string }
        countedUnits: { type: integer, format: int64, description: "0 is a real count and posts a variance." }
        variantId: { type: string, nullable: true }
        note: { type: string, nullable: true }
        countedAt: { type: integer, format: int64, nullable: true, description: "When this line was counted; falls back to the request's countedAt, then now." }
      required: [productId, countedUnits]
    StockCountSessionLine:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        variantId: { type: string, nullable: true }
        sku: { type: string, nullable: true }
        stockUnit: { type: string, nullable: true, description: "The product's stock unit (each, g, ml). The back office offers By the bottle on an ml line; the count itself stays in this unit." }
        expectedUnits: { type: integer, format: int64, nullable: true, description: "Absent on a blind session that is still COUNTING." }
        countedUnits: { type: integer, format: int64, nullable: true, description: "Absent means not yet counted — distinct from a counted 0." }
        varianceUnits: { type: integer, format: int64, nullable: true, description: "Absent while expectedUnits is withheld." }
        varianceValueCents: { type: integer, format: int64, nullable: true, description: "varianceUnits at the unit's cost, signed (negative is stock written off). Absent while expectedUnits is withheld, and for a role without VIEW_COST." }
        countedByStaffId: { type: string, nullable: true }
        countedAt: { type: integer, format: int64, nullable: true }
        note: { type: string, nullable: true }
      required: [productId, name]
    StockCountSession:
      type: object
      properties:
        id: { type: string }
        reference: { type: string }
        locationId: { type: string }
        status: { type: string, enum: [DRAFT, COUNTING, REVIEW, APPROVED, CANCELLED] }
        scopeType: { type: string }
        blind: { type: boolean }
        note: { type: string, nullable: true }
        createdByStaffId: { type: string, nullable: true }
        approvedByStaffId: { type: string, nullable: true }
        approvedAt: { type: integer, format: int64, nullable: true }
        createdAt: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/StockCountSessionLine" } }
        countedLines: { type: integer }
        totalLines: { type: integer }
        varianceValueCents: { type: integer, format: int64, nullable: true, description: "The sheet's variance at cost, signed: what approval would post. Absent while a blind count hides it, and for a role without VIEW_COST." }
      required: [id, reference, locationId, status, scopeType, blind, createdAt, lines, countedLines, totalLines]
    StockCountSummary:
      type: object
      properties:
        id: { type: string }
        reference: { type: string }
        locationId: { type: string }
        status: { type: string }
        scopeType: { type: string }
        blind: { type: boolean }
        totalLines: { type: integer }
        countedLines: { type: integer }
        totalVarianceUnits: { type: integer, format: int64, nullable: true, description: "Withheld while a blind count is open." }
        createdAt: { type: integer, format: int64 }
        approvedAt: { type: integer, format: int64, nullable: true }
      required: [id, reference, locationId, status, scopeType, blind, totalLines, countedLines, createdAt]
    ApproveCountResponse:
      type: object
      properties:
        applied: { type: integer, description: "Lines that produced a movement." }
        totalVarianceUnits: { type: integer, format: int64, description: "Sum of ABSOLUTE variances." }
        varianceValueCents: { type: integer, format: int64, description: "Signed: negative wrote stock off, positive found it. Absent for a role without VIEW_COST." }
        tradedUnitsSinceSnapshot: { type: integer, format: int64, description: "Net units that moved between the snapshot and the count, left out of the variance." }
        eightySixed: { type: array, items: { type: string } }
      required: [applied, totalVarianceUnits, varianceValueCents]

    # ── Counting discipline & bin locations (V52) ──
    CountingPolicy:
      type: object
      description: >
        Every `*ShareBp` field is basis points: 8000 is 80%. Integers throughout, so a threshold
        cannot drift by a rounding error between the screen that showed it and the gate that
        enforced it.
      properties:
        id: { type: string, nullable: true, description: "Absent when source is DEFAULT — no row exists to have an id." }
        locationId: { type: string, nullable: true, description: "Echoes the locationId that was asked about, not the one the answering row belongs to." }
        source: { type: string, enum: [LOCATION, TENANT, DEFAULT], description: "Which row answered. One row or the other, never a merge — a partially inherited policy cannot be read off a screen." }
        abcBasis: { type: string, enum: [MOVEMENT, STOCK_VALUE], default: MOVEMENT }
        abcWindowDays: { type: integer, default: 90, description: "Ninety days: three month-ends, but short enough to notice a range change." }
        classAShareBp: { type: integer, default: 8000, description: "Basis points. The conventional 80% of value." }
        classBShareBp: { type: integer, default: 9500, description: "Basis points, and must exceed classAShareBp or class B is empty." }
        classAIntervalDays: { type: integer, default: 28, description: "Monthly." }
        classBIntervalDays: { type: integer, default: 91, description: "Quarterly." }
        classCIntervalDays: { type: integer, default: 365, description: "Annual." }
        recountUnits: { type: integer, format: int64, default: 10, description: "Catches the cheap bulk line. 0 means recount every variance." }
        recountValueCents: { type: integer, format: int64, default: 25000, description: "R250 — about one bottle of gin. Catches the expensive line." }
        recountShareBp: { type: integer, default: 2000, description: "Basis points of expected. Catches the small line, where 3 of 12 is serious and 3 of 900 is not." }
        approvalValueCents: { type: integer, format: int64, default: 50000, description: "A write-off at or over this needs the manager to name the figure to the cent." }
        freezeMode: { type: string, enum: [SNAPSHOT_RECONCILED], description: "The only mode implemented. Sales continue during a count; freezing the counted scope would mean a till refusing a customer's money, which is a change to the POS rather than a setting." }
      required: [source, abcBasis, abcWindowDays, classAShareBp, classBShareBp, classAIntervalDays, classBIntervalDays, classCIntervalDays, recountUnits, recountValueCents, recountShareBp, approvalValueCents, freezeMode]
    CountingPolicyUpsert:
      type: object
      description: A patch. Every field is optional and an absent one keeps its stored value rather than clearing it.
      properties:
        locationId: { type: string, nullable: true, description: "Absent or blank sets the tenant default; naming one sets that location's override." }
        abcBasis: { type: string, nullable: true, enum: [MOVEMENT, STOCK_VALUE] }
        abcWindowDays: { type: integer, nullable: true, description: "At least 1." }
        classAShareBp: { type: integer, nullable: true, description: "Basis points, strictly between 0 and 10000." }
        classBShareBp: { type: integer, nullable: true, description: "Basis points, strictly between 0 and 10000, and strictly above classAShareBp." }
        classAIntervalDays: { type: integer, nullable: true }
        classBIntervalDays: { type: integer, nullable: true }
        classCIntervalDays: { type: integer, nullable: true }
        recountUnits: { type: integer, format: int64, nullable: true, description: "0 is legal and means recount every variance; negative is not." }
        recountValueCents: { type: integer, format: int64, nullable: true }
        recountShareBp: { type: integer, nullable: true }
        approvalValueCents: { type: integer, format: int64, nullable: true }
        freezeMode: { type: string, nullable: true, enum: [SNAPSHOT_RECONCILED], description: "Anything else is refused rather than silently given this one." }
        byStaffId: { type: string, nullable: true, description: "Defaults to the calling user." }
    AbcClassSummary:
      type: object
      properties:
        abcClass: { type: string, enum: [A, B, C] }
        skuCount: { type: integer }
        valueCents: { type: integer, format: int64 }
        intervalDays: { type: integer }
      required: [abcClass, skuCount, valueCents, intervalDays]
    AbcLine:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        abcClass: { type: string, enum: [A, B, C] }
        valueCents: { type: integer, format: int64, description: "The figure classified on, per the basis in force. Clamped at zero — a negative value is a data fault, not a smaller priority." }
        shareBp: { type: integer, description: "This line's share of the total, in basis points, truncated. Display only." }
        cumulativeShareBp: { type: integer, description: "Share carried by this line and everything above it, truncated. Display only." }
        rank: { type: integer, description: "1-based position in the value ranking." }
        intervalDays: { type: integer }
      required: [productId, productName, abcClass, valueCents, shareBp, cumulativeShareBp, rank, intervalDays]
    AbcResponse:
      type: object
      properties:
        locationId: { type: string }
        basis: { type: string, enum: [MOVEMENT, STOCK_VALUE], description: "The basis actually used, after any query override." }
        windowDays: { type: integer }
        windowFromMs: { type: integer, format: int64 }
        windowToMs: { type: integer, format: int64 }
        classAShareBp: { type: integer }
        classBShareBp: { type: integer }
        totalValueCents: { type: integer, format: int64, description: "The whole location, never just the filtered class." }
        classSummary: { type: array, items: { $ref: "#/components/schemas/AbcClassSummary" }, description: "Always all three classes, in A/B/C order, even when one is empty." }
        totalSkus: { type: integer, description: "Rows after any abcClass filter, before the page limit." }
        lines: { type: array, items: { $ref: "#/components/schemas/AbcLine" } }
      required: [locationId, basis, windowDays, windowFromMs, windowToMs, classAShareBp, classBShareBp, totalValueCents, classSummary, totalSkus, lines]
    CycleDueLine:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        abcClass: { type: string, enum: [A, B, C] }
        valueCents: { type: integer, format: int64 }
        intervalDays: { type: integer }
        lastCountedAtMs: { type: integer, format: int64, nullable: true, description: "Absent when never counted." }
        dueAtMs: { type: integer, format: int64, nullable: true, description: "Absent when never counted — deliberately not the epoch, which would sort as absurdly overdue." }
        overdueDays: { type: integer, nullable: true, description: "Whole days past due, truncated. Absent when never counted; zero when not yet due." }
        neverCounted: { type: boolean, description: "Due immediately and sorted first: the only line about which the books hold no evidence at all." }
        due: { type: boolean }
      required: [productId, productName, abcClass, valueCents, intervalDays, neverCounted, due]
    CycleDueResponse:
      type: object
      properties:
        locationId: { type: string }
        nowMs: { type: integer, format: int64 }
        dueCount: { type: integer, description: "Across the whole schedule, ignoring the filters." }
        neverCountedCount: { type: integer, description: "Across the whole schedule, ignoring the filters." }
        totalSkus: { type: integer, description: "Rows after the filters, before the page limit." }
        lines: { type: array, items: { $ref: "#/components/schemas/CycleDueLine" } }
      required: [locationId, nowMs, dueCount, neverCountedCount, totalSkus, lines]
    WalkStop:
      type: object
      description: One place a person stands. Shared by the count route, the pick path and both halves of a putaway line.
      properties:
        sequence: { type: integer, description: "1-based position on the walk. Always 0 inside a PutawayLine, where the ordering lives on the line rather than on its destinations." }
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        binId: { type: string, nullable: true }
        binCode: { type: string, nullable: true, description: "The label on the shelf." }
        zone: { type: string, nullable: true }
        aisle: { type: string, nullable: true }
        shelf: { type: string, nullable: true }
        bin: { type: string, nullable: true }
        walkOrder: { type: integer, nullable: true }
        role: { type: string, nullable: true, enum: [PICK_FACE, BULK] }
        capacityUnits: { type: integer, format: int64, nullable: true, description: "Recorded, and never used to decide anything — Ruva holds no quantity per bin." }
        binActive: { type: boolean, default: true }
        unassigned: { type: boolean, default: false, description: "Nothing records where this SKU is. Returned anyway and sorted last — never dropped, or a picker leaves with a short order and no explanation." }
      required: [sequence, productId, productName]
    CountScopeResponse:
      type: object
      properties:
        locationId: { type: string }
        zone: { type: string, nullable: true }
        aisle: { type: string, nullable: true }
        binId: { type: string, nullable: true }
        abcClass: { type: string, nullable: true }
        dueOnly: { type: boolean }
        scopeIds: { type: array, items: { type: string }, description: "Distinct product ids, because that is what V20's PRODUCTS scope takes. Hand straight to POST /inventory/counts with scopeType = \"PRODUCTS\"." }
        totalStops: { type: integer }
        stops: { type: array, items: { $ref: "#/components/schemas/WalkStop" } }
      required: [locationId, dueOnly, scopeIds, totalStops, stops]
    CountRouteResponse:
      type: object
      description: Carries no expected, counted or variance figure of any kind, so it is safe to hand to a counter during a blind count.
      properties:
        sessionId: { type: string }
        reference: { type: string }
        locationId: { type: string }
        status: { type: string, enum: [DRAFT, COUNTING, REVIEW, APPROVED, CANCELLED] }
        blind: { type: boolean }
        mode: { type: string, enum: [COUNT, PICK] }
        filter: { type: string, enum: [ALL, UNCOUNTED, RECOUNT] }
        unassignedCount: { type: integer, description: "Stops no bin records. Worth showing: it is the size of the gap in the layout." }
        stops: { type: array, items: { $ref: "#/components/schemas/WalkStop" } }
      required: [sessionId, reference, locationId, status, blind, mode, filter, unassignedCount, stops]
    CountVarianceLine:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        expectedUnits: { type: integer, format: int64, description: "The snapshot taken when the session opened." }
        countedUnits: { type: integer, format: int64, nullable: true, description: "Absent means nobody reached this line, which posts nothing — distinct from a counted 0." }
        tradedUnitsSinceSnapshot: { type: integer, format: int64, description: "Net movement between the snapshot and the moment this line was counted. Negative for sales." }
        rawVarianceUnits: { type: integer, format: int64, nullable: true, description: "counted - expected: what POST /inventory/counts/{id}/approve would post." }
        varianceUnits: { type: integer, format: int64, nullable: true, description: "counted - expected - traded: what this family's approval posts instead." }
        unitCostCents: { type: integer, format: int64, description: "Stock value over on-hand, falling back to the product's cost when the level row cannot supply one." }
        varianceValueCents: { type: integer, format: int64, description: "Signed: negative wrote stock off, positive found it." }
        requiresRecount: { type: boolean, description: "Over one of the three recount thresholds — units, value, or share of expected." }
        recountSatisfied: { type: boolean, description: "A different person has since recounted this line." }
        recountCount: { type: integer }
        firstCountedByStaffId: { type: string, nullable: true, description: "Frozen at the first recount, so it still names the original counter after the line has been overwritten." }
        recountedByStaffId: { type: string, nullable: true }
        posts: { type: boolean, description: "This line will produce a stock movement on approval." }
      required: [productId, productName, expectedUnits, tradedUnitsSinceSnapshot, unitCostCents, varianceValueCents, requiresRecount, recountSatisfied, recountCount, posts]
    CountVarianceResponse:
      type: object
      properties:
        sessionId: { type: string }
        reference: { type: string }
        locationId: { type: string }
        status: { type: string, enum: [DRAFT, COUNTING, REVIEW, APPROVED, CANCELLED] }
        blind: { type: boolean }
        snapshotAtMs: { type: integer, format: int64, description: "When the session was opened, which is the baseline the trading term is measured from." }
        freezeMode: { type: string, enum: [SNAPSHOT_RECONCILED] }
        recountUnits: { type: integer, format: int64, description: "The policy in force, echoed so a screen can explain why a line was flagged." }
        recountValueCents: { type: integer, format: int64 }
        recountShareBp: { type: integer, description: "Basis points." }
        approvalValueCents: { type: integer, format: int64 }
        totalLines: { type: integer }
        countedLines: { type: integer }
        linesPosting: { type: integer }
        totalVarianceUnits: { type: integer, format: int64, description: "Sum of absolute reconciled variances." }
        rawVarianceUnits: { type: integer, format: int64, description: "The unreconciled total, carried for comparison with V20's endpoint." }
        tradedUnitsSinceSnapshot: { type: integer, format: int64 }
        writeOffValueCents: { type: integer, format: int64, description: "Negative." }
        foundValueCents: { type: integer, format: int64, description: "Positive." }
        netValueCents: { type: integer, format: int64 }
        requiresExplicitConfirmation: { type: boolean, description: "The write-off is at or over approvalValueCents, so approval must name the figure." }
        blockedReason: { type: string, nullable: true, enum: [recount_required, write_off_confirmation_required, write_off_value_changed], description: "Absent means the count's own figures let it post. Approval judges one thing more, of whoever approves: `second_approver_required` when a write-off at or over approvalValueCents is approved by somebody who counted or recounted it." }
        awaitingRecount: { type: integer, description: "Flagged lines with no independent recount. Any at all refuses the whole session — a partially approved count looks finished while missing its most significant lines." }
        lines: { type: array, items: { $ref: "#/components/schemas/CountVarianceLine" } }
      required: [sessionId, reference, locationId, status, blind, snapshotAtMs, freezeMode, recountUnits, recountValueCents, recountShareBp, approvalValueCents, totalLines, countedLines, linesPosting, totalVarianceUnits, rawVarianceUnits, tradedUnitsSinceSnapshot, writeOffValueCents, foundValueCents, netValueCents, requiresExplicitConfirmation, awaitingRecount, lines]
    RecountRequest:
      type: object
      properties:
        productId: { type: string }
        countedUnits: { type: integer, format: int64, description: "Replaces the line's counted quantity outright. 0 is a real count." }
        variantId: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true, description: "Ignored (T-35.10 fix 2): the recounter is the calling user, who must not be whoever counted first, or the request is refused with `same_counter`." }
        note: { type: string, nullable: true }
      required: [productId, countedUnits]
    RecountResponse:
      type: object
      description: Echoes only what the recounter typed — no expected figure and no variance, one call after being sent to count a shelf blind.
      properties:
        id: { type: string }
        sessionId: { type: string }
        productId: { type: string }
        variantId: { type: string, nullable: true }
        countedUnits: { type: integer, format: int64 }
        recountedByStaffId: { type: string }
        recountedAtMs: { type: integer, format: int64 }
        recountNumber: { type: integer, description: "1 for the first recount, 2 for the supervisor settling a disagreement, and so on." }
      required: [id, sessionId, productId, countedUnits, recountedByStaffId, recountedAtMs, recountNumber]
    ApproveVarianceRequest:
      type: object
      properties:
        confirmWriteOffValueCents:
          type: integer
          format: int64
          nullable: true
          description: >
            Required, and must equal the write-off on the screen, when that write-off is at or over
            the policy threshold. Positive or negative — both mean "I am approving this much
            destroyed". A figure that no longer matches is refused with `write_off_value_changed`
            rather than posting the new one.
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true, description: "Ignored (T-35.10 fix 2): the approver is the calling user." }
    ApproveVarianceResponse:
      type: object
      properties:
        sessionId: { type: string }
        locationId: { type: string }
        applied: { type: integer, description: "Lines that produced a movement. A zero variance posts nothing." }
        totalVarianceUnits: { type: integer, format: int64 }
        rawVarianceUnits: { type: integer, format: int64, description: "What V20's endpoint would have posted, so the difference the reconciliation made is visible rather than asserted." }
        tradedUnitsSinceSnapshot: { type: integer, format: int64 }
        writeOffValueCents: { type: integer, format: int64, description: "Negative. What was actually posted, not what was forecast." }
        foundValueCents: { type: integer, format: int64 }
        netValueCents: { type: integer, format: int64 }
        confirmedWriteOffValueCents: { type: integer, format: int64, nullable: true }
        explicitConfirmation: { type: boolean }
        recountedLines: { type: integer }
        freezeMode: { type: string, enum: [SNAPSHOT_RECONCILED] }
        approvedByStaffId: { type: string }
        approvedAtMs: { type: integer, format: int64 }
        eightySixed: { type: array, items: { type: string }, description: "Products the auto-86 sweep took off sale, because the count found less than the books and emptied an ingredient." }
      required: [sessionId, locationId, applied, totalVarianceUnits, rawVarianceUnits, tradedUnitsSinceSnapshot, writeOffValueCents, foundValueCents, netValueCents, explicitConfirmation, recountedLines, freezeMode, approvedByStaffId, approvedAtMs]
    BinLocation:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        code: { type: string, description: "The label on the shelf, and the identity a bin upsert is keyed on." }
        zone: { type: string, nullable: true }
        aisle: { type: string, nullable: true }
        shelf: { type: string, nullable: true }
        bin: { type: string, nullable: true }
        walkOrder: { type: integer, description: "Ascending, in the order a person physically walks the room. Ties break on code." }
        active: { type: boolean }
        createdAt: { type: integer, format: int64 }
        updatedAt: { type: integer, format: int64 }
      required: [id, locationId, code, walkOrder, active, createdAt, updatedAt]
    BinUpsert:
      type: object
      description: Keyed on (locationId, code). Absent fields are kept, so renumbering a walk does not blank out an aisle.
      properties:
        locationId: { type: string }
        code: { type: string }
        zone: { type: string, nullable: true }
        aisle: { type: string, nullable: true }
        shelf: { type: string, nullable: true }
        bin: { type: string, nullable: true }
        walkOrder: { type: integer, nullable: true, description: "Non-negative. Defaults to 0 on create." }
        active: { type: boolean, nullable: true, description: "Defaults to true on create. False is how a bin is taken out of service — it keeps its assignments, so the stock still gets counted." }
      required: [locationId, code]
    BinAssignment:
      type: object
      properties:
        id: { type: string }
        locationId: { type: string }
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        binId: { type: string }
        binCode: { type: string, nullable: true }
        zone: { type: string, nullable: true }
        aisle: { type: string, nullable: true }
        shelf: { type: string, nullable: true }
        bin: { type: string, nullable: true }
        walkOrder: { type: integer, nullable: true }
        binActive: { type: boolean, default: true }
        role: { type: string, enum: [PICK_FACE, BULK] }
        capacityUnits: { type: integer, format: int64, nullable: true }
        updatedAt: { type: integer, format: int64 }
      required: [id, locationId, productId, productName, binId, role, updatedAt]
    BinAssignmentUpsert:
      type: object
      properties:
        productId: { type: string }
        binId: { type: string }
        variantId: { type: string, nullable: true }
        role: { type: string, nullable: true, enum: [PICK_FACE, BULK], default: PICK_FACE, description: "PICK_FACE moves the SKU's existing face; BULK adds an overflow bin." }
        capacityUnits: { type: integer, format: int64, nullable: true, description: "Must be positive if given. Recorded, never used to decide anything." }
        locationId: { type: string, nullable: true, description: "Optional cross-check. The location comes from the bin; naming a different one is refused rather than silently ignored." }
      required: [productId, binId]
    PickPathResponse:
      type: object
      properties:
        locationId: { type: string }
        mode: { type: string, enum: [PICK, COUNT] }
        unassignedCount: { type: integer }
        stops: { type: array, items: { $ref: "#/components/schemas/WalkStop" } }
      required: [locationId, mode, unassignedCount, stops]
    PutawayLine:
      type: object
      properties:
        sequence: { type: integer, description: "1-based, in the order the delivery should be walked." }
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        variantName: { type: string, nullable: true }
        primary: { allOf: [{ $ref: "#/components/schemas/WalkStop" }], description: "Fill this first: the pick face, or the nearest bulk bin when there is no face." }
        alternates: { type: array, items: { $ref: "#/components/schemas/WalkStop" }, description: "Overflow, nearest first. Empty when there is nowhere else to put it." }
      required: [sequence, productId, productName, primary]
    PutawayResponse:
      type: object
      properties:
        locationId: { type: string, description: "Read from the PO when poId was given." }
        poId: { type: string, nullable: true }
        unassignedCount: { type: integer, description: "Lines whose primary destination is unknown, i.e. the SKU has no bin at all." }
        lines: { type: array, items: { $ref: "#/components/schemas/PutawayLine" } }
      required: [locationId, unassignedCount, lines]

    # ── Valuation (V21) ──
    CategoryValuation:
      type: object
      properties:
        categoryId: { type: string, nullable: true }
        categoryName: { type: string }
        units: { type: integer, format: int64 }
        valueCents: { type: integer, format: int64 }
        skuCount: { type: integer }
      required: [categoryName, units, valueCents, skuCount]
    ValuationReport:
      type: object
      properties:
        locationId: { type: string }
        asOf: { type: integer, format: int64 }
        totalValueCents: { type: integer, format: int64, description: "Tracked cost of the stock actually held." }
        totalUnits: { type: integer, format: int64 }
        skuCount: { type: integer }
        listValueCents: { type: integer, format: int64, description: "Same stock at today's list cost — a wide gap means stale list costs." }
        byCategory: { type: array, items: { $ref: "#/components/schemas/CategoryValuation" } }
      required: [locationId, asOf, totalValueCents, totalUnits, skuCount, listValueCents, byCategory]
    ValuationPoint:
      type: object
      properties:
        date: { type: string, description: "Trading day in SAST, `yyyy-MM-dd`." }
        valueCents: { type: integer, format: int64 }
        units: { type: integer, format: int64 }
      required: [date, valueCents, units]
    ValuationHistory:
      type: object
      properties:
        locationId: { type: string }
        days: { type: integer }
        coveredFrom: { type: integer, format: int64, nullable: true, description: "Earliest movement in the window; before it the series is flat." }
        points: { type: array, items: { $ref: "#/components/schemas/ValuationPoint" } }
      required: [locationId, days, points]
    CogsReport:
      type: object
      properties:
        locationId: { type: string }
        days: { type: integer }
        cogsCents: { type: integer, format: int64, description: "SALE movements only." }
        unitsSold: { type: integer, format: int64 }
        wastageCents: { type: integer, format: int64, description: "Waste, spoilage and expiry — money gone." }
        returnedToSupplierCents: { type: integer, format: int64, description: "RTV — money owed, not lost." }
        averageUnitCostCents: { type: integer, format: int64, nullable: true, description: "Null when nothing sold in the window." }
      required: [locationId, days, cogsCents, unitsSold, wastageCents, returnedToSupplierCents]

    # ── Batches / lots (V23) ──
    BatchEntry:
      type: object
      properties:
        id: { type: string }
        batchCode: { type: string }
        productId: { type: string }
        name: { type: string }
        variantId: { type: string, nullable: true }
        locationId: { type: string }
        expiresAt: { type: integer, format: int64, nullable: true, description: "Null = no expiry; sorts last in FEFO." }
        daysToExpiry: { type: integer, nullable: true, description: "Negative for a lot already past its date." }
        expired: { type: boolean }
        receivedAt: { type: integer, format: int64 }
        receivedUnits: { type: integer, format: int64 }
        remainingUnits: { type: integer, format: int64 }
        unitCostCents: { type: integer, format: int64 }
        supplierId: { type: string, nullable: true }
        poId: { type: string, nullable: true }
      required: [id, batchCode, productId, name, locationId, receivedAt, receivedUnits, remainingUnits, unitCostCents]
    SupplierPriceListImport:
      type: object
      properties:
        supplierId: { type: string }
        csv: { type: string, description: "The file's text." }
        fingerprint: { type: string, nullable: true, description: "Required on commit: the review's fingerprint." }
      required: [supplierId, csv]
    SupplierPriceListReview:
      type: object
      properties:
        summary: { type: string }
        fatal: { type: string, nullable: true }
        delimiter: { type: string, nullable: true }
        recognisedColumns: { type: object, additionalProperties: { type: string } }
        ignoredColumns: { type: array, items: { type: string } }
        rows:
          type: array
          items:
            type: object
            properties:
              line: { type: integer }
              outcome: { type: string, description: "UPDATE | ADD | UNCHANGED | REFUSED" }
              productName: { type: string, nullable: true }
              code: { type: string, nullable: true }
              detail: { type: string, nullable: true }
              changes:
                type: array
                items:
                  type: object
                  properties:
                    field: { type: string }
                    before: { type: string, nullable: true }
                    after: { type: string }
              warnings: { type: array, items: { type: string } }
        notListed: { type: array, items: { type: string } }
        updates: { type: integer }
        adds: { type: integer }
        unchanged: { type: integer }
        refused: { type: integer }
        fingerprint: { type: string }
      required: [summary, fingerprint]
    MovementJournalPage:
      type: object
      properties:
        total: { type: integer, format: int64 }
        offset: { type: integer, format: int64 }
        limit: { type: integer }
        rows:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              occurredAt: { type: integer, format: int64 }
              locationId: { type: string }
              locationName: { type: string, nullable: true }
              productId: { type: string }
              productName: { type: string, nullable: true }
              variantId: { type: string, nullable: true }
              variantName: { type: string, nullable: true }
              sku: { type: string, nullable: true }
              deltaUnits: { type: integer, format: int64 }
              reason: { type: string }
              reasonLabel: { type: string, nullable: true }
              reasonClass: { type: string, nullable: true }
              referenceId: { type: string, nullable: true }
              note: { type: string, nullable: true }
              batchId: { type: string, nullable: true }
              unitCostCents: { type: integer, format: int64, nullable: true, description: "Null before costing (V21); not zero." }
              valueDeltaCents: { type: integer, format: int64 }
              staffId: { type: string, nullable: true }
              staffName: { type: string, nullable: true }
              staffBasis: { type: string, nullable: true, description: "MOVEMENT | SALE" }
              deviceId: { type: string, nullable: true }
              deviceName: { type: string, nullable: true }
              deviceBasis: { type: string, nullable: true, description: "SALE, or null: no device recorded." }
        summary:
          type: array
          items:
            type: object
            properties:
              reason: { type: string }
              reasonLabel: { type: string, nullable: true }
              reasonClass: { type: string, nullable: true }
              movements: { type: integer, format: int64 }
              unitsIn: { type: integer, format: int64 }
              unitsOut: { type: integer, format: int64 }
              valueDeltaCents: { type: integer, format: int64 }
              uncosted: { type: integer, format: int64 }
        reasonChoices:
          type: array
          items:
            type: object
            properties:
              code: { type: string }
              label: { type: string }
              reasonClass: { type: string, nullable: true }
    ExpiryReport:
      type: object
      properties:
        criticalDays: { type: integer }
        warningDays: { type: integer }
        alerts:
          type: array
          items:
            type: object
            properties:
              batchId: { type: string }
              batchCode: { type: string }
              productId: { type: string }
              productName: { type: string, nullable: true }
              variantId: { type: string, nullable: true }
              locationId: { type: string }
              tier: { type: string, description: "EXPIRED | CRITICAL | WARNING" }
              expiresAt: { type: integer, format: int64, nullable: true }
              daysToExpiry: { type: integer, nullable: true, description: "Negative once past its date." }
              unitsAtRisk: { type: integer, format: int64 }
              unitCostCents: { type: integer, format: int64 }
              valueAtRiskCents: { type: integer, format: int64 }
        totals:
          type: array
          items:
            type: object
            properties:
              tier: { type: string }
              lots: { type: integer }
              units: { type: integer, format: int64 }
              valueAtRiskCents: { type: integer, format: int64 }
        valueAtRiskCents: { type: integer, format: int64 }
        expiredValueCents: { type: integer, format: int64 }
        coverage:
          type: array
          items:
            type: object
            properties:
              productId: { type: string }
              productName: { type: string, nullable: true }
              variantId: { type: string, nullable: true }
              locationId: { type: string }
              onHandUnits: { type: integer, format: int64 }
              lottedUnits: { type: integer, format: int64 }
              unlottedUnits: { type: integer, format: int64 }
      required: [criticalDays, warningDays, alerts, totals, valueAtRiskCents, expiredValueCents, coverage]
    BatchTraceLocation:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string, nullable: true }
        remainingUnits: { type: integer, format: int64 }
      required: [locationId, remainingUnits]
    BatchTrace:
      type: object
      properties:
        batchCode: { type: string }
        receivedUnits: { type: integer, format: int64 }
        remainingUnits: { type: integer, format: int64 }
        locations: { type: array, items: { $ref: "#/components/schemas/BatchTraceLocation" } }
        batches: { type: array, items: { $ref: "#/components/schemas/BatchEntry" } }
      required: [batchCode, receivedUnits, remainingUnits, locations, batches]
    BatchDrift:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        variantId: { type: string, nullable: true }
        onHandUnits: { type: integer, format: int64 }
        lotUnits: { type: integer, format: int64 }
        driftUnits: { type: integer, format: int64, description: "on-hand minus live lot total." }
      required: [productId, name, onHandUnits, lotUnits, driftUnits]
    CreateBatchRequest:
      type: object
      properties:
        locationId: { type: string }
        productId: { type: string }
        batchCode: { type: string }
        quantityUnits: { type: integer, format: int64 }
        unitCostCents: { type: integer, format: int64 }
        variantId: { type: string, nullable: true }
        expiresAt: { type: integer, format: int64, nullable: true, description: "Omit to derive from the product's shelfLifeDays." }
        supplierId: { type: string, nullable: true }
        reason: { type: string, nullable: true, default: BATCH_IN }
        note: { type: string, nullable: true }
        approverPin: { type: string, nullable: true, description: "Another manager's PIN, sent only after a 409 second_approver_required (a lot costed below what the holding carries). Never stored or returned." }
      required: [locationId, productId, batchCode, quantityUnits, unitCostCents]
    CreateBatchResponse:
      type: object
      properties:
        batchId: { type: string }
        batchCode: { type: string }
        onHandAfter: { type: integer, format: int64 }
        valueAfterCents: { type: integer, format: int64 }
      required: [batchId, batchCode, onHandAfter, valueAfterCents]
    WriteOffBatchRequest:
      type: object
      properties:
        batchIds: { type: array, items: { type: string } }
        note: { type: string, nullable: true }
      required: [batchIds]
    WriteOffBatchResponse:
      type: object
      properties:
        lotsWrittenOff: { type: integer }
        unitsWrittenOff: { type: integer, format: int64 }
        valueWrittenOffCents: { type: integer, format: int64 }
        eightySixed: { type: array, items: { type: string } }
      required: [lotsWrittenOff, unitsWrittenOff, valueWrittenOffCents]

    # ── Supplier returns / RTV (V22) ──
    CreateReturnRequest:
      type: object
      properties:
        locationId: { type: string }
        supplierId: { type: string }
        lines: { type: array, items: { $ref: "#/components/schemas/CreateReturnLine" } }
        reason: { type: string, enum: [DAMAGED, FAULTY, EXPIRED, OVER_SUPPLIED, RECALL, OTHER], default: OTHER }
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
      required: [locationId, supplierId, lines]
    CreateReturnLine:
      type: object
      properties:
        productId: { type: string }
        quantityUnits: { type: integer, format: int64 }
        variantId: { type: string, nullable: true }
        reason: { type: string, nullable: true, description: "Overrides the header reason for a mixed return." }
        note: { type: string, nullable: true }
      required: [productId, quantityUnits]
    CreditReturnRequest:
      type: object
      properties:
        creditCents: { type: integer, format: int64, description: "May be less than the claim; 0 records a refused claim." }
        creditNoteRef: { type: string, nullable: true }
      required: [creditCents]
    SendReturnResponse:
      type: object
      properties:
        id: { type: string }
        status: { type: string }
        totalCents: { type: integer, format: int64 }
        eightySixed: { type: array, items: { type: string } }
      required: [id, status, totalCents]
    SupplierReturnLine:
      type: object
      properties:
        id: { type: string }
        productId: { type: string }
        name: { type: string }
        variantId: { type: string, nullable: true }
        quantityUnits: { type: integer, format: int64 }
        unitCostCents: { type: integer, format: int64, description: "Frozen when sent — a later price change cannot restate the claim." }
        lineTotalCents: { type: integer, format: int64 }
        reason: { type: string, nullable: true }
        note: { type: string, nullable: true }
      required: [id, productId, name, quantityUnits, unitCostCents, lineTotalCents]
    SupplierReturn:
      type: object
      properties:
        id: { type: string }
        reference: { type: string, description: "e.g. `RTV-20260804-000001`." }
        locationId: { type: string }
        supplierId: { type: string }
        supplierName: { type: string, nullable: true }
        status: { type: string, enum: [DRAFT, SENT, CREDITED, CANCELLED] }
        reason: { type: string }
        note: { type: string, nullable: true }
        totalCents: { type: integer, format: int64, description: "0 until sent — lines are priced on send." }
        creditCents: { type: integer, format: int64, nullable: true }
        shortfallCents: { type: integer, format: int64, nullable: true, description: "Claimed minus credited; null until a credit is recorded." }
        creditNoteRef: { type: string, nullable: true }
        sentAt: { type: integer, format: int64, nullable: true }
        creditedAt: { type: integer, format: int64, nullable: true }
        createdAt: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/SupplierReturnLine" } }
      required: [id, reference, locationId, supplierId, status, reason, totalCents, createdAt]

    # ── Loyalty points (V24) ──
    LoyaltySettingsRequest:
      type: object
      description: "Keep-on-absent — omitted fields keep their current value."
      properties:
        pointsPerRandBp: { type: integer, nullable: true, description: "Basis points of a point per rand earned; 1000 = 0.1 pts/rand." }
        centsPerPoint: { type: integer, format: int64, nullable: true, description: "What one point is worth when spent; 100 = R1.00. Must be >= 1." }
        minRedeemPoints: { type: integer, format: int64, nullable: true }
        maxRedeemPctBp: { type: integer, nullable: true, description: "Cap on redemption as a share of the bill; 5000 = 50%, 10000 = settle in full." }
        redemptionActive: { type: boolean, nullable: true, description: "False refuses redemption but leaves earning running." }
    LoyaltySettings:
      type: object
      properties:
        pointsPerRandBp: { type: integer }
        centsPerPoint: { type: integer, format: int64 }
        minRedeemPoints: { type: integer, format: int64 }
        maxRedeemPctBp: { type: integer }
        redemptionActive: { type: boolean }
      required: [pointsPerRandBp, centsPerPoint, minRedeemPoints, maxRedeemPctBp, redemptionActive]
    LoyaltyLedgerEntry:
      type: object
      properties:
        id: { type: string }
        deltaPoints: { type: integer, format: int64, description: "Negative on a REDEEM." }
        reason: { type: string, description: "EARN | REDEEM | REDEEM_REVERSED | manual adjustment." }
        referenceId: { type: string, nullable: true, description: "The order, where one applies." }
        occurredAt: { type: integer, format: int64 }
      required: [id, deltaPoints, reason, occurredAt]
    LoyaltyBalance:
      type: object
      properties:
        customerId: { type: string }
        name: { type: string }
        points: { type: integer, format: int64 }
        valueCents: { type: integer, format: int64, description: "points x centsPerPoint." }
        tier: { type: string }
        recent: { type: array, items: { $ref: "#/components/schemas/LoyaltyLedgerEntry" } }
      required: [customerId, name, points, valueCents, tier]
    LoyaltyQuoteRequest:
      type: object
      properties:
        customerId: { type: string }
        orderId: { type: string }
      required: [customerId, orderId]
    LoyaltyQuote:
      type: object
      properties:
        orderId: { type: string }
        customerId: { type: string }
        balancePoints: { type: integer, format: int64 }
        balanceValueCents: { type: integer, format: int64, description: "What the WHOLE balance is worth — reported even when redemption is off." }
        maxPoints: { type: integer, format: int64, description: "The largest redemption allowed on this bill." }
        maxValueCents: { type: integer, format: int64 }
        outstandingCents: { type: integer, format: int64, description: "Subtotal less discounts already applied." }
        centsPerPoint: { type: integer, format: int64 }
        available: { type: boolean }
        cappedByBill: { type: boolean, description: "True when the guest could have spent more if the bill allowed." }
        reason: { type: string, enum: [OK, DISABLED, BELOW_MINIMUM, NOTHING_TO_DISCOUNT, NO_BALANCE] }
      required: [orderId, customerId, balancePoints, balanceValueCents, maxPoints, maxValueCents, outstandingCents, centsPerPoint, available, cappedByBill, reason]
    LoyaltyRedeemRequest:
      type: object
      properties:
        customerId: { type: string }
        orderId: { type: string }
        points: { type: integer, format: int64, description: "Must be <= the quote's maxPoints; more is refused, not trimmed." }
        byStaffId: { type: string, nullable: true }
      required: [customerId, orderId, points]
    LoyaltyRedeemResult:
      type: object
      properties:
        orderId: { type: string }
        customerId: { type: string }
        pointsRedeemed: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        remainingPoints: { type: integer, format: int64 }
        orderDiscountCents: { type: integer, format: int64, description: "Total order discount, including any voucher already applied." }
        orderOutstandingCents: { type: integer, format: int64 }
      required: [orderId, customerId, pointsRedeemed, discountCents, remainingPoints, orderDiscountCents, orderOutstandingCents]
    LoyaltyReverseRequest:
      type: object
      properties:
        orderId: { type: string }
      required: [orderId]
    LoyaltyReverseResult:
      type: object
      properties:
        orderId: { type: string }
        customerId: { type: string }
        pointsReturned: { type: integer, format: int64 }
        discountRemovedCents: { type: integer, format: int64 }
        remainingPoints: { type: integer, format: int64 }
      required: [orderId, customerId, pointsReturned, discountRemovedCents, remainingPoints]

    # ── Promotions (V25) ──
    PromotionUpsertRequest:
      type: object
      description: |
        Fields are interpreted per `promoType`, and validated server-side:
          • BUY_X_GET_Y — buyQuantity, getQuantity, getDiscountBp (10000 = free).
          • MULTI_BUY — buyQuantity (>= 2) and bundlePriceCents. Mix-and-match and bundles are this, scoped to a category or several products.
          • QUANTITY_BREAK — buyQuantity (>= 2) and value as basis points, 1..10000: every qualifying unit is that much off once there are buyQuantity of them.
          • BASKET_PERCENT — value as basis points, 1..10000.
          • BASKET_FIXED — value as cents.
        On create `name` and `promoType` are required; on update all are keep-on-absent.
      properties:
        name: { type: string, nullable: true }
        description: "{ type: string, nullable: true }"
        promoType: { type: string, nullable: true, enum: [BUY_X_GET_Y, MULTI_BUY, QUANTITY_BREAK, BASKET_PERCENT, BASKET_FIXED] }
        buyQuantity: { type: integer, nullable: true }
        getQuantity: { type: integer, nullable: true }
        getDiscountBp: { type: integer, nullable: true, description: "1..10000; 10000 = free, 5000 = half price. 0 is refused." }
        bundlePriceCents: { type: integer, format: int64, nullable: true }
        value: { type: integer, format: int64, nullable: true }
        minBasketCents: { type: integer, format: int64, nullable: true, description: "Gate on the WHOLE basket, even when the discount is scoped." }
        scopeType: { type: string, nullable: true, enum: [ALL, CATEGORY, PRODUCT] }
        scopeIds: { type: array, nullable: true, items: { type: string } }
        daysOfWeek: { type: string, nullable: true, description: "Letters from MTWRFSU, same encoding as price rules." }
        startMinute: { type: integer, nullable: true, description: "0..1439. A start after the end is an overnight window and fires across midnight." }
        endMinute: { type: integer, nullable: true }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        locationIds: { type: array, nullable: true, items: { type: string }, description: "Omit for every location." }
        code: { type: string, nullable: true, description: "Omit to auto-apply; set to require the cashier to key it. Unique per tenant, matched case-insensitively." }
        priority: { type: integer, nullable: true, description: "Orders stackable offers, and breaks ties between equal non-stackable ones. It does NOT let a weaker offer beat a better one." }
        stackable: { type: boolean, nullable: true, description: "False (default) means only the single best-value qualifying offer applies." }
        maxApplicationsPerSale: { type: integer, nullable: true, description: "Omit for as many as the basket allows." }
        usageLimit: { type: integer, format: int64, nullable: true, description: "Sales, not applications, over the promotion's life." }
        active: { type: boolean, nullable: true }
        channels: { type: array, nullable: true, items: { type: string, enum: [TILL, QR, KIOSK] }, description: "Where the offer runs (T-4.5). Omit to keep what is stored (every channel on create). An empty list is refused with 400 channels_empty." }
        floorAtCost: { type: boolean, nullable: true, description: "Never take a line below the product's cost price, however the offer stacks (T-4.5)." }
    Promotion:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        description: "{ type: string, nullable: true }"
        promoType: { type: string }
        buyQuantity: { type: integer }
        getQuantity: { type: integer }
        getDiscountBp: { type: integer }
        bundlePriceCents: { type: integer, format: int64, nullable: true }
        value: { type: integer, format: int64 }
        minBasketCents: { type: integer, format: int64 }
        scopeType: { type: string }
        scopeIds: { type: array, items: { type: string } }
        daysOfWeek: { type: string }
        startMinute: { type: integer }
        endMinute: { type: integer }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        locationIds: { type: array, nullable: true, items: { type: string }, description: "Null = every location; an empty list would mean none." }
        code: { type: string, nullable: true }
        priority: { type: integer }
        stackable: { type: boolean }
        maxApplicationsPerSale: { type: integer, nullable: true }
        usageLimit: { type: integer, format: int64, nullable: true }
        usageCount: { type: integer, format: int64 }
        active: { type: boolean }
        channels: { type: array, nullable: true, items: { type: string, enum: [TILL, QR, KIOSK] }, description: "Null = every channel (T-4.5)." }
        floorAtCost: { type: boolean, default: false }
      required: [id, name, promoType, buyQuantity, getQuantity, getDiscountBp, value, minBasketCents, scopeType, daysOfWeek, startMinute, endMinute, priority, stackable, usageCount, active]
    EvaluateRequest:
      type: object
      properties:
        orderId: { type: string }
        codes: { type: array, items: { type: string }, description: "Codes the cashier has keyed." }
      required: [orderId]
    PromotionAward:
      type: object
      properties:
        promotionId: { type: string }
        name: { type: string }
        type: { type: string }
        applications: { type: integer }
        discountCents: { type: integer, format: int64 }
        affectedLineIds: { type: array, items: { type: string } }
        detail: { type: string, description: "Human-facing summary, e.g. \"2 x buy 2 get 1 free\"." }
      required: [promotionId, name, type, applications, discountCents, detail]
    PromotionSkip:
      type: object
      properties:
        promotionId: { type: string }
        name: { type: string }
        reason:
          type: string
          enum: [INACTIVE, OUT_OF_WINDOW, WRONG_LOCATION, WRONG_CHANNEL, CODE_NOT_ENTERED, USAGE_LIMIT_REACHED,
                 NOT_ENOUGH_QUALIFYING_ITEMS, BELOW_MINIMUM_BASKET, NO_DISCOUNT_EARNED,
                 SUPERSEDED_BY_BETTER_OFFER, NOTHING_LEFT_TO_DISCOUNT, CAP_SPENT]
      required: [promotionId, name, reason]
    PromotionEvaluation:
      type: object
      properties:
        totalDiscountCents: { type: integer, format: int64 }
        awards: { type: array, items: { $ref: "#/components/schemas/PromotionAward" } }
        skipped: { type: array, items: { $ref: "#/components/schemas/PromotionSkip" } }
      required: [totalDiscountCents]
    ApplyPromotionsResponse:
      type: object
      properties:
        orderId: { type: string }
        promotionDiscountCents: { type: integer, format: int64 }
        awards: { type: array, items: { $ref: "#/components/schemas/PromotionAward" } }
        skipped: { type: array, items: { $ref: "#/components/schemas/PromotionSkip" } }
      required: [orderId, promotionDiscountCents]
    PromotionPerformance:
      type: object
      properties:
        promotionId: { type: string }
        name: { type: string }
        usageCount: { type: integer, format: int64, description: "The counter the engine gates on." }
        usageLimit: { type: integer, format: int64, nullable: true }
        salesCount: { type: integer, description: "Derived from redemption rows; the truth if it disagrees with usageCount." }
        totalApplications: { type: integer }
        totalDiscountCents: { type: integer, format: int64 }
        averageDiscountCents: { type: integer, format: int64, nullable: true, description: "Null when it has never fired — distinct from an average of 0." }
      required: [promotionId, name, usageCount, salesCount, totalApplications, totalDiscountCents]

    # ── Composite bundles (V26) ──
    BundleOptionUpsert:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true, description: "The specific SKU when the component is variant-bearing." }
        priceDeltaCents: { type: integer, format: int64, description: "Signed upcharge for a premium pick, applied before apportionment." }
        isDefault: { type: boolean, description: "Pre-selected, so a fixed component needs no tap at the till." }
      required: [productId]
    BundleSlotUpsert:
      type: object
      properties:
        name: { type: string, description: "What the till prompts with, e.g. \"Choose a side\"." }
        quantity: { type: integer, default: 1, description: "How many picks; 2 = \"any two sides\". Must not exceed the option count." }
        required: { type: boolean, default: true, description: "False lets a guest decline. The bundle price is unchanged — declining must not make the meal cheaper for the venue to sell." }
        options: { type: array, items: { $ref: "#/components/schemas/BundleOptionUpsert" } }
      required: [name, options]
    BundleUpsertRequest:
      type: object
      description: |
        pricingMode:
          • FIXED — the bundle product's own priceCents is the bundle price.
          • SUM_MINUS_PCT — components at list, less discountBp.
          • SUM — components at list (a convenience bundle, not a saving).
      properties:
        productId: { type: string }
        pricingMode: { type: string, default: FIXED, enum: [FIXED, SUM_MINUS_PCT, SUM] }
        discountBp: { type: integer, default: 0, description: "Basis points; only read for SUM_MINUS_PCT." }
        description: "{ type: string, nullable: true }"
        active: { type: boolean, default: true }
        slots: { type: array, items: { $ref: "#/components/schemas/BundleSlotUpsert" } }
      required: [productId, slots]
    BundleOption:
      type: object
      properties:
        optionId: { type: string }
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        priceDeltaCents: { type: integer, format: int64 }
        listPriceCents: { type: integer, format: int64 }
        isDefault: { type: boolean }
      required: [optionId, productId, productName]
    BundleSlot:
      type: object
      properties:
        slotId: { type: string }
        name: { type: string }
        quantity: { type: integer }
        required: { type: boolean }
        options: { type: array, items: { $ref: "#/components/schemas/BundleOption" } }
      required: [slotId, name, quantity, required]
    Bundle:
      type: object
      properties:
        productId: { type: string }
        productName: { type: string, nullable: true }
        pricingMode: { type: string }
        discountBp: { type: integer }
        fixedPriceCents: { type: integer, format: int64, description: "The bundle product's own price — the bundle price under FIXED." }
        description: "{ type: string, nullable: true }"
        active: { type: boolean }
        slots: { type: array, items: { $ref: "#/components/schemas/BundleSlot" } }
      required: [productId, pricingMode, discountBp, fixedPriceCents, active]
    BundleSelection:
      type: object
      properties:
        slotId: { type: string }
        optionIds: { type: array, items: { type: string }, description: "One id per pick; a slot taking 2 needs 2." }
      required: [slotId, optionIds]
    BundleQuoteRequest:
      type: object
      properties:
        selections: { type: array, items: { $ref: "#/components/schemas/BundleSelection" }, description: "Omit to price the bundle's defaults." }
    BundleComponent:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        name: { type: string }
        vatType: { type: string, description: "The component's OWN type — a mixed-rate bundle taxes each part correctly." }
        lineTotalCents: { type: integer, format: int64, description: "This component's apportioned share of the bundle price." }
        listPriceCents: { type: integer, format: int64 }
        slotId: { type: string }
        optionId: { type: string }
      required: [productId, name, vatType, lineTotalCents, listPriceCents, slotId, optionId]
    BundleQuote:
      type: object
      properties:
        productId: { type: string }
        bundlePriceCents: { type: integer, format: int64 }
        listTotalCents: { type: integer, format: int64 }
        savingCents: { type: integer, format: int64, description: "List less bundle price. Zero for SUM, and negative if a declined optional slot leaves less on the plate than the fixed price." }
        components: { type: array, items: { $ref: "#/components/schemas/BundleComponent" } }
      required: [productId, bundlePriceCents, listTotalCents, savingCents]
    AddBundleRequest:
      type: object
      properties:
        productId: { type: string }
        selections: { type: array, items: { $ref: "#/components/schemas/BundleSelection" }, description: "Omit to use the defaults." }
        quantity: { type: integer, default: 1, description: "Each becomes an independent bundle instance with its own group id." }
        seatNumber: { type: integer, nullable: true }
        note: { type: string, nullable: true }
      required: [productId]
    AddBundleResponse:
      type: object
      properties:
        orderId: { type: string }
        bundleProductId: { type: string }
        bundleGroupIds: { type: array, items: { type: string }, description: "One per bundle instance." }
        linesAdded: { type: integer }
        bundlePriceCents: { type: integer, format: int64 }
        totalAddedCents: { type: integer, format: int64 }
        savingCents: { type: integer, format: int64 }
        orderSubtotalCents: { type: integer, format: int64 }
      required: [orderId, bundleProductId, linesAdded, bundlePriceCents, totalAddedCents, savingCents, orderSubtotalCents]

    # ── Price lists (V27) ──
    PriceListUpsertRequest:
      type: object
      description: "Keep-on-absent on update; `name` is required on create."
      properties:
        name: { type: string, nullable: true }
        description: "{ type: string, nullable: true }"
        upliftBp: { type: integer, nullable: true, description: "Signed basis points for anything not itemised; 1500 = +15%. Range -10000..100000." }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true, description: "Outside the window the list is ignored and its locations fall back to base prices." }
        active: { type: boolean, nullable: true, description: "False makes every assigned location sell at base without unassigning anything." }
    AssignedLocation:
      type: object
      properties:
        locationId: { type: string }
        locationName: { type: string }
      required: [locationId, locationName]
    CollectSlot:
      type: object
      properties:
        startsAt: { type: integer, format: int64 }
        endsAt: { type: integer, format: int64 }
        available: { type: integer, description: Remaining capacity. Full slots are omitted entirely. }
    CollectSlots:
      type: object
      properties:
        locationId: { type: string }
        leadMinutes: { type: integer, description: Notice required. Rounds UP to the next slot boundary. }
        allowPayOnCollection: { type: boolean }
        maxPerItem: { type: integer, format: int64, default: 50, description: "The most of one item an order may take at this venue (T-2.54, D-110): the venue's own setting, 1 to 9999, else 50. A larger quantity is refused `400 invalid_quantity` with a sentence naming this figure. A page's quantity stepper stops at it." }
        slots: { type: array, items: { $ref: "#/components/schemas/CollectSlot" } }
        promotions:
          type: array
          description: "The venue's live offers a guest's order is priced by (T-43.26): the QR menu's own, never one that may take a line below its cost."
          items: { $ref: "#/components/schemas/CollectPromotion" }
    CollectPromotion:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        type: { type: string }
        scope: { type: string }
        scopeIds: { type: array, items: { type: string } }
        buyQuantity: { type: integer }
        getQuantity: { type: integer }
        getDiscountBp: { type: integer }
        bundlePriceCents: { type: integer, format: int64, nullable: true }
        value: { type: integer, format: int64 }
        minBasketCents: { type: integer, format: int64 }
        daysOfWeek: { type: string }
        startMinute: { type: integer }
        endMinute: { type: integer }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        priority: { type: integer }
        stackable: { type: boolean }
        maxApplicationsPerSale: { type: integer, nullable: true }
        channels: { type: array, nullable: true, items: { type: string } }
    CollectOffer:
      type: object
      properties:
        promotionId: { type: string }
        name: { type: string }
        discountCents: { type: integer, format: int64 }
    CollectCatalogueItem:
      type: object
      properties:
        productId: { type: string }
        name: { type: string }
        priceCents: { type: integer, format: int64, description: Resolved at this location, server-side. }
        vatType: { type: string }
        availableUnits:
          type: integer
          format: int64
          nullable: true
          description: >-
            `on_hand - reserved`, never on-hand. Null for a product that does not track
            stock — nothing to run out of.
    CollectLineRequest:
      type: object
      required: [productId, quantity]
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        quantity: { type: integer, format: int64 }
    PlaceCollectOrderRequest:
      type: object
      required: [contactName, contactPhone, slotStartsAt, lines]
      properties:
        contactName: { type: string }
        contactPhone: { type: string }
        contactEmail: { type: string, nullable: true }
        slotStartsAt: { type: integer, format: int64, description: Validated against the generated slot list. }
        paymentMode: { type: string, enum: [ONLINE, ON_COLLECTION], default: ONLINE }
        clientToken:
          type: string
          nullable: true
          description: Strongly recommended — makes a double-tap idempotent.
        note: { type: string, nullable: true }
        lines: { type: array, items: { $ref: "#/components/schemas/CollectLineRequest" } }
    CollectPlaced:
      type: object
      properties:
        collectOrderId: { type: string }
        reference: { type: string, example: "COL-20260804-000001" }
        status: { type: string }
        totalCents: { type: integer, format: int64, description: "The quote: subtotalCents less promotionDiscountCents. Checkout charges it (T-43.26)." }
        subtotalCents: { type: integer, format: int64, description: The lines' total before offers. }
        promotionDiscountCents: { type: integer, format: int64 }
        offers: { type: array, items: { $ref: "#/components/schemas/CollectOffer" }, description: "The discount lines, one per offer, as the quote kept them; a replay answers the same (empty for an order quoted before they were kept)." }
        slotStartsAt: { type: integer, format: int64 }
        expiresAt:
          type: integer
          format: int64
          nullable: true
          description: When the hold lapses if unpaid. Null once paid — a paid order never expires.
        duplicate: { type: boolean, description: True when this clientToken had already ordered. }
        unavailableProductIds: { type: array, items: { type: string } }
    CollectTracking:
      type: object
      description: >-
        Deliberately narrow — no phone number, note, reservation flag, expiry or line
        detail. A public surface shows progress, not operational state.
      properties:
        reference: { type: string }
        status: { type: string }
        slotStartsAt: { type: integer, format: int64 }
        slotEndsAt: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        readyForCollection: { type: boolean }
        message: { type: string, description: Progress in words. }
    CollectSettingsRequest:
      type: object
      required: [locationId]
      properties:
        locationId: { type: string }
        enabled: { type: boolean, nullable: true, description: False until a venue opts in. }
        slotMinutes: { type: integer, minimum: 5, maximum: 240, nullable: true }
        slotCapacity: { type: integer, minimum: 1, nullable: true }
        leadMinutes: { type: integer, nullable: true }
        openMinute: { type: integer, nullable: true, description: Minutes from midnight, SAST. }
        closeMinute: { type: integer, nullable: true }
        holdMinutes: { type: integer, minimum: 1, maximum: 1440, nullable: true }
        allowPayOnCollection: { type: boolean, nullable: true }
    CollectSettings:
      type: object
      properties:
        locationId: { type: string }
        enabled: { type: boolean }
        slotMinutes: { type: integer }
        slotCapacity: { type: integer }
        leadMinutes: { type: integer }
        openMinute: { type: integer }
        closeMinute: { type: integer }
        holdMinutes: { type: integer }
        allowPayOnCollection: { type: boolean }
    CollectPayRequest:
      type: object
      required: [amountCents]
      properties:
        method: { type: string, default: CARD }
        amountCents: { type: integer, format: int64 }
        tenderedCents: { type: integer, format: int64, nullable: true }
        providerReference: { type: string, nullable: true }
    CollectMoney:
      type: object
      properties:
        collectOrderId: { type: string }
        orderId: { type: string }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        balanceDueCents: { type: integer, format: int64 }
        status: { type: string }
    CollectHandoverRequest:
      type: object
      properties:
        payments:
          type: array
          items: { $ref: "#/components/schemas/PaymentLeg" }
          description: Only what is left — anything paid online already counts.
        ageCheck: { type: object, nullable: true, description: "T-37.1 - the age check made at the hand-over: required when the order has an age-restricted line (`409 age_check_required` without it, and nothing is handed over). Recorded as TILL and the signed-in person.", properties: { surface: { type: string, enum: [TILL, QR, KIOSK, ONLINE_STORE] }, staffId: { type: string, nullable: true }, atMs: { type: integer, format: int64, nullable: true } }, required: [surface] }
    CollectHandover:
      type: object
      properties:
        collectOrderId: { type: string }
        orderId: { type: string }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
    CollectCancelled:
      type: object
      properties:
        collectOrderId: { type: string }
        unitsReleased: { type: integer, format: int64 }
        refundDueCents: { type: integer, format: int64, description: Reported, never silently kept. }
    CollectSweepResult:
      type: object
      properties:
        expired: { type: integer }
        unitsReleased: { type: integer, format: int64 }
        markedShort: { type: integer, description: Orders a walk-in has taken stock from. }
    CollectOrderLine:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        name: { type: string, description: The name the customer saw when ordering. }
        quantity: { type: integer, format: int64 }
        unitPriceCents: { type: integer, format: int64, description: Frozen at order time. }
        lineTotalCents: { type: integer, format: int64 }
        reservedUnits: { type: integer, format: int64, description: Units currently held. Zero after a release. }
    CollectOrder:
      type: object
      properties:
        id: { type: string }
        reference: { type: string }
        locationId: { type: string }
        locationName: { type: string, nullable: true }
        contactName: { type: string }
        contactPhone: { type: string }
        contactEmail: { type: string, nullable: true }
        slotStartsAt: { type: integer, format: int64 }
        slotEndsAt: { type: integer, format: int64 }
        status:
          type: string
          enum: [PENDING_PAYMENT, RESERVED, READY, SHORT, COLLECTED, CANCELLED, EXPIRED]
        standing: { type: string, description: What to do next, in words. }
        paymentMode: { type: string }
        orderId: { type: string, nullable: true }
        stockReserved: { type: boolean }
        expiresAt: { type: integer, format: int64, nullable: true }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        balanceDueCents: { type: integer, format: int64 }
        minutesWaiting: { type: integer, format: int64 }
        notifiedAt: { type: integer, format: int64, nullable: true }
        note: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/CollectOrderLine" } }
    RotaUpsertRequest:
      type: object
      properties:
        locationId: { type: string }
        staffId: { type: string }
        startsAt: { type: integer, format: int64, description: "Half-open with endsAt, so a 17:00 handover is not an overlap." }
        endsAt: { type: integer, format: int64 }
        breakMinutes: { type: integer, default: 0, description: Unpaid, deducted from the forecast. }
        role: { type: string, nullable: true, description: What they are rostered AS — a supervisor covering the bar is a bar shift. }
        note: { type: string, nullable: true }
    RotaShift:
      type: object
      properties:
        id: { type: string }
        staffId: { type: string }
        staffName: { type: string, nullable: true }
        role: { type: string, nullable: true }
        startsAt: { type: integer, format: int64 }
        endsAt: { type: integer, format: int64 }
        breakMinutes: { type: integer }
        plannedMinutes: { type: integer, format: int64 }
        published: { type: boolean, description: False while the week is a draft — staff cannot see it. }
    RotaStaffForecast:
      type: object
      properties:
        staffId: { type: string }
        staffName: { type: string, nullable: true }
        shifts: { type: integer }
        plannedMinutes: { type: integer, format: int64 }
        forecastCostCents: { type: integer, format: int64, nullable: true, description: "Minutes × the person's rate: null unless the session may read pay (T-37.4)." }
    Rota:
      type: object
      properties:
        periodLabel: { type: string }
        periodFrom: { type: integer, format: int64 }
        periodUntil: { type: integer, format: int64 }
        shifts: { type: array, items: { $ref: "#/components/schemas/RotaShift" } }
        forecastCostCents:
          type: integer
          format: int64
          nullable: true
          description: >-
            Null for non-managers — cost is a management figure — and for a manager's session the business's second factor
            withholds pay from (T-37.4). Priced at TODAY's rate.
        plannedMinutes: { type: integer, format: int64 }
        unpublishedShifts: { type: integer }
        staff: { type: array, items: { $ref: "#/components/schemas/RotaStaffForecast" } }
    RotaPublishRequest:
      type: object
      properties:
        preset: { type: string, default: THIS_WEEK }
        from: { type: integer, format: int64, nullable: true }
        until: { type: integer, format: int64, nullable: true }
        locationId: { type: string, nullable: true }
    RotaPublishResult:
      type: object
      properties:
        periodLabel: { type: string }
        periodFrom: { type: integer, format: int64 }
        periodUntil: { type: integer, format: int64 }
        shiftsPublished: { type: integer, description: Zero on a repeat — already-published shifts are not re-stamped. }
    RotaVarianceLine:
      type: object
      properties:
        staffId: { type: string }
        staffName: { type: string, nullable: true }
        plannedMinutes: { type: integer, format: int64 }
        actualMinutes: { type: integer, format: int64 }
        differenceMinutes: { type: integer, format: int64, description: Positive = worked more than rostered. }
        forecastCostCents: { type: integer, format: int64 }
        actualCostCents: { type: integer, format: int64 }
        differenceCostCents: { type: integer, format: int64 }
        verdict:
          type: string
          description: Proportional, so 15 minutes over a four-hour shift is not flagged while 15 over a 40-hour week is.
          enum: ["On the roster", "Over the roster", "Under the roster", "Rostered but did not clock in", "Worked without being rostered", "Nothing rostered or worked"]
    RotaVariance:
      type: object
      properties:
        periodLabel: { type: string }
        periodFrom: { type: integer, format: int64 }
        periodUntil: { type: integer, format: int64 }
        plannedMinutes: { type: integer, format: int64 }
        actualMinutes: { type: integer, format: int64 }
        forecastCostCents: { type: integer, format: int64 }
        actualCostCents: { type: integer, format: int64 }
        differenceCostCents: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/RotaVarianceLine" } }
    DeliveryPlatformUpsertRequest:
      type: object
      properties:
        platform: { type: string, enum: [UBER_EATS, MR_D, BOLT_FOOD, DELIVEROO, DOORDASH, OTHER] }
        displayName: { type: string, nullable: true }
        commissionBp:
          type: integer
          minimum: 0
          maximum: 10000
          description: Their cut. Above 100% the payout would be negative, so it is refused.
        locationId: { type: string }
        webhookSecret:
          type: string
          nullable: true
          writeOnly: true
          description: |
            The key the platform signs its order webhooks under. Write-only — never returned (the list says
            `webhookConfigured`); stored sealed, never in clear. A blank value clears it; omitted leaves it. A server with
            no token encryption key refuses to store one (400 `no_encryption_key`).
        active: { type: boolean, nullable: true }
    DeliveryPlatform:
      type: object
      properties:
        id: { type: string }
        platform: { type: string }
        displayName: { type: string }
        commissionBp: { type: integer }
        locationId: { type: string }
        locationName: { type: string, nullable: true }
        active: { type: boolean }
        mappedItems: { type: integer }
        ordersReceived: { type: integer }
        webhookConfigured: { type: boolean, description: Whether a secret is set — never the secret itself. }
    DeliveryItemMapRequest:
      type: object
      required: [externalItemId, productId]
      properties:
        externalItemId: { type: string }
        productId: { type: string }
        variantId: { type: string, nullable: true }
    DeliveryItemMapping:
      type: object
      properties:
        externalItemId: { type: string }
        productId: { type: string }
        productName: { type: string, nullable: true }
        variantId: { type: string, nullable: true }
    DeliveryIngestLine:
      type: object
      required: [externalItemId, name, quantity, unitPriceCents]
      properties:
        externalItemId: { type: string }
        name: { type: string, description: The platform's own wording — it reaches the kitchen ticket. }
        quantity: { type: integer, format: int64 }
        unitPriceCents:
          type: integer
          format: int64
          description: >-
            The platform's price, VAT-inclusive. Theirs, not the catalogue's: an
            aggregator's menu is usually marked up, and re-pricing would disagree with
            the customer's receipt and the platform statement.
    DeliveryIngestRequest:
      type: object
      required: [platformId, externalId, lines]
      properties:
        platformId: { type: string }
        externalId: { type: string, description: Their order id. Half the idempotency key. }
        externalRef: { type: string, nullable: true, description: The short reference printed on the bag. }
        customerName: { type: string, nullable: true }
        customerPhone: { type: string, nullable: true }
        expectedArrivalAt: { type: integer, format: int64, nullable: true, description: "When the platform's driver is expected for the order, epoch millis (T-36.9). The kitchen ticket shows it as Driver due; omitted means none is shown. A value of zero or less is refused (400 bad_expected_arrival)." }
        lines: { type: array, items: { $ref: "#/components/schemas/DeliveryIngestLine" } }
    DeliveryWebhookAck:
      type: object
      properties:
        ingested: { type: boolean }
        duplicate: { type: boolean }
        deliveryOrderId: { type: string, nullable: true }
        orderId: { type: string, nullable: true }
        status: { type: string, nullable: true, description: "RECEIVED (placed, not yet settled) or ACCEPTED." }
        unmappedItems: { type: array, items: { type: string } }
        detail: { type: string, nullable: true }
      required: [ingested]
    DeliveryIngestResult:
      type: object
      description: "commissionCents + payoutCents always equals grossCents exactly."
      properties:
        deliveryOrderId: { type: string }
        orderId: { type: string, nullable: true, description: The Ruva sale this became. }
        duplicate: { type: boolean, description: True when this external id had already been ingested — nothing was created. }
        status: { type: string, enum: [RECEIVED, ACCEPTED, REJECTED, CANCELLED] }
        grossCents: { type: integer, format: int64, description: What the customer paid. This is the sale, and output VAT is owed on it. }
        commissionCents: { type: integer, format: int64, description: The platform's cut — an expense. }
        payoutCents: { type: integer, format: int64, description: What to expect in the bank. }
        unmappedItems:
          type: array
          items: { type: string }
          description: Platform item ids with no product mapped. The order still went through.
    DeliveryOrder:
      type: object
      properties:
        id: { type: string }
        platformId: { type: string }
        platformName: { type: string, nullable: true }
        externalId: { type: string }
        externalRef: { type: string, nullable: true }
        orderId: { type: string, nullable: true }
        status: { type: string }
        grossCents: { type: integer, format: int64 }
        commissionCents: { type: integer, format: int64 }
        payoutCents: { type: integer, format: int64 }
        hasUnmappedItems: { type: boolean }
        failureReason: { type: string, nullable: true, description: "Why Ruva refused the order (status REJECTED, no sale rung; T-2.34): a line outside the sale-line bounds or more than 200 lines. A platform's retry of it is answered 400 `delivery_order_refused` and leaves this one record." }
        unmappedItems: { type: array, items: { type: string } }
        customerName: { type: string, nullable: true }
        receivedAt: { type: integer, format: int64 }
    DeliveryReconciliation:
      type: object
      properties:
        deliveryOrderId: { type: string }
        grossCents: { type: integer, format: int64 }
        expectedPayoutCents: { type: integer, format: int64 }
        actualPayoutCents: { type: integer, format: int64 }
        differenceCents: { type: integer, format: int64, description: Positive = they paid more than expected. }
        matches: { type: boolean, description: True within one cent — the platform may round the other way. }
        impliedCommissionBp: { type: integer, description: The rate the payout implies — what they are really charging. }
        note: { type: string }
    Menu:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        description: "{ type: string, nullable: true }"
        publishedVersion: { type: integer, description: What tills read. 0 = never published, so locations fall back to all products. }
        draftVersion: { type: integer }
        publishedAt: { type: integer, format: int64, nullable: true }
        active: { type: boolean }
        publishedItemCount: { type: integer }
        draftItemCount: { type: integer }
        hasDraftChanges: { type: boolean, description: Whether there is anything to publish. }
        locations: { type: array, items: { type: string } }
    MenuDraft:
      type: object
      properties:
        menuId: { type: string }
        draftVersion: { type: integer }
        publishedVersion: { type: integer }
        draftItemCount: { type: integer }
    MenuPublishResult:
      type: object
      properties:
        menuId: { type: string }
        publishedVersion: { type: integer }
        itemCount: { type: integer }
    EffectiveMenu:
      type: object
      properties:
        locationId: { type: string }
        menuId: { type: string, nullable: true }
        menuName: { type: string, nullable: true }
        version: { type: integer }
        source:
          type: string
          enum: [MENU, ALL_ACTIVE_PRODUCTS]
          description: Said out loud so a till (and whoever is debugging it) knows which mode it is in.
        productIds: { type: array, items: { type: string } }
    InvoiceLineRequest:
      type: object
      required: [description]
      properties:
        description: "{ type: string }"
        quantity: { type: integer, format: int64, default: 1 }
        unitPriceCents: { type: integer, format: int64, default: 0, description: Negative expresses an agreed reduction, visibly. }
        vatType: { type: string, nullable: true, enum: [STANDARD, ZERO, EXEMPT] }
    InvoiceCreateRequest:
      type: object
      properties:
        houseAccountId: { type: string, nullable: true }
        customerId: { type: string, nullable: true }
        locationId: { type: string, nullable: true }
        billToName: { type: string, nullable: true }
        billToEmail: { type: string, nullable: true }
        billToVatNumber: { type: string, nullable: true }
        terms: { type: string, nullable: true }
        note: { type: string, nullable: true }
        transactionIds:
          type: array
          items: { type: string }
          description: Sales to consolidate. Each can only ever appear on one invoice.
        lines: { type: array, items: { $ref: "#/components/schemas/InvoiceLineRequest" } }
    InvoiceLinesRequest:
      type: object
      properties:
        transactionIds: { type: array, items: { type: string } }
        lines: { type: array, items: { $ref: "#/components/schemas/InvoiceLineRequest" } }
    InvoicePaymentRequest:
      type: object
      required: [amountCents]
      properties:
        amountCents: { type: integer, format: int64 }
        method: { type: string, default: EFT }
        reference: { type: string, nullable: true }
        receivedAt: { type: integer, format: int64, nullable: true }
    InvoiceTotals:
      type: object
      properties:
        subtotalCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        lineCount: { type: integer }
    InvoiceLine:
      type: object
      properties:
        transactionId: { type: string, nullable: true, description: The sale billed. Unique per tenant — a sale can only be invoiced once. }
        description: "{ type: string, description: Survives a product rename or a voided sale. }"
        quantity: { type: integer, format: int64 }
        unitPriceCents: { type: integer, format: int64 }
        vatType: { type: string }
        lineTotalCents: { type: integer, format: int64 }
    InvoicePaymentEntry:
      type: object
      properties:
        amountCents: { type: integer, format: int64 }
        method: { type: string }
        reference: { type: string, nullable: true }
        receivedAt: { type: integer, format: int64 }
    Invoice:
      type: object
      properties:
        id: { type: string }
        invoiceNumber: { type: string, example: "INV-20260804-000001" }
        houseAccountId: { type: string, nullable: true }
        customerId: { type: string, nullable: true }
        locationId: { type: string }
        billToName: { type: string, nullable: true, description: Snapshotted at creation — a later contact change does not alter a sent document. }
        billToEmail: { type: string, nullable: true }
        billToVatNumber: { type: string, nullable: true }
        status: { type: string, enum: [DRAFT, ISSUED, PAID, VOID] }
        displayStatus:
          type: string
          enum: [DRAFT, ISSUED, OVERDUE, PAID, VOID]
          description: Derived. An ISSUED invoice past its due date reads OVERDUE; paid beats overdue.
        daysOverdue: { type: integer, format: int64 }
        issuedAt: { type: integer, format: int64, nullable: true }
        dueAt: { type: integer, format: int64, nullable: true }
        paidAt: { type: integer, format: int64, nullable: true }
        voidedAt: { type: integer, format: int64, nullable: true }
        voidReason: { type: string, nullable: true }
        subtotalCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64, description: The portion already inside totalCents. }
        totalCents: { type: integer, format: int64, description: Negative on a credit note. }
        paidCents: { type: integer, format: int64 }
        balanceDueCents: { type: integer, format: int64, description: Never negative. }
        creditNoteOf: { type: string, nullable: true, description: Set on a credit note, pointing at the invoice it corrects. }
        terms: { type: string, nullable: true }
        note: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/InvoiceLine" } }
        payments: { type: array, items: { $ref: "#/components/schemas/InvoicePaymentEntry" } }
    ReportPreset:
      type: object
      properties:
        preset: { type: string, example: LAST_MONTH }
        label: { type: string, example: Last month }
        fromMs: { type: integer, format: int64 }
        untilMs: { type: integer, format: int64, description: Exclusive. In-progress periods end at now. }
    ReportTemplateUpsertRequest:
      type: object
      properties:
        name: { type: string }
        reportType: { type: string, enum: [products, labour, by-dimension, sales] }
        datePreset:
          type: string
          enum: [TODAY, YESTERDAY, THIS_WEEK, LAST_WEEK, THIS_MONTH, LAST_MONTH, LAST_7_DAYS, LAST_30_DAYS, THIS_YEAR, CUSTOM]
          default: LAST_MONTH
          description: The intent, resolved against the clock on every run — never two stored dates.
        customFrom: { type: integer, format: int64, nullable: true, description: CUSTOM only. }
        customUntil: { type: integer, format: int64, nullable: true }
        params:
          type: array
          items: { type: string }
          nullable: true
          description: "`key=value` options, e.g. `dimension=supplier`. Unknown keys are ignored."
        locationId: { type: string, nullable: true, description: Null = every location. }
    ReportTemplate:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        reportType: { type: string }
        datePreset: { type: string }
        resolvedFrom: { type: integer, format: int64, description: What the preset covers right now. Computed live, never stored. }
        resolvedUntil: { type: integer, format: int64 }
        periodLabel: { type: string }
        params: { type: array, items: { type: string } }
        locationId: { type: string, nullable: true }
        locationName: { type: string, nullable: true }
        scheduleCount: { type: integer }
        createdAt: { type: integer, format: int64 }
    RenderedReport:
      type: object
      description: >-
        Columns and rows of strings rather than a typed shape per report, so one CSV
        writer serves every report.
      properties:
        templateId: { type: string }
        reportType: { type: string }
        periodLabel: { type: string }
        periodFrom: { type: integer, format: int64 }
        periodUntil: { type: integer, format: int64 }
        columns: { type: array, items: { type: string } }
        rows:
          type: array
          items: { type: array, items: { type: string } }
        totals: { type: object, additionalProperties: { type: string } }
    ReportScheduleUpsertRequest:
      type: object
      required: [templateId, cadence]
      properties:
        templateId: { type: string }
        cadence: { type: string, enum: [DAILY, WEEKLY, MONTHLY] }
        hourOfDay: { type: integer, minimum: 0, maximum: 23, default: 7, description: SAST. }
        dayOfWeek: { type: integer, minimum: 1, maximum: 7, nullable: true, description: 1=Monday. WEEKLY only. }
        dayOfMonth:
          type: integer
          minimum: 1
          maximum: 28
          nullable: true
          description: Capped at 28 so a monthly report cannot silently skip February.
        recipients:
          type: array
          items: { type: string }
          description: Required and non-empty — a schedule with nobody to send to would succeed and deliver nothing.
        format: { type: string, enum: [CSV, HTML], default: CSV }
        active: { type: boolean, default: true }
    ReportSchedule:
      type: object
      properties:
        id: { type: string }
        templateId: { type: string }
        templateName: { type: string, nullable: true }
        cadence: { type: string, enum: [DAILY, WEEKLY, MONTHLY] }
        hourOfDay: { type: integer }
        dayOfWeek: { type: integer, nullable: true }
        dayOfMonth: { type: integer, nullable: true }
        recipients: { type: array, items: { type: string } }
        format: { type: string }
        active: { type: boolean }
        lastRunAt: { type: integer, format: int64, nullable: true }
        lastStatus: { type: string, nullable: true }
        lastPeriodKey: { type: string, nullable: true }
    ReportDeliveryOutcome:
      type: object
      properties:
        scheduleId: { type: string }
        templateName: { type: string, nullable: true }
        periodKey: { type: string, example: "2026-08-04" }
        status:
          type: string
          enum: [SENT, FAILED, SKIPPED_EMPTY, NOT_CONFIGURED, ALREADY_SENT, WITHHELD, UNSUPPORTED]
          description: >-
            WITHHELD means nothing went: whoever made the schedule may no longer send it, or none of its
            recipients is still an active person of the business holding the report's permission. UNSUPPORTED
            means the server could not produce that report for that schedule (see `error`).
            SKIPPED_EMPTY is a real outcome, not an error — nobody wants an empty
            spreadsheet every Monday, but they do want to know the schedule ran.
            ALREADY_SENT is reported rather than omitted, because "ran, nothing to do"
            and "did not run" are different answers.
        rowCount: { type: integer }
        recipients:
          type: array
          items: { type: string }
          description: >-
            Who it was sent to — not the schedule's list. A recipient left out at send time (no longer an active person of the
            business holding the report's permission) is not here, and a WITHHELD delivery has none; `error` says how many were left out.
        error: { type: string, nullable: true }
    ReportDelivery:
      type: object
      properties:
        scheduleId: { type: string }
        templateName: { type: string, nullable: true }
        periodKey: { type: string }
        periodFrom: { type: integer, format: int64, description: The window actually reported on, stored so a delivery can be explained months later. }
        periodUntil: { type: integer, format: int64 }
        status: { type: string }
        rowCount: { type: integer }
        recipients: { type: array, items: { type: string }, description: Who it was sent to (a recipient left out at send time is not here). }
        error: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
    LabourStaffLine:
      type: object
      properties:
        staffId: { type: string }
        staffName: { type: string, nullable: true }
        role: { type: string, nullable: true }
        minutes: { type: integer, format: int64, description: Paid minutes, clipped to the window and net of a pro-rated break. }
        hourlyRateCents: { type: integer, format: int64, description: The rate their shifts were actually costed at, not today's. }
        costCents: { type: integer, format: int64 }
    LabourReport:
      type: object
      properties:
        periodLabel: { type: string }
        periodFrom: { type: integer, format: int64 }
        periodUntil: { type: integer, format: int64 }
        salesCents: { type: integer, format: int64 }
        labourCostCents: { type: integer, format: int64 }
        labourPctOfSalesBp:
          type: integer
          format: int64
          description: Basis points; 2850 = 28.50%. Zero when there were no sales — never infinity.
        paidMinutes: { type: integer, format: int64 }
        salesPerHourCents: { type: integer, format: int64, description: Revenue per paid hour — what a roster is judged on. }
        verdict: { type: string, enum: ["Tight", "Healthy", "Heavy", "Overstaffed for the trade", "No sales in this period"] }
        overBudget: { type: boolean, description: "Labour ran above the healthy band (LabourCost)." }
        staff: { type: array, items: { $ref: "#/components/schemas/LabourStaffLine" } }
    PayrollFile:
      type: object
      properties:
        periodLabel: { type: string }
        periodFrom: { type: integer, format: int64 }
        periodUntil: { type: integer, format: int64 }
        locationId: { type: string, nullable: true, description: "Null: every location of the business." }
        people:
          type: array
          items:
            type: object
            properties:
              staffId: { type: string }
              staffName: { type: string }
              role: { type: string }
              paidMinutes: { type: integer, format: int64, description: Shifts in the period less their breaks, and duty time no drawer covers. }
              hourlyRateCents: { type: integer, format: int64, description: The rate the person's time was costed at; 0 where they worked none. }
              wagesCents: { type: integer, format: int64, description: The labour report's cost of those minutes. }
              tipsCents: { type: integer, format: int64, description: What the tips report says they are owed. }
              commissionCents: { type: integer, format: int64, nullable: true, description: "Commission written in the period, net of reversals; absent with `locationId` (commission records no location)." }
              commissionOwedCents: { type: integer, format: int64, nullable: true, description: "Of it, what is not yet marked paid; absent with `locationId`." }
        notes: { type: array, items: { type: string }, description: "What the columns mean; tips held back that the file cannot assign to a person; the tip policy's own notes; commission left out of a one-location file; every drawer or duty stint not clocked out." }
    DimensionRow:
      type: object
      properties:
        key: { type: string, description: "The raw grouping value; `__unset__` where nothing is recorded." }
        label: { type: string, description: "\"Not recorded\" for the unset bucket." }
        productCount: { type: integer }
        unitsSold: { type: integer, format: int64 }
        revenueCents: { type: integer, format: int64 }
        costCents: { type: integer, format: int64 }
        marginCents: { type: integer, format: int64 }
        marginPctBp: { type: integer, format: int64 }
    DimensionReport:
      type: object
      properties:
        dimension: { type: string, enum: [brand, supplier, category] }
        periodLabel: { type: string }
        periodFrom: { type: integer, format: int64 }
        periodUntil: { type: integer, format: int64 }
        totalRevenueCents: { type: integer, format: int64, description: Equals the sales report's total for the same window — the unset bucket is why. }
        totalMarginCents: { type: integer, format: int64 }
        rows: { type: array, items: { $ref: "#/components/schemas/DimensionRow" } }
    DrilldownLine:
      type: object
      properties:
        transactionId: { type: string }
        transactionNumber: { type: string }
        closedAt: { type: integer, format: int64, nullable: true }
        productId: { type: string }
        productName: { type: string, description: The name as it was on the receipt. }
        quantity: { type: integer, format: int64 }
        lineTotalCents: { type: integer, format: int64, description: Zero for a comped line — it happened, but was given away. }
        comped: { type: boolean }
    CommissionSchemeUpsertRequest:
      type: object
      properties:
        name: { type: string }
        basis:
          type: string
          enum: [LINE_TOTAL, LINE_MARGIN]
          default: LINE_TOTAL
          description: >-
            LINE_MARGIN pays on (charged − cost) and earns nothing at or below cost.
            It needs product cost to be real, which is why it is not the default.
        rateBp:
          type: integer
          minimum: 1
          maximum: 10000
          description: Basis points; 500 = 5%. Capped so a percent/bp mix-up is caught.
        scopeType: { type: string, enum: [ALL, CATEGORY, PRODUCT], default: ALL }
        scopeIds: { type: array, items: { type: string }, nullable: true }
        role: { type: string, nullable: true, description: Null pays every role. A staff member with no role does NOT earn a role-restricted scheme. }
        staffIds: { type: array, items: { type: string }, nullable: true, description: Empty pays everyone. }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        active: { type: boolean, nullable: true }
    CommissionScheme:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        basis: { type: string, enum: [LINE_TOTAL, LINE_MARGIN] }
        rateBp: { type: integer }
        scopeType: { type: string, enum: [ALL, CATEGORY, PRODUCT] }
        scopeIds: { type: array, items: { type: string } }
        role: { type: string, nullable: true }
        staffIds: { type: array, items: { type: string } }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        active: { type: boolean }
        earnedEntries: { type: integer, description: Why it may not be deletable. }
    StaffCommission:
      type: object
      properties:
        staffId: { type: string }
        staffName: { type: string, nullable: true }
        periodKey: { type: string, example: "2026-08" }
        entryCount: { type: integer }
        accruedCents: { type: integer, format: int64, description: Net of reversals. }
        paidCents: { type: integer, format: int64 }
        owedCents: { type: integer, format: int64, description: Never negative. }
    CommissionEntry:
      type: object
      description: "Self-explaining: baseCents × rateBp ÷ 10000 reproduces amountCents."
      properties:
        id: { type: string }
        transactionId: { type: string }
        lineId: { type: string, nullable: true }
        productId: { type: string, nullable: true }
        baseCents:
          type: integer
          format: int64
          description: >-
            What the rate was applied to — the line total net of its own discount and
            its share of any bill discount, or the margin for a LINE_MARGIN scheme.
        rateBp: { type: integer, description: Frozen at accrual, so a later rate change cannot restate this. }
        amountCents: { type: integer, format: int64, description: Negative for a refund reversal. }
        status: { type: string, enum: [ACCRUED, PAID] }
        reversesId: { type: string, nullable: true, description: Present on a reversal; identifies it structurally. }
        createdAt: { type: integer, format: int64 }
    PayCommissionRequest:
      type: object
      properties:
        period: { type: string, nullable: true, description: Defaults to the current month in SAST. }
        reference: { type: string, nullable: true, description: e.g. an EFT reference. }
    PayCommissionResult:
      type: object
      properties:
        staffId: { type: string }
        periodKey: { type: string }
        entriesMarkedPaid: { type: integer, description: Zero on a second attempt. }
        amountPaidCents: { type: integer, format: int64 }
    SegmentRule:
      type: object
      description: >-
        Criteria, ANDed. Every field is nullable and a null field is not tested, so
        an empty object matches every customer — which is the correct reading of
        "no criteria" and how a whole-list campaign is expressed. There is no OR:
        that is two segments.
      properties:
        tiers: { type: array, items: { type: string }, nullable: true }
        minSpendCents: { type: integer, format: int64, nullable: true }
        maxSpendCents: { type: integer, format: int64, nullable: true }
        minVisits: { type: integer, nullable: true }
        maxVisits: { type: integer, nullable: true, description: "0 selects customers who have never visited." }
        minPoints: { type: integer, format: int64, nullable: true }
        lapsedDays:
          type: integer
          nullable: true
          description: >-
            Has visited, but not in this many days. A customer who has NEVER visited
            deliberately does not match — treating a null last-visit as infinitely
            lapsed would send "we miss you" to someone who has never been in.
        activeWithinDays: { type: integer, nullable: true }
        tagsAny:
          type: array
          items: { type: string }
          nullable: true
          description: Case-insensitive. An empty list is treated as no criterion, not as "matches nothing".
        tagsAll: { type: array, items: { type: string }, nullable: true }
        birthdayMonth: { type: integer, minimum: 1, maximum: 12, nullable: true }
        hasPhone: { type: boolean, nullable: true }
        hasEmail: { type: boolean, nullable: true }
        optedInWhatsapp:
          type: boolean
          nullable: true
          description: >-
            Consent as a *selection* criterion. Distinct from the consent check at
            send time, which applies whether or not the segment mentions it — a
            segment cannot opt someone in by omitting this.
        optedInEmail: { type: boolean, nullable: true }
    SegmentUpsertRequest:
      type: object
      properties:
        name: { type: string }
        description: "{ type: string, nullable: true }"
        rule: { $ref: "#/components/schemas/SegmentRule" }
        ruleProvided:
          type: boolean
          default: true
          description: >-
            False updates without touching the criteria. Needed because the default
            rule value is indistinguishable from an omitted one, so a rename would
            otherwise silently reset the segment to "everyone".
        active: { type: boolean, nullable: true }
    SegmentPreviewRequest:
      type: object
      properties:
        rule: { $ref: "#/components/schemas/SegmentRule" }
    SegmentMember:
      type: object
      properties:
        id: { type: string }
        name: { type: string, nullable: true }
        tier: { type: string }
        visitCount: { type: integer }
        totalSpentCents: { type: integer, format: int64 }
        lastVisitAt: { type: integer, format: int64, nullable: true }
    SegmentPreview:
      type: object
      properties:
        description: "{ type: string, description: The rule in plain English. }"
        size: { type: integer }
        reachableWhatsapp: { type: integer, description: How many can actually be messaged — the number that matters. }
        reachableEmail: { type: integer }
        sample: { type: array, items: { $ref: "#/components/schemas/SegmentMember" } }
    Segment:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        description: "{ type: string, nullable: true }"
        ruleDescription: { type: string, description: So nobody has to read the JSON. }
        rule: { $ref: "#/components/schemas/SegmentRule" }
        size: { type: integer, description: Who matches right now — membership is derived, not stored. }
        reachableWhatsapp: { type: integer }
        reachableEmail: { type: integer }
        active: { type: boolean }
        createdAt: { type: integer, format: int64 }
    CampaignUpsertRequest:
      type: object
      properties:
        name: { type: string }
        channel: { type: string, enum: [WHATSAPP, EMAIL] }
        segmentId: { type: string, nullable: true, description: Null means an ad-hoc audience given at send time. }
        subject: { type: string, nullable: true, description: Email only. }
        body:
          type: string
          description: >-
            Template using {name}, {firstName}, {tier}, {points}, {spend}, {credit},
            {venue}, {link}. Unknown tokens are rejected at save time.
        scheduledAt: { type: integer, format: int64, nullable: true }
    SendCampaignRequest:
      type: object
      properties:
        customerIds:
          type: array
          items: { type: string }
          nullable: true
          description: >-
            Overrides the segment. Ids are intersected with the tenant's own
            customers rather than trusted, and a repeated id is messaged once.
    SendCampaignResult:
      type: object
      description: "sentCount + failedCount + suppressedCount always equals audienceCount."
      properties:
        campaignId: { type: string }
        audienceCount: { type: integer }
        sentCount: { type: integer }
        failedCount: { type: integer }
        suppressedCount: { type: integer }
        dryRun:
          type: boolean
          description: >-
            True when the channel has no credentials, so nothing was delivered.
            Reported explicitly rather than counted as success.
    Campaign:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        channel: { type: string, enum: [WHATSAPP, EMAIL] }
        segmentId: { type: string, nullable: true }
        segmentName: { type: string, nullable: true }
        subject: { type: string, nullable: true }
        body: { type: string }
        status: { type: string, enum: [DRAFT, SCHEDULED, SENDING, SENT, CANCELLED, FAILED] }
        scheduledAt: { type: integer, format: int64, nullable: true }
        startedAt: { type: integer, format: int64, nullable: true }
        finishedAt: { type: integer, format: int64, nullable: true }
        audienceCount: { type: integer }
        sentCount: { type: integer }
        failedCount: { type: integer }
        suppressedCount: { type: integer }
        createdAt: { type: integer, format: int64 }
    CampaignRecipient:
      type: object
      properties:
        customerId: { type: string }
        customerName: { type: string, nullable: true }
        channelAddress:
          type: string
          nullable: true
          description: The address as it was at send time — never read live.
        status: { type: string, enum: [PENDING, SENT, FAILED, SUPPRESSED] }
        suppressReason:
          type: string
          nullable: true
          enum: [NO_CONSENT, NO_ADDRESS, DUPLICATE, NOT_CONFIGURED]
          description: >-
            Names whose job the fix is: marketing, data entry, nothing, deployment.
            Kept separate from `error`, which is something that went wrong.
        error: { type: string, nullable: true }
        sentAt: { type: integer, format: int64, nullable: true }
    LifecycleUpsertRequest:
      type: object
      required: [triggerType, channel, body]
      properties:
        triggerType: { type: string, enum: [BIRTHDAY, WIN_BACK, WELCOME, REVIEW_REQUEST] }
        channel: { type: string, enum: [WHATSAPP, EMAIL] }
        subject: { type: string, nullable: true }
        body: { type: string, description: "The message. For REVIEW_REQUEST, which Ruva words itself, send an empty string: it is ignored." }
        days:
          type: integer
          default: 0
          description: >-
            WIN_BACK: days of silence before it fires (must be at least 1).
            WELCOME: days to wait after the visit, so the message does not arrive
            while the guest is still at the table. Ignored by BIRTHDAY and by
            REVIEW_REQUEST (which waits `delayHours`).
        delayHours:
          type: integer
          nullable: true
          minimum: 1
          maximum: 48
          description: "REVIEW_REQUEST only (`invalid_delay_hours`; any other trigger answers `review_request_only`). Hours to wait after the order closes; null is 3."
        alsoWhatsapp:
          type: boolean
          default: false
          description: "REVIEW_REQUEST only. Also send through the one `review_request` WhatsApp utility template (metered, only to a guest who agreed to WhatsApp, only where the location has WhatsApp on)."
        active: { type: boolean, default: true }
    LifecycleAutomation:
      type: object
      properties:
        id: { type: string }
        triggerType: { type: string, enum: [BIRTHDAY, WIN_BACK, WELCOME, REVIEW_REQUEST] }
        channel: { type: string, enum: [WHATSAPP, EMAIL] }
        subject: { type: string, nullable: true }
        body: { type: string }
        days: { type: integer }
        delayHours: { type: integer, nullable: true }
        alsoWhatsapp: { type: boolean }
        active: { type: boolean }
        lastRunAt: { type: integer, format: int64, nullable: true }
        sentTotal: { type: integer }
    LifecycleRunResult:
      type: object
      properties:
        triggerType: { type: string }
        considered: { type: integer }
        sent: { type: integer }
        skippedAlreadySent:
          type: integer
          description: Already sent for this occurrence — the dedupe log doing its job, not an error.
        suppressed: { type: integer }
        failed: { type: integer }
    CourierAccountView:
      type: object
      description: A venue's connection to one courier (T-37.9). Has no field for a secret.
      required: [provider, label, state]
      properties:
        provider: { type: string, enum: [UBER_DIRECT] }
        label: { type: string }
        state: { type: string, enum: [NOT_CONNECTED, VERIFYING, CONNECTED, REJECTED] }
        enabled: { type: boolean, default: true }
        signingKeySet: { type: boolean, description: "A webhook signing key is held; without one the poll alone follows the driver." }
        webhookUrl: { type: string, nullable: true, description: "The address to register with the courier for driver updates." }
        rejectedReason: { type: string, nullable: true, description: "The courier's own words when it refused the keys." }
        customerId: { type: string, nullable: true }
    CourierConnect:
      type: object
      required: [customerId, clientId, clientSecret]
      properties:
        customerId: { type: string }
        clientId: { type: string, writeOnly: true }
        clientSecret: { type: string, writeOnly: true, description: "Never returned." }
        signingKey: { type: string, writeOnly: true, nullable: true, description: "The key the courier signs its webhook with. Never returned." }
    CourierTestResult:
      type: object
      required: [account]
      properties:
        account: { $ref: "#/components/schemas/CourierAccountView" }
        unreachable: { type: string, nullable: true }
    CourierJobView:
      type: object
      required: [id, orderId, status, courierLabel]
      properties:
        id: { type: string }
        orderId: { type: string }
        status: { type: string, enum: [READY, BOOKING, FAILED, PENDING, PICKUP, PICKED_UP, DROPOFF, DELIVERED, CANCELLED, RETURNED] }
        courierLabel: { type: string }
        trackingUrl: { type: string, nullable: true, description: "https on the courier's own host, or null." }
        needsAttention: { type: boolean }
        retrying: { type: boolean, description: "A failed booking is still being retried; false means it waits for a person." }
        problem: { type: string, nullable: true, description: "The courier's own words, scrubbed." }
        unclear: { type: boolean, description: "The last booking went unanswered and may exist at the courier: check its dashboard first." }
        mayBookAgain: { type: boolean, description: "Book again is offered: held for a person, not cancelled, and within 30 minutes of an unanswered booking." }
        mayDismiss: { type: boolean, description: "A cancel needing a person may be marked handled (POST .../dismiss)." }
        courierFeeCents: { type: integer, format: int64, nullable: true, description: "What the courier charges the venue; never the guest's price." }
        updatedAt: { type: integer, format: int64 }
        directions: { type: string, nullable: true, maxLength: 200, description: "The guest's directions for the driver, as the courier was sent them (T-37.14); null when they left none." }
        pickupNumber: { type: string, nullable: true, description: "The order's pickup number, the reference the courier is given: which delivery this job is." }
    CourierJobsResponse:
      type: object
      properties:
        jobs: { type: array, items: { $ref: "#/components/schemas/CourierJobView" } }
    CourierRetryAck:
      type: object
      required: [queued]
      properties:
        queued: { type: boolean }
    CourierDismissAck:
      type: object
      required: [dismissed]
      properties:
        dismissed: { type: boolean }
    CourierWebhookAck:
      type: object
      required: [applied]
      properties:
        applied: { type: boolean }
    QrCourierStatus:
      type: object
      description: Where a delivery's driver is, on a guest's round (T-37.9).
      required: [stage]
      properties:
        stage: { type: string, enum: [FINDING, COLLECTING, ON_THE_WAY, DELIVERED, REARRANGING], description: "REARRANGING: the courier dropped the delivery and the venue is arranging another." }
        trackingUrl: { type: string, nullable: true, description: "https on the courier's own host, never otherwise; null once delivered." }
    PaymentRailView:
      type: object
      description: A venue's own payment account (T-2.1). Has no field for a secret.
      required: [provider, state]
      properties:
        provider: { type: string, enum: [YOCO, PAYFAST, SNAPSCAN] }
        state: { type: string, enum: [NOT_CONNECTED, VERIFYING, CONNECTED, REJECTED] }
        publicKey: { type: string, nullable: true, description: "Yoco's public key, PayFast's merchant key — both seen by a guest's browser." }
        merchantCode: { type: string, nullable: true, description: "PayFast's merchant id, SnapScan's SnapCode." }
        testMode: { type: boolean }
        verifiedAt: { type: integer, format: int64, nullable: true }
        rejectedReason: { type: string, nullable: true, description: "The provider's own words when it refused the key." }
        webhookRegistered: { type: boolean }
        webhookConfirmed: { type: boolean, description: "SnapScan: a payment notice signed with the business's own webhook key has arrived since it was saved." }
        liveForGuests: { type: boolean, description: "Offered to guests: CONNECTED, a provider Ruva offers (Yoco and PayFast; SnapScan is not offered right now, so it is always false), and its payment confirmations are verified per venue — each checked with the business's own secret — and the business has not switched it off (`enabled`)." }
        enabled: { type: boolean, description: "The business offers this provider to its guests (Settings → Payments' switch). Off, no new guest payment opens on it; its keys are kept and a payment already taken still settles and refunds." }
    PaymentRailConnect:
      type: object
      required: [secret]
      properties:
        secret: { type: string, writeOnly: true, description: "Yoco's secret key, PayFast's passphrase, SnapScan's API key. Never returned." }
        publicKey: { type: string, nullable: true }
        merchantCode: { type: string, nullable: true }
        webhookSecret: { type: string, writeOnly: true, nullable: true, description: "SnapScan's webhook authentication key." }
        testMode: { type: boolean, description: "PayFast's sandbox." }
        currentPassword: { type: string, writeOnly: true, nullable: true, description: "The signed-in person's own Ruva password, checked before anything is saved (403 `reauth_required` when absent or wrong). Never stored or logged." }
    PaymentRailPrefer:
      type: object
      properties:
        currentPassword: { type: string, writeOnly: true, nullable: true, description: "The signed-in person's own Ruva password, checked before anything changes (403 `reauth_required` when absent or wrong). Never stored or logged." }
    PaymentRailSwitch:
      type: object
      required: [enabled]
      properties:
        enabled: { type: boolean, description: "Whether guests are offered this provider. No key travels either way." }
    PaymentRailTestResult:
      type: object
      required: [rail]
      properties:
        rail: { $ref: "#/components/schemas/PaymentRailView" }
        unreachable: { type: string, nullable: true }
    CashierDiscountLimit:
      type: object
      required: [percent]
      properties:
        percent: { type: integer, minimum: 0, maximum: 100 }
    RetentionDto:
      type: object
      required: [customerRetentionMonths]
      properties:
        customerRetentionMonths: { type: integer, minimum: 1, maximum: 120 }
    DeletionStatusDto:
      type: object
      properties:
        businessName: { type: string }
        requestedAt: { type: integer, format: int64, nullable: true }
        requestedBy: { type: string, nullable: true }
        dueAt: { type: integer, format: int64, nullable: true, description: "When everything is deleted, unless cancelled." }
        coolingOffDays: { type: integer }
    DeletionRequest:
      type: object
      required: [confirmName]
      properties:
        confirmName: { type: string, description: "The business name, typed back." }
    ConsentRequest:
      type: object
      required: [channel, optedIn]
      properties:
        channel: { type: string, enum: [WHATSAPP, EMAIL] }
        optedIn: { type: boolean }
        source:
          type: string
          default: BACK_OFFICE
          enum: [TILL, BACK_OFFICE, QR, IMPORT, UNSUBSCRIBE_LINK]
        note: { type: string, nullable: true, description: e.g. the words the customer used. }
    ConsentEvent:
      type: object
      properties:
        channel: { type: string }
        optedIn: { type: boolean }
        source: { type: string }
        note: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
    ContactHistoryEntry:
      type: object
      properties:
        campaignId: { type: string }
        campaignName: { type: string }
        channel: { type: string }
        status: { type: string }
        suppressReason: { type: string, nullable: true }
        sentAt: { type: integer, format: int64, nullable: true }
        createdAt: { type: integer, format: int64 }
    Quote:
      type: object
      description: >-
        A priced offer. Reserves no stock and holds no money — `depositDueCents` is a
        policy figure printed on the document, not funds received.
      properties:
        id: { type: string }
        reference: { type: string, example: "QT-20260804-000001" }
        locationId: { type: string }
        locationName: { type: string, nullable: true }
        customerId: { type: string, nullable: true }
        customerName: { type: string, nullable: true }
        contactName: { type: string, nullable: true, description: "For a phone enquiry with no customer record yet." }
        contactPhone: { type: string, nullable: true }
        contactEmail: { type: string, nullable: true }
        title: { type: string, nullable: true }
        status:
          type: string
          description: The stored status. EXPIRED is never stored.
          enum: [DRAFT, SENT, ACCEPTED, DECLINED, CONVERTED, CANCELLED]
        displayStatus:
          type: string
          description: "[status], except a SENT quote past its date reads EXPIRED."
          enum: [DRAFT, SENT, EXPIRED, ACCEPTED, DECLINED, CONVERTED, CANCELLED]
        expired: { type: boolean }
        validUntil:
          type: integer
          format: int64
          nullable: true
          description: >-
            How long the PRICE stands, epoch millis. Null never expires — an open-ended
            standing price for a corporate account is legitimate. Inclusive of its final
            instant.
        eventAt:
          type: integer
          format: int64
          nullable: true
          description: When the function happens — unrelated to validUntil, which is price validity.
        subtotalCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        vatCents:
          type: integer
          format: int64
          description: The 15/115 portion already inside totalCents, not an addition to it.
        totalCents: { type: integer, format: int64 }
        depositDueCents: { type: integer, format: int64, description: What the quote asks for up front. Printed, not held. }
        note: { type: string, nullable: true }
        terms: { type: string, nullable: true }
        convertedOrderId: { type: string, nullable: true }
        convertedAt: { type: integer, format: int64, nullable: true }
        sentAt: { type: integer, format: int64, nullable: true }
        acceptedAt: { type: integer, format: int64, nullable: true }
        declinedAt: { type: integer, format: int64, nullable: true }
        declineReason: { type: string, nullable: true }
        cancelledAt: { type: integer, format: int64, nullable: true }
        createdAt: { type: integer, format: int64 }
        lines: { type: array, items: { $ref: "#/components/schemas/QuoteLine" } }
    QuoteLine:
      type: object
      properties:
        id: { type: string }
        productId:
          type: string
          nullable: true
          description: Null = a free-text line (labour, venue hire, delivery) carrying no stock or cost.
        variantId: { type: string, nullable: true }
        description:
          type: string
          description: Always present — the customer reads this, and products get renamed.
        quantity: { type: integer, format: int64 }
        unitPriceCents:
          type: integer
          format: int64
          description: Frozen when the line was written, VAT-inclusive.
        discountCents: { type: integer, format: int64 }
        vatType:
          type: string
          description: Snapshotted from the product, so a VAT reclassification cannot restate a sent quote.
          enum: [STANDARD, ZERO, EXEMPT]
        lineTotalCents: { type: integer, format: int64 }
        note: { type: string, nullable: true }
        sortOrder: { type: integer }
    QuoteLineRequest:
      type: object
      required: [description]
      properties:
        productId: { type: string, nullable: true, description: Omit for a free-text line. }
        variantId: { type: string, nullable: true, description: Requires productId. }
        description: "{ type: string }"
        quantity: { type: integer, format: int64, default: 1 }
        unitPriceCents:
          type: integer
          format: int64
          nullable: true
          description: >-
            Omit to price from the catalogue at the quote's location and freeze the
            result. A value overrides that — a negotiated number is the point of quoting.
        discountCents: { type: integer, format: int64, default: 0 }
        vatType: { type: string, nullable: true, enum: [STANDARD, ZERO, EXEMPT] }
        note: { type: string, nullable: true }
    QuoteCreateRequest:
      type: object
      required: [locationId, lines]
      properties:
        locationId: { type: string }
        customerId: { type: string, nullable: true }
        contactName: { type: string, nullable: true }
        contactPhone: { type: string, nullable: true }
        contactEmail: { type: string, nullable: true }
        title: { type: string, nullable: true }
        validUntil:
          type: integer
          format: int64
          nullable: true
          description: >-
            Epoch ms the price holds to — at most the end of the 30th South African day after today (T-2.56, D-112);
            later is refused with `quote_valid_too_long`. Omitted stores exactly that last instant: a quote never holds
            its price open-ended.
        eventAt: { type: integer, format: int64, nullable: true }
        note: { type: string, nullable: true }
        terms: { type: string, nullable: true }
        discountCents: { type: integer, format: int64, default: 0 }
        depositPctBp:
          type: integer
          format: int64
          default: 0
          description: "Deposit policy in basis points; 3000 = 30%. Rounded up to the cent."
        byStaffId: { type: string, nullable: true }
        approverStaffId:
          type: string
          nullable: true
          description: >-
            The manager who stands for a price of the quote's own or a discount when the signed-in caller is not a
            manager. Must be a live manager of this business (`quote_needs_manager` otherwise).
        lines: { type: array, items: { $ref: "#/components/schemas/QuoteLineRequest" } }
    QuoteLinesRequest:
      type: object
      required: [lines]
      properties:
        lines: { type: array, items: { $ref: "#/components/schemas/QuoteLineRequest" } }
        discountCents: { type: integer, format: int64, nullable: true, description: Omit to keep the existing header discount. }
        depositPctBp: { type: integer, format: int64, default: 0 }
        approverStaffId:
          type: string
          nullable: true
          description: >-
            The manager who stands for a price of the quote's own or a discount when the signed-in caller is not a
            manager. Must be a live manager of this business (`quote_needs_manager` otherwise).
    QuoteTotals:
      type: object
      properties:
        subtotalCents: { type: integer, format: int64 }
        discountCents: { type: integer, format: int64 }
        vatCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        depositDueCents: { type: integer, format: int64 }
    QuoteConvertRequest:
      type: object
      properties:
        orderType: { type: string, default: TAKEAWAY }
        tableId: { type: string, nullable: true }
        covers: { type: integer, nullable: true }
        byStaffId: { type: string, nullable: true }
        approverStaffId:
          type: string
          nullable: true
          description: >-
            The manager who stands for a quote carrying a price of its own or a discount that no manager approved when
            it was written, when the signed-in caller is not a manager. Must be a live manager of this business.
    QuoteConverted:
      type: object
      properties:
        quoteId: { type: string }
        orderId: { type: string }
        orderNumber: { type: string, example: "POS-20260804-000011" }
    SpecialOrder:
      type: object
      description: >-
        Goods brought in for one named customer. The deposit is not a field here — it is
        a CAPTURED payment on `orderId`, surfaced as `depositPaidCents`.
      properties:
        id: { type: string }
        reference: { type: string, example: "SO-20260804-000001" }
        locationId: { type: string }
        locationName: { type: string, nullable: true }
        customerId: { type: string, description: Required — an order held for nobody is just stock. }
        customerName: { type: string, nullable: true }
        customerPhone: { type: string, nullable: true }
        description: "{ type: string, description: What was asked for, in the customer's words. }"
        productId: { type: string, nullable: true, description: Often null — that is usually why it is special. }
        variantId: { type: string, nullable: true }
        supplierId: { type: string, nullable: true }
        supplierName: { type: string, nullable: true }
        quantityUnits: { type: integer, format: int64 }
        unitPriceCents:
          type: integer
          format: int64
          nullable: true
          description: Null = not yet priced, which differs from priced at zero (a warranty replacement).
        totalCents: { type: integer, format: int64, nullable: true }
        status:
          type: string
          enum: [REQUESTED, ORDERED, READY, COLLECTED, CANCELLED]
        orderId: { type: string, nullable: true, description: The sale carrying the deposit. Null until priced. }
        purchaseOrderId: { type: string, nullable: true }
        depositPaidCents: { type: integer, format: int64 }
        balanceDueCents: { type: integer, format: int64, nullable: true }
        expectedAt: { type: integer, format: int64, nullable: true }
        orderedAt: { type: integer, format: int64, nullable: true }
        readyAt: { type: integer, format: int64, nullable: true }
        notifiedAt:
          type: integer
          format: int64
          nullable: true
          description: Whether the customer was told — a fact about a message, not a stage of the goods.
        collectedAt: { type: integer, format: int64, nullable: true }
        cancelledAt: { type: integer, format: int64, nullable: true }
        cancelReason: { type: string, nullable: true }
        daysWaiting: { type: integer, format: int64, description: Whole days on the shelf. }
        note: { type: string, nullable: true }
        createdAt: { type: integer, format: int64 }
    SpecialOrderCreateRequest:
      type: object
      required: [locationId, customerId, description]
      properties:
        locationId: { type: string }
        customerId: { type: string }
        description: "{ type: string }"
        productId: { type: string, nullable: true }
        variantId: { type: string, nullable: true }
        supplierId: { type: string, nullable: true }
        quantityUnits: { type: integer, format: int64, default: 1 }
        unitPriceCents: { type: integer, format: int64, nullable: true }
        expectedAt: { type: integer, format: int64, nullable: true }
        note: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
    SpecialOrderPriceRequest:
      type: object
      properties:
        unitPriceCents:
          type: integer
          format: int64
          nullable: true
          description: Omit for a catalogue item to price it at the order's location.
        productId: { type: string, nullable: true, description: Attach a catalogue item to a request that started as text. }
        variantId: { type: string, nullable: true }
        quantityUnits: { type: integer, format: int64, nullable: true }
        depositPctBp: { type: integer, format: int64, default: 0, description: Only suggests a figure back; nothing is collected. }
        byStaffId: { type: string, nullable: true }
    SpecialOrderPriced:
      type: object
      properties:
        id: { type: string }
        orderId: { type: string }
        unitPriceCents: { type: integer, format: int64 }
        totalCents: { type: integer, format: int64 }
        suggestedDepositCents: { type: integer, format: int64 }
    SpecialOrderDepositRequest:
      type: object
      required: [amountCents]
      properties:
        method: { type: string, default: CASH }
        amountCents: { type: integer, format: int64 }
        tenderedCents: { type: integer, format: int64, nullable: true, description: Cash tendered, so change can be worked out. }
        providerReference: { type: string, nullable: true }
        last4: { type: string, nullable: true }
        byStaffId: { type: string, nullable: true }
    SpecialOrderMoney:
      type: object
      properties:
        id: { type: string }
        orderId: { type: string }
        totalCents: { type: integer, format: int64 }
        paidCents: { type: integer, format: int64 }
        balanceDueCents: { type: integer, format: int64 }
    SpecialOrderOrderedRequest:
      type: object
      properties:
        purchaseOrderId: { type: string, nullable: true }
        supplierId: { type: string, nullable: true }
        expectedAt: { type: integer, format: int64, nullable: true }
    SpecialOrderCollectRequest:
      type: object
      properties:
        payments:
          type: array
          description: Only needs to cover the balance — the deposit is already captured.
          items: { $ref: "#/components/schemas/PaymentLeg" }
        byStaffId: { type: string, nullable: true }
        ageCheck: { type: object, nullable: true, description: "T-37.1 - the age check made at collection: required when the order is for an age-restricted product (`409 age_check_required` without it). Recorded as TILL and the signed-in person.", properties: { surface: { type: string, enum: [TILL, QR, KIOSK, ONLINE_STORE] }, staffId: { type: string, nullable: true }, atMs: { type: integer, format: int64, nullable: true } }, required: [surface] }
    SpecialOrderCollected:
      type: object
      properties:
        id: { type: string }
        orderId: { type: string }
        totalCents: { type: integer, format: int64, description: The full price, not the balance. }
        paidCents: { type: integer, format: int64 }
    SpecialOrderCancelled:
      type: object
      properties:
        id: { type: string }
        depositToRefundCents:
          type: integer
          format: int64
          description: Money already taken that still needs returning. Reported, never dropped.
    PriceList:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        description: "{ type: string, nullable: true }"
        upliftBp: { type: integer }
        validFrom: { type: integer, format: int64, nullable: true }
        validUntil: { type: integer, format: int64, nullable: true }
        active: { type: boolean }
        itemCount: { type: integer, description: "SKUs with an explicit price; the rest follow upliftBp." }
        locations: { type: array, items: { $ref: "#/components/schemas/AssignedLocation" } }
      required: [id, name, upliftBp, active, itemCount]
    PriceListItemUpsert:
      type: object
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true, description: "Null prices the product for every variant; the variant delta still applies." }
        priceCents: { type: integer, format: int64, description: "Absolute, never a delta — a delta would mean editing a base price silently moves every location." }
      required: [productId, priceCents]
    PriceListItemsRequest:
      type: object
      properties:
        items: { type: array, items: { $ref: "#/components/schemas/PriceListItemUpsert" } }
      required: [items]
    PriceListItem:
      type: object
      properties:
        id: { type: string }
        productId: { type: string }
        productName: { type: string }
        variantId: { type: string, nullable: true }
        priceCents: { type: integer, format: int64 }
        basePriceCents: { type: integer, format: int64, description: "Carried so a UI can show what the list changes." }
      required: [id, productId, productName, priceCents, basePriceCents]
    AssignRequest:
      type: object
      properties:
        locationIds: { type: array, items: { type: string } }
      required: [locationIds]
    PricePreview:
      type: object
      description: |
        Why a price is what it is. The layers apply in order: base → price list →
        rules, and a rule discounts the *location's* price rather than the base one.
      properties:
        productId: { type: string }
        variantId: { type: string, nullable: true }
        locationId: { type: string, nullable: true }
        basePriceCents: { type: integer, format: int64, description: "Product price plus variant delta." }
        listPriceCents: { type: integer, format: int64, description: "After the location's price list; equals the base when there is none." }
        priceCents: { type: integer, format: int64, description: "Final, after any rule." }
        priceListId: { type: string, nullable: true }
        priceListName: { type: string, nullable: true }
        itemisedByList: { type: boolean, description: "True when an explicit item priced it, false when the blanket uplift did." }
        appliedRuleId: { type: string, nullable: true }
        ruleDiscountCents: { type: integer, format: int64, description: "What the rule took off the list price." }
      required: [productId, basePriceCents, listPriceCents, priceCents, itemisedByList, ruleDiscountCents]

# ── Outbound webhooks: GENERATED from the server's own classes by OpenApiCoverageSpec. Never hand-edit.
# Regenerate: ./gradlew :server:test --tests '*OpenApiCoverageSpec*' -Dopenapi.webhooks.write=true
x-webhooks:
  description: >-
    Ruva POSTs a JSON body to each of your endpoints subscribed to an event. Verify the signature before
    trusting it: HMAC-SHA256, keyed with your endpoint's secret (the bytes after `whsec_`,
    base64-decoded), over `<Ruva-Webhook-Id>.<Ruva-Webhook-Timestamp>.<raw body>`, compared
    with each space-separated `v1,<base64>` entry of Ruva-Webhook-Signature. Refuse a timestamp more
    than 300 seconds from your clock. Answer 2xx within 10 seconds; anything else is
    retried with backoff, 8 attempts in all, and a delivery can be replayed from the
    Developer page. De-duplicate requests on Ruva-Webhook-Id and facts on the body's `id`.
  headers:
    Ruva-Webhook-Id: "The delivery's id: the same on every retry, new for a replay."
    Ruva-Webhook-Timestamp: "Seconds since the epoch when this attempt was signed."
    Ruva-Webhook-Signature: "Space-separated v1,<base64 HMAC-SHA256> entries; one matching is enough."
    Ruva-Webhook-Event: "The event type, as in the body's type."
    Ruva-Webhook-Attempt: "1 for the first attempt, counting up on each retry."
    Ruva-Webhook-Replay: "true when somebody replayed this event on purpose."
  envelope:
    type: object
    required: [id, deliveryId, type, tenantId, occurredAt, replay, data]
    properties:
      id: { type: string }
      deliveryId: { type: string }
      type: { type: string }
      tenantId: { type: string }
      occurredAt: { type: integer, format: int64 }
      replay: { type: boolean }
      replayOfDeliveryId: { type: string, nullable: true }
      data: { type: object, description: "The event's payload: see events.<type>.data." }
  events:
    sale.completed:
      summary: "A sale was paid in full: at a till, on a till that was offline and synced later, by a guest's QR or kiosk order, or online. Its vatCents is the VAT it charged: 15/115 of its total after discounts per VAT type, rounded once to the nearest cent. A line's vatCents is its share of that, so the lines add up to it; a sale closed before November 2026, or by a till not yet updated, kept each line's VAT before the sale's discountCents, so there the lines' may add up to more."
      data:
        type: object
        required: [id, transactionNumber, locationId, status, orderType, subtotalCents, discountCents, vatCents, serviceChargeCents, tipCents, roundingCents, totalCents, paidCents, openedAt, lines]
        properties:
          id: { type: string }
          transactionNumber: { type: string }
          locationId: { type: string }
          status: { type: string }
          orderType: { type: string }
          customerId: { type: string, nullable: true }
          subtotalCents: { type: integer, format: int64 }
          discountCents: { type: integer, format: int64 }
          vatCents: { type: integer, format: int64 }
          serviceChargeCents: { type: integer, format: int64 }
          tipCents: { type: integer, format: int64 }
          roundingCents: { type: integer, format: int64 }
          totalCents: { type: integer, format: int64 }
          paidCents: { type: integer, format: int64 }
          openedAt: { type: integer, format: int64 }
          closedAt: { type: integer, format: int64, nullable: true }
          refundOfId: { type: string, nullable: true }
          refundReasonCode: { type: string, nullable: true }
          lines:
            type: array
            items:
              type: object
              required: [productId, name, quantity, unitPriceCents, lineTotalCents, vatCents, discountCents, comped, voided]
              properties:
                productId: { type: string }
                variantId: { type: string, nullable: true }
                name: { type: string }
                quantity: { type: integer, format: int32 }
                unitPriceCents: { type: integer, format: int64 }
                lineTotalCents: { type: integer, format: int64 }
                vatCents: { type: integer, format: int64 }
                discountCents: { type: integer, format: int64 }
                comped: { type: boolean }
                voided: { type: boolean }
    sale.refunded:
      summary: "Money was given back. A refund is a sale of its own, and refundOfId names the sale it reverses."
      data:
        type: object
        required: [id, transactionNumber, locationId, status, orderType, subtotalCents, discountCents, vatCents, serviceChargeCents, tipCents, roundingCents, totalCents, paidCents, openedAt, lines]
        properties:
          id: { type: string }
          transactionNumber: { type: string }
          locationId: { type: string }
          status: { type: string }
          orderType: { type: string }
          customerId: { type: string, nullable: true }
          subtotalCents: { type: integer, format: int64 }
          discountCents: { type: integer, format: int64 }
          vatCents: { type: integer, format: int64 }
          serviceChargeCents: { type: integer, format: int64 }
          tipCents: { type: integer, format: int64 }
          roundingCents: { type: integer, format: int64 }
          totalCents: { type: integer, format: int64 }
          paidCents: { type: integer, format: int64 }
          openedAt: { type: integer, format: int64 }
          closedAt: { type: integer, format: int64, nullable: true }
          refundOfId: { type: string, nullable: true }
          refundReasonCode: { type: string, nullable: true }
          lines:
            type: array
            items:
              type: object
              required: [productId, name, quantity, unitPriceCents, lineTotalCents, vatCents, discountCents, comped, voided]
              properties:
                productId: { type: string }
                variantId: { type: string, nullable: true }
                name: { type: string }
                quantity: { type: integer, format: int32 }
                unitPriceCents: { type: integer, format: int64 }
                lineTotalCents: { type: integer, format: int64 }
                vatCents: { type: integer, format: int64 }
                discountCents: { type: integer, format: int64 }
                comped: { type: boolean }
                voided: { type: boolean }
    product.created:
      summary: "A product was added."
      data:
        type: object
        required: [id, name, categoryId, priceCents, active]
        properties:
          id: { type: string }
          name: { type: string }
          sku: { type: string, nullable: true }
          barcode: { type: string, nullable: true }
          categoryId: { type: string }
          priceCents: { type: integer, format: int64 }
          active: { type: boolean }
    product.updated:
      summary: "A product's name, SKU, barcode, category, price or availability changed."
      data:
        type: object
        required: [id, name, categoryId, priceCents, active]
        properties:
          id: { type: string }
          name: { type: string }
          sku: { type: string, nullable: true }
          barcode: { type: string, nullable: true }
          categoryId: { type: string }
          priceCents: { type: integer, format: int64 }
          active: { type: boolean }
    stock.adjusted:
      summary: "Stock moved for a reason other than a sale or a return (those are told by the sale): a count, waste, a delivery, a transfer or an adjustment."
      data:
        type: object
        required: [id, productId, locationId, deltaUnits, reason, occurredAt]
        properties:
          id: { type: string }
          productId: { type: string }
          variantId: { type: string, nullable: true }
          locationId: { type: string }
          deltaUnits: { type: integer, format: int64 }
          reason: { type: string }
          occurredAt: { type: integer, format: int64 }
    order.created:
      summary: "An order was opened and is not yet paid: a tab, a ticket, or a guest's QR or kiosk order."
      data:
        type: object
        required: [id, transactionNumber, locationId, status, orderType, totalCents, openedAt]
        properties:
          id: { type: string }
          transactionNumber: { type: string }
          locationId: { type: string }
          status: { type: string }
          orderType: { type: string }
          tableId: { type: string, nullable: true }
          totalCents: { type: integer, format: int64 }
          openedAt: { type: integer, format: int64 }
    order.updated:
      summary: "An open order's status, total or table changed."
      data:
        type: object
        required: [id, transactionNumber, locationId, status, orderType, totalCents, openedAt]
        properties:
          id: { type: string }
          transactionNumber: { type: string }
          locationId: { type: string }
          status: { type: string }
          orderType: { type: string }
          tableId: { type: string, nullable: true }
          totalCents: { type: integer, format: int64 }
          openedAt: { type: integer, format: int64 }
    customer.created:
      summary: "A customer record was added. It carries the id and never the person: fetch the record with the customers:read scope."
      data:
        type: object
        required: [id, erased, deleted, createdAt, updatedAt]
        properties:
          id: { type: string }
          erased: { type: boolean }
          deleted: { type: boolean }
          createdAt: { type: integer, format: int64 }
          updatedAt: { type: integer, format: int64 }
    customer.updated:
      summary: "A customer record changed, was deleted or was erased. It carries the id and never the person."
      data:
        type: object
        required: [id, erased, deleted, createdAt, updatedAt]
        properties:
          id: { type: string }
          erased: { type: boolean }
          deleted: { type: boolean }
          createdAt: { type: integer, format: int64 }
          updatedAt: { type: integer, format: int64 }
    kitchen.ticket_ready:
      summary: "One kitchen ticket was plated: a single station's part of an order, not the whole order (an order with several stations has one of these per ticket, and the expo's call is not an event). Told once per ticket. It carries the pickup number, the station and the lines made, never a guest's name, phone, address or note."
      data:
        type: object
        required: [id, orderId, locationId, pickupNumber, firedAt, lines]
        properties:
          id: { type: string }
          orderId: { type: string }
          locationId: { type: string }
          pickupNumber: { type: string }
          stationId: { type: string, nullable: true }
          stationName: { type: string, nullable: true }
          firedAt: { type: integer, format: int64 }
          readyAt: { type: integer, format: int64, nullable: true }
          bumpedAt: { type: integer, format: int64, nullable: true }
          lines:
            type: array
            items:
              type: object
              required: [name, quantity, modifiers]
              properties:
                productId: { type: string, nullable: true }
                name: { type: string }
                quantity: { type: integer, format: int32 }
                modifiers:
                  type: array
                  items:
                    type: object
                    required: [name]
                    properties:
                      group: { type: string, nullable: true }
                      name: { type: string }
    kitchen.ticket_bumped:
      summary: "One kitchen ticket was bumped off its board. Told once per ticket, even when it is tapped twice, replayed by a hub that was offline, or recalled and bumped again. It carries the pickup number, the station and the lines made, never a guest's name, phone, address or note."
      data:
        type: object
        required: [id, orderId, locationId, pickupNumber, firedAt, lines]
        properties:
          id: { type: string }
          orderId: { type: string }
          locationId: { type: string }
          pickupNumber: { type: string }
          stationId: { type: string, nullable: true }
          stationName: { type: string, nullable: true }
          firedAt: { type: integer, format: int64 }
          readyAt: { type: integer, format: int64, nullable: true }
          bumpedAt: { type: integer, format: int64, nullable: true }
          lines:
            type: array
            items:
              type: object
              required: [name, quantity, modifiers]
              properties:
                productId: { type: string, nullable: true }
                name: { type: string }
                quantity: { type: integer, format: int32 }
                modifiers:
                  type: array
                  items:
                    type: object
                    required: [name]
                    properties:
                      group: { type: string, nullable: true }
                      name: { type: string }
    platform.ping:
      summary: "Sent by the endpoint's test button, so you can prove your receiver is reachable and your signature check is right."
      data:
        type: object
        required: [message, endpointId, requestedBy]
        properties:
          message: { type: string }
          endpointId: { type: string }
          requestedBy: { type: string }
