openapi: 3.1.1

info:
  title: OpenShop Public API
  version: "1.0.0"
  summary: The externally-consumable half of OpenShop.mn — catalog, checkout, orders, payment links and the Buildry Chat connector.
  description: |
    This file is the **contract**, not a tour of the codebase. It describes only what an
    integrator outside OpenShop may call:

    * the **token-free public shop surface** a storefront or a chat commerce client uses
      (`/shop/products*`, `/shop/checkout`, `/shop/pay/*`, …);
    * the **API-key surface** a merchant's POS/ERP uses (`Authorization: Bearer osk_live_…`,
      migrations 0137/0138);
    * the **merchant integration console** that mints those keys and registers webhook
      endpoints (browser session only — a credential never administers credentials);
    * **third-party apps** (X9 Phase A/C): an app — registered by OpenShop or by a developer
      in the self-serve portal (`app.openshop.mn/developer`) and approved in review — is
      installed by a merchant on one shop through OAuth 2.0 authorization code + PKCE on
      `id.openshop.mn` (`appOAuth`), and then calls the same shop surface with an opaque
      `osa_live_…` token — see the `appOAuth` security scheme and the `Apps` tag;
    * the **Buildry Chat connector** surface (HMAC-signed, `api.openshop.mn` only).

    Deliberately **not** described here, because they are not a public contract:
    the superadmin back-office (`/admin/*`), the internal provisioning routes
    (`/api/v1/internal/*`), the payment-rail callbacks (`/api/v1/pay/*`, IP-allowlisted at
    the edge), the first-party identity/OIDC login surface (`/oauth2/authorize` for
    first-party clients, `/oauth2/userinfo`, `/oauth2/consent`,
    `/.well-known/openid-configuration`, `/api/v1/auth/*`, `/api/v1/me/*` [including the
    self-serve developer portal `/api/v1/me/developer*`, which is browser-session only on
    `app.openshop.mn` — no API key or app token is ever accepted there] — the app install,
    token and revoke endpoints ARE part of this contract, via `appOAuth`), the marketing
    blog reads (`/api/v1/blog*`), and the
    session-only merchant console CRUD (catalog writes, coupons, storefront design, Wire
    KYB, e-barimt configuration, staff, roles, domains, pages, bundles, payable
    administration). Those may change without a major version.

    **Error envelope.** Every error is `{"error": "<message, usually Mongolian>"}`. Errors
    that an integrator is expected to branch on additionally carry a stable machine-readable
    `code` (and sometimes extra fields such as `remaining` or `required_scope`). Codes are
    additive: a new one may appear, an existing one is never renamed. **Never branch on the
    message text** — it is UI copy and gets edited.

    **Languages.** Mongolian (`mn`) is the default; English (`en`) is optional. The
    language of messages and display labels (`error`, `*_label`, hints) follows the
    `X-OS-Locale: mn|en` header (anything else = `mn`; `Accept-Language` is ignored) or,
    on `/shop/*`, the `?lang=mn|en` query parameter. Merchant text (product titles,
    descriptions, categories, pages …) is translated only when the caller asks for a
    content language with `?lang=` or `X-OS-Content-Locale: en`, and only if the shop has
    that language turned on; each field falls back to Mongolian when it has no
    translation, and the response's `locale` says which language was served. Codes and
    enum values never change with the language.

    **Money and time.** All amounts are Mongolian tögrög as integers (`*_mnt`), never
    decimals. Timestamps are RFC 3339; most are rendered in `Asia/Ulaanbaatar` (`+08:00`).

    **Versioning.** The major version lives in the URL (`/v1`). Additive change (a new
    optional field, a new error code, a new endpoint) happens inside `v1`. A breaking
    change means `/v2`. Removal follows the deprecation policy: `Deprecation` (RFC 9745) +
    `Sunset` (RFC 8594) + a `Link` to the successor, at least six months' notice, then
    `410 Gone` with code `endpoint_sunset`.
  contact:
    name: OpenShop platform team
    url: https://openshop.mn
  license:
    name: Proprietary
    identifier: LicenseRef-OpenShop-Proprietary

externalDocs:
  description: Integrator guide (Mongolian) — docs/OPEN-API-PLATFORM.md §10
  url: https://github.com/usukhv/openshop/blob/main/docs/OPEN-API-PLATFORM.md

servers:
  - url: https://{slug}.openshop.mn/api/v1
    description: |
      The shop's own host. The shop is identified by the subdomain, so the token-free
      public surface works here with no credential at all.
    variables:
      slug:
        default: demo
        description: The shop handle, e.g. `demo` in `demo.openshop.mn`.
  - url: https://api.openshop.mn/v1
    description: |
      The canonical API host. There is no shop in the hostname here, so every shop-scoped
      call must present an API key — the key names its own shop. This is also the only host
      that serves the platform-level connector surface.

tags:
  - name: Catalog
    description: Public, read-only reads of one shop's catalog. No credential required.
  - name: Checkout
    description: Creating and following an order. Public by default; never CORS-enabled.
  - name: Payment links
    description: "«Төлбөрийн холбоос» — a standalone payable whose UUID is a capability token."
  - name: Gift cards
    description: |
      The shop's own closed-loop gift cards: sold through checkout (the money goes to the
      merchant like any order), spent only in the same shop via `gift_card_codes`. No
      cash-out, top-up or cross-shop transfer exists. Codes travel in request bodies only.
  - name: Orders
    description: The merchant's own order data. API key (or console session) with `order:read` / `order:write`.
  - name: Inventory
    description: Price and stock writes a POS performs with `product:write`.
  - name: Integration console
    description: Minting API keys and registering webhook endpoints. Browser session only.
  - name: Storefront design
    description: |
      The merchant console's design history. Browser session only, with `product:write`;
      console surface — may change without a major version.
  - name: Connector
    description: The Buildry Chat ↔ OpenShop pairing protocol. HMAC-signed, `api.openshop.mn` only.
  - name: Apps
    description: |
      Third-party apps. A developer (any OpenShop account that accepts the developer terms;
      DAN-verified) registers up to 5 apps at `app.openshop.mn/developer`, gets the client
      secret once, and tries a **draft** app on shops they manage (dev mode — no one else can
      install it). Submitting sends the app to OpenShop review: approved unlisted (install
      link, pilot shops only), listed (directory `/apps`), or back to draft with a reason.
      An approved app's name, logo, wider scopes and new redirect/webhook/install hosts need
      a new review. A merchant installs an app on one shop and consents to its scopes; the app
      then holds an opaque token for that shop. Enabled per deployment (`APPS_ENABLED`) —
      while off, these routes answer `404`.

security: []

paths:
  # ───────────────────────────── Catalog (public) ─────────────────────────────
  /shop/products:
    get:
      tags: [Catalog]
      operationId: listProducts
      summary: List the shop's products
      description: |
        Returns active products. A caller holding a `product:write` API key (or a console
        session with that permission) additionally sees drafts.

        `?q=` runs the Mongolian search engine rather than a plain filter; `hint` reports
        how the result was produced. Cross-origin browser calls are refused unless the
        origin is named in `PUBLIC_API_CORS_ORIGINS` (default: none — this surface is
        server-to-server).
      security:
        - {}
        - apiKey: []
        - session: []
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Offset'
        - name: q
          in: query
          description: Free-text search over title and description.
          required: false
          schema: { type: string }
        - name: category
          in: query
          description: Shop-category id; the subtree is included. An unparseable value is ignored, not refused.
          required: false
          schema: { type: string, format: uuid }
        - name: module
          in: query
          description: |
            Narrow to one shop module's product types — `shop` = physical, `digital` = digital,
            `course` = course + pass. Any other value is ignored (all types), not refused.
          required: false
          schema: { type: string, enum: [shop, digital, course] }
        - name: availability
          in: query
          description: |
            `in_stock` = buyable now, `preorder` = sold as a pre-order (buyable before stock arrives,
            whatever the stock count), `sold_out` = every tracked variant at 0 and not a pre-order.
            The three keys partition the catalogue. Any other value is ignored (all products), not refused.
          required: false
          schema: { type: string, enum: [in_stock, preorder, sold_out] }
        - $ref: '#/components/parameters/ContentLang'
        - $ref: '#/components/parameters/ContentLocaleHeader'
        - name: on_sale
          in: query
          description: |
            `1` = only products with an advertised discount — an honest, visible badge on the
            product or on any of its variants. A discount hidden by the price-history rule
            (`discount_basis` `inflated`/`insufficient`) never qualifies, though it still applies
            at checkout. Reads at most the first 1000 matches.
          required: false
          schema: { type: string, enum: ['1'] }
      responses:
        '200':
          description: The matching products.
          headers:
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema:
                type: object
                required: [products, hint]
                properties:
                  products:
                    type: array
                    items: { $ref: '#/components/schemas/Product' }
                  hint:
                    type: string
                    description: |
                      How the search answered. `""` = an ordinary listing or an exact match,
                      `relaxed` = no row matched every word so any-word matching was used,
                      `phone` = the query looked like a telephone number.
                    enum: ["", relaxed, phone]
                  max_discount_percent:
                    type: integer
                    description: |
                      Present with `on_sale=1` or `sort=discount`: the largest honest, visible discount
                      among every product the query matches (first 1000), not just this page. 0 = none.
                  max_discount_label:
                    type: string
                    description: Display-ready header for it («45% хүртэл хямдрал»); empty when 0.
                  locale: { $ref: '#/components/schemas/ContentLocale' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/products/{id}:
    get:
      tags: [Catalog]
      operationId: getProduct
      summary: Read one product
      description: One product by id. Drafts are visible only to a caller with `product:write`, or through a `pv` preview token.
      security:
        - {}
        - apiKey: []
        - session: []
      parameters:
        - $ref: '#/components/parameters/ProductId'
        - name: pv
          in: query
          description: A single-use draft-preview token minted by the merchant console. Lets an anonymous caller see one unpublished product.
          required: false
          schema: { type: string }
        - $ref: '#/components/parameters/ContentLang'
        - $ref: '#/components/parameters/ContentLocaleHeader'
      responses:
        '200':
          description: The product. `recent_paid_count` is present here (and only here) when at least two buyers paid for it in the last seven days.
          headers:
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Product' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/products/{id}/variants:
    get:
      tags: [Catalog]
      operationId: listVariants
      summary: List a product's variants and its option axes
      description: |
        `cost_mnt` — the merchant's buying price — is **never** returned to an API key,
        whatever its scopes, nor to an anonymous caller. Only a console session that could
        edit the variant sees it.

        An unknown product id is not an error here: the response is simply empty.
      security:
        - {}
        - apiKey: []
        - session: []
      parameters:
        - $ref: '#/components/parameters/ProductId'
        - $ref: '#/components/parameters/ContentLang'
        - $ref: '#/components/parameters/ContentLocaleHeader'
      responses:
        '200':
          description: The product's variants and options.
          headers:
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema:
                type: object
                required: [variants, options]
                properties:
                  variants:
                    type: array
                    items: { $ref: '#/components/schemas/Variant' }
                  options:
                    type: array
                    items: { $ref: '#/components/schemas/ProductOption' }
                  locale: { $ref: '#/components/schemas/ContentLocale' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/products/{id}/reviews:
    get:
      tags: [Catalog]
      operationId: listProductReviews
      summary: Read a product's reviews
      description: |
        Verified-purchase reviews only — every review is tied to one paid order line. One page
        (10) of visible reviews plus the aggregate (`summary`, with the 5→1 histogram), the filter
        chips and the sorts, all display-ready. The aggregate counts every verified rating,
        including reviews whose text the shop hid (`hidden_note` says so).
      parameters:
        - $ref: '#/components/parameters/ProductId'
        - { name: page, in: query, schema: { type: integer, minimum: 1 } }
        - { name: stars, in: query, description: 'Only N-star reviews (1–5).', schema: { type: integer, minimum: 1, maximum: 5 } }
        - { name: photos, in: query, description: '`1` = only reviews with photos.', schema: { type: string, enum: ['1'] } }
        - { name: sort, in: query, description: '`helpful` = most readers found it helpful.', schema: { type: string, enum: [new, helpful, high, low] } }
      responses:
        '200':
          description: The product's review summary and one page of reviews.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProductReviewList' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/reviews:
    get:
      tags: [Catalog]
      operationId: listShopReviews
      summary: Read the shop's reputation
      description: Up to 30 most recent shop reviews plus the aggregate.
      responses:
        '200':
          description: The shop's review summary and recent reviews.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ReviewList' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/categories:
    get:
      tags: [Catalog]
      operationId: listShopCategories
      summary: List the shop's category tree
      description: The whole tree in one call — parent links are in `parent_id`, ordering in `position`.
      security:
        - {}
        - apiKey: []
        - session: []
      responses:
        '200':
          description: Every category of this shop.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/ShopCategory' }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/categories/{id}:
    get:
      tags: [Catalog]
      operationId: getShopCategory
      summary: Read one category
      description: One node of the shop's category tree, including its product count and taxonomy mapping.
      security:
        - {}
        - apiKey: []
        - session: []
      parameters:
        - name: id
          in: path
          required: true
          description: Category id.
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The category.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShopCategory' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/bundles/public/{id}:
    get:
      tags: [Catalog]
      operationId: getPublicBundle
      summary: Read an active bundle
      description: |
        Display-ready: component titles, sale-aware unit prices and per-component
        availability are resolved server-side. Only `active` bundles are visible.
      security:
        - {}
        - apiKey: []
        - session: []
      parameters:
        - name: id
          in: path
          required: true
          description: Bundle id.
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The bundle.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Bundle' }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/public/branches:
    get:
      tags: [Catalog]
      operationId: listPublicBranches
      summary: List the shop's branches (store locator)
      description: |
        Active branches only, main branch first, then the merchant's order. Display-ready:
        the composed address, `tel:` links, the weekly hours and the «open now» state are
        computed server-side in Asia/Ulaanbaatar at response time (cached ≤ 60 s).
        `pickup` = checkout offers «Очиж авах» (collect at a branch); `delivery_available`
        = checkout takes delivery orders (false = pickup-only: send `pickup_branch_id`).
      security:
        - {}
        - apiKey: []
        - session: []
      responses:
        '200':
          description: The branches.
          content:
            application/json:
              schema:
                type: object
                required: [branches, pickup, count_label]
                properties:
                  branches: { type: array, items: { $ref: '#/components/schemas/Branch' } }
                  pickup: { type: boolean }
                  delivery_available:
                    type: boolean
                    description: |
                      false = the shop takes pickup orders only; a shipping cart without
                      `pickup_branch_id` is refused with `delivery_unavailable` (409).
                  count_label: { type: string, description: "«N салбарт үйлчилж байна»; empty when none." }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/videos:
    get:
      tags: [Catalog]
      operationId: listShopVideos
      summary: List the shop's curated videos
      description: |
        The merchant's ordered video list (YouTube, Facebook, Instagram, TikTok). Only the
        parsed provider + id is stored; `embed_url`, `url` and `thumbnail_url` are rebuilt
        server-side from it (thumbnail = YouTube only, else empty). `portrait` = a 9:16 player.
      security:
        - {}
        - apiKey: []
        - session: []
      responses:
        '200':
          description: The videos.
          content:
            application/json:
              schema:
                type: object
                required: [videos]
                properties:
                  videos:
                    type: array
                    items:
                      type: object
                      required: [id, provider, provider_label, title, url, embed_url, thumbnail_url, portrait]
                      properties:
                        id: { type: string, format: uuid }
                        provider: { type: string, enum: [youtube, facebook, instagram, tiktok] }
                        provider_label: { type: string }
                        title: { type: string }
                        url: { type: string, description: Open-on-platform link. }
                        embed_url: { type: string, description: The only iframe src to use. }
                        thumbnail_url: { type: string }
                        portrait: { type: boolean }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '500': { $ref: '#/components/responses/InternalError' }
  /shop/public/branches/{id}:
    get:
      tags: [Catalog]
      operationId: getPublicBranch
      summary: Read one active branch
      description: >-
        One active branch of the shop (name, address, phones, weekly hours with a
        server-computed «open now» label, optional map point and photo). Inactive
        or unknown ids return 404.
      security:
        - {}
        - apiKey: []
        - session: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The branch.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Branch' }
        '401': { $ref: '#/components/responses/InvalidAPIKey' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/suggest:
    get:
      tags: [Catalog]
      operationId: suggestShopProducts
      summary: Search-as-you-type over this shop
      description: |
        At most eight confident hits. A query shorter than two characters answers `200`
        with an empty list rather than an error. Results are cached for five minutes on the
        normalised query.
      parameters:
        - name: q
          in: query
          required: true
          description: The partial query. Fewer than two characters returns an empty list.
          schema: { type: string }
        - $ref: '#/components/parameters/ContentLang'
        - $ref: '#/components/parameters/ContentLocaleHeader'
      responses:
        '200':
          description: Suggestions, most relevant first.
          content:
            application/json:
              schema:
                type: object
                required: [suggestions]
                properties:
                  suggestions:
                    type: array
                    items: { $ref: '#/components/schemas/Suggestion' }
                  locale: { $ref: '#/components/schemas/ContentLocale' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/feed.csv:
    get:
      tags: [Catalog]
      operationId: getProductFeedCSV
      summary: Product feed (CSV)
      description: |
        The shop's own catalogue as a Google Merchant Center / Meta Commerce Manager
        product feed. Paste the URL into Merchant Center («Scheduled fetch») or Commerce
        Manager («Data feed» → scheduled); no credential is needed.

        **Rows.** Every `active` product that has an active variant (this is the
        merchant's own feed; there is no cross-shop catalogue). Drafts never appear. A product with one variant is one row whose `id` is the
        **product UUID** — the same `retailer_id` the Facebook catalogue sync and the Pixel's
        `content_ids` use. A product with two or more active variants fans out to one row
        per variant: `id` = variant UUID, `item_group_id` = product UUID, title suffixed with
        the option values, price/availability/image per variant. `link` is always the
        product page on the shop's canonical host (its custom domain when active).

        **Columns**, in order: `id`, `item_group_id`, `title`, `description` (plain text,
        ≤5000 characters), `availability` (`in stock` / `out of stock` — an untracked
        variant is in stock), `condition` (always `new`), `price` (`"<integer> MNT"`),
        `sale_price` (present only while the sale is active; computed exactly like the
        storefront), `sale_price_effective_date` (only when the sale has an end date),
        `link`, `image_link`, `additional_image_link` (comma-joined, at most 10), `brand`
        (the shop's display name), `product_type` (the shop-category trail),
        `google_product_category` (the reference taxonomy path, English; empty when the
        shop category is not linked). Nothing private to the merchant — cost, stock counts —
        is ever included.

        **Caching.** The body is cached per shop and format for five minutes (`Cache-Control:
        public, max-age=300`) and carries an `ETag`; send it back as `If-None-Match` to get
        `304`. A change to the catalogue therefore shows in the feed within five minutes.
        UTF-8 with a byte-order mark; RFC 4180 quoting. Per-client budget of 30 requests
        per minute.
      parameters:
        - $ref: '#/components/parameters/IfNoneMatch'
      responses:
        '200':
          description: The feed, streamed. `Content-Disposition` is `inline` — this is a document for a crawler, not a download.
          headers:
            ETag: { $ref: '#/components/headers/FeedETag' }
            Cache-Control: { $ref: '#/components/headers/FeedCacheControl' }
            Content-Disposition: { $ref: '#/components/headers/FeedDisposition' }
          content:
            text/csv:
              schema: { type: string }
        '304': { $ref: '#/components/responses/FeedNotModified' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/feed.xml:
    get:
      tags: [Catalog]
      operationId: getProductFeedXML
      summary: Product feed (RSS 2.0, Google `g:` namespace)
      description: |
        The same rows as `/shop/feed.csv`, as the RSS 2.0 dialect Merchant Center and
        Commerce Manager read: one `<item>` per row, `title`/`description`/`link` as RSS
        elements and every other column as `<g:…>` under `xmlns:g="http://base.google.com/ns/1.0"`;
        additional images are repeated `<g:additional_image_link>` elements. Row rules,
        caching and the per-client budget are as for the CSV variant.
      parameters:
        - $ref: '#/components/parameters/IfNoneMatch'
      responses:
        '200':
          description: The feed, streamed.
          headers:
            ETag: { $ref: '#/components/headers/FeedETag' }
            Cache-Control: { $ref: '#/components/headers/FeedCacheControl' }
            Content-Disposition: { $ref: '#/components/headers/FeedDisposition' }
          content:
            application/rss+xml:
              schema: { type: string }
        '304': { $ref: '#/components/responses/FeedNotModified' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  # ───────────────────────────── Checkout ─────────────────────────────
  /shop/checkout:
    post:
      tags: [Checkout]
      operationId: createCheckout
      summary: Create an order and open a payment
      description: |
        Guest-first: no credential is required. The response carries the order and, when the
        shop is live on the payment rail, an invoice with a hosted `checkout_url` the payer
        is sent to.

        **Server-side pricing.** Prices in the request are ignored; sale price, bundle
        composition, coupon and delivery fee are all resolved on the server, in that order.

        **Not transactional with stock.** An order is created without reserving stock, but a
        line whose variant is already sold out is refused with `out_of_stock` /
        `insufficient_stock` before any order exists.

        **Go-live gate.** If the shop is not an active merchant on the payment rail the call
        fails with `payments_not_ready` and **no order is created** — the buyer's cart is
        intact and they should be told to contact the shop.

        **Idempotency.** Send `Idempotency-Key` (see the header description). Without it a
        retried POST creates a second order.

        **Connector guard.** A request that identifies itself with `X-Connector-Id` must also
        carry a valid `X-Connector-Signature` and belong to a linked shop. A request with no
        `X-Connector-Id` is the shop's own storefront and passes untouched — unless the
        platform has enforcement on and the User-Agent is Buildry's, in which case it is
        refused with `connector_required`.

        This endpoint is **never** CORS-enabled. Call it from your server.
      security:
        - {}
        - apiKey: []
        - connectorHmac: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
        - $ref: '#/components/parameters/ConnectorId'
        - $ref: '#/components/parameters/ConnectorSignature'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CheckoutRequest' }
      responses:
        '201':
          description: The order was created. `invoice.checkout_url` is the hosted payment page.
          headers:
            Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' }
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema:
                type: object
                required: [order]
                properties:
                  order: { $ref: '#/components/schemas/Order' }
                  invoice: { $ref: '#/components/schemas/Invoice' }
                  access_token:
                    type: string
                    description: |
                      Present only when the order holds a downloadable file, a code or a course.
                      The buyer's capability for `{shop}/d/{access_token}` — returned ONCE, stored
                      only as a hash, never returned by `GET /checkout/{id}`. Hand it to the buyer;
                      do not log it.
        '400':
          description: |
            The request is not acceptable. `buyer_email_required` = a cart with digital
            items and no signed-in buyer carries no `buyer_email`; `digital_qty_invalid` = a
            file/course line with qty > 1 or a code line above 20. Plain-envelope validation failures (bad
            `product_id`, non-positive `qty`, more than 100 items or 20 bundles, an
            organisation ТТД that is not 11–14 digits, a malformed citizen register) carry no
            `code`; a malformed `Idempotency-Key` carries `idempotency_key_invalid`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: A connector-signed request failed verification.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                invalidSignature:
                  value: { error: invalid_signature, code: invalid_signature }
        '403':
          description: The connector is not permitted to check out for this shop.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                notLinked:
                  summary: Signed, but the shop has no active connector link
                  value: { error: connector_not_linked, code: connector_not_linked }
                required:
                  summary: Enforcement is on and a Buildry client called without signing
                  value: { error: connector_required, code: connector_required }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: |
            The order could not be created as asked. `out_of_stock` and `insufficient_stock`
            also carry `title` and `remaining`; `already_enrolled` = the signed-in buyer already
            owns the course in the cart. Coupon failures use the plain envelope with a
            Mongolian explanation and no `code` — except `coupon_not_assigned_to_you`: the code
            is a personal coupon the merchant gave one customer, usable only while that
            customer is signed in (whose it is is never revealed). `promotion_not_stackable` = a
            coupon code was sent while a promotion that does not combine with coupons applies to
            the cart (send the order without the code).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                insufficientStock:
                  value:
                    error: "Цамц барааны үлдэгдэл хүрэлцэхгүй байна (үлдсэн: 2)."
                    code: insufficient_stock
                    title: Цамц
                    remaining: 2
                outOfStock:
                  value: { error: "Цамц бараа дууссан байна.", code: out_of_stock, title: Цамц, remaining: 0 }
                deliveryUnavailable:
                  summary: Pickup-only shop and no `pickup_branch_id` on a shipping cart — no order was created
                  value:
                    error: Энэ дэлгүүр захиалгыг зөвхөн салбараас очиж авахаар хүлээн авна. Очиж авах салбараа сонгоно уу.
                    code: delivery_unavailable
                paymentsNotReady:
                  summary: The shop cannot accept online payment yet — no order was created
                  value:
                    error: Энэ дэлгүүр одоогоор онлайн төлбөр хүлээн авах боломжгүй байна. Дэлгүүртэй шууд холбогдож захиалаарай.
                    code: payments_not_ready
                idempotencyInProgress:
                  summary: An earlier request with this key is still running
                  value: { error: Ижил хүсэлт боловсруулагдаж байна. Түр хүлээгээд дахин шалгана уу., code: idempotency_in_progress }
        '413':
          description: The request body exceeded the connector's 64 KiB limit.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '422': { $ref: '#/components/responses/IdempotencyKeyReuse' }
        '429':
          description: |
            Too many checkouts. A **keyed** caller is counted against its own key's write
            budget and gets the coded envelope plus `Retry-After`; an anonymous caller is
            counted per client address (30 a minute) and gets the plain envelope with no
            `code`.
          headers:
            Retry-After: { $ref: '#/components/headers/RetryAfter' }
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                keyed:
                  value: { error: хэт олон хүсэлт — түр хүлээгээд дахин оролдоно уу, code: rate_limited }
                anonymous:
                  value: { error: хэт олон хүсэлт, түр хүлээнэ үү }
        '500': { $ref: '#/components/responses/InternalError' }
        '502': { $ref: '#/components/responses/RailUnavailable' }

  /shop/checkout/{id}:
    get:
      tags: [Checkout]
      operationId: getCheckoutStatus
      summary: Poll an order's payment status
      description: |
        The order id doubles as the receipt token: it is an unguessable UUID and the response
        carries no buyer data. Treat `status: "paid"` from **this** endpoint as the only proof
        of payment — a hosted-checkout redirect back to your site is not proof.

        Same connector guard as `POST /shop/checkout`. Never CORS-enabled.
      security:
        - {}
        - apiKey: []
        - connectorHmac: []
      parameters:
        - name: id
          in: path
          required: true
          description: The order id returned by `POST /shop/checkout`.
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/ConnectorId'
        - $ref: '#/components/parameters/ConnectorSignature'
      responses:
        '200':
          description: The order. `paid_at` appears once the rail has settled it.
          headers:
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401':
          description: A connector-signed request failed verification.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: The connector is not linked to this shop.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/gift-card-offers/{id}:
    get:
      tags: [Gift cards]
      operationId: getGiftCardOffer
      summary: A gift-card product's buying rules
      description: |
        Denominations and/or the custom range, validity and the sanitised terms of an active
        `gift_card` product — what the product page needs to build `items[].gift_card` for
        `POST /shop/checkout`. Public catalogue read.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The offer.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GiftCardOffer' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/gift-cards/lookup:
    post:
      tags: [Gift cards]
      operationId: lookupGiftCard
      summary: Check a gift card's balance
      description: |
        The code goes in the BODY (never a URL) and is never echoed back. A code only ever
        resolves in the shop that issued it. Rate-limited to 10 requests a minute per client
        address; 20 wrong codes in an hour block that address for this shop for an hour.
        Never CORS-enabled.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              properties:
                code: { type: string, description: 'XXXX-XXXX-XXXX-XXXX (case, spaces and dashes are ignored).' }
      responses:
        '200':
          description: The card (masked).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GiftCardBalance' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404':
          description: '`gift_card_not_found` — unknown, malformed, or another shop''s code.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/orders/lookup:
    post:
      tags: [Checkout]
      operationId: lookupGuestOrder
      summary: Look up a guest's own order
      description: |
        The buyer-facing receipt: it needs **both** the unguessable order id and the phone
        number entered at checkout. Every miss — wrong phone, wrong shop, unknown id — is the
        same `404`, so the endpoint reveals nothing. Rate-limited to 10 requests a minute per
        client address.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [order_id, phone]
              properties:
                order_id: { type: string, format: uuid }
                phone:
                  type: string
                  description: The phone entered at checkout.
      responses:
        '200':
          description: The buyer's view of the order, including its lines and a resumable payment URL when it is still payable.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BuyerOrder' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '429': { $ref: '#/components/responses/RateLimitedPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/coupons/quote:
    post:
      tags: [Checkout]
      operationId: quoteCoupon
      summary: Price a coupon against a cart
      description: |
        A preview only — nothing is redeemed. With `code` empty the shop's best automatically
        applied discount is previewed instead, and "no coupon applies" is a `200` with a zero
        discount, not an error.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CouponQuoteRequest' }
      responses:
        '200':
          description: The discount this cart would receive.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CouponQuote' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: The coupon exists but does not apply — inactive, exhausted, below the minimum spend, already used by this buyer, first-order-only, or producing no benefit. Mongolian message, no `code` — except `coupon_not_assigned_to_you` (a personal coupon given to another customer, or entered while signed out).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/promotions/quote:
    post:
      tags: [Checkout]
      operationId: quotePromotions
      summary: Price a cart's promotions
      description: |
        A preview only (2+1 / 1+1 / N+M and gift-with-purchase promotions the shop runs). Checkout
        re-prices server-side in the order sale → bundle → promotion → minimum order / free delivery
        → coupon → loyalty → delivery → gift card, so send the same lines you will check out. Lines
        that no longer resolve are skipped. Every label is display-ready Mongolian.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PromotionQuoteRequest' }
      responses:
        '200':
          description: The promotions this cart would receive.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PromotionQuote' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/ebarimt/tin-lookup:
    get:
      tags: [Checkout]
      operationId: lookupTIN
      summary: Resolve an organisation registration number to its ТТД
      description: |
        A B2B fiscal receipt needs an 11–14 digit ТТД; a company's 7-digit registration number
        is not one. Resolve it here first. Rate-limited to 60 requests a minute per client
        address.
      parameters:
        - name: regNo
          in: query
          required: true
          description: The 7-digit organisation registration number.
          schema: { type: string }
      responses:
        '200':
          description: The resolved ТТД.
          content:
            application/json:
              schema:
                type: object
                required: [tin]
                properties:
                  tin: { type: string }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '429': { $ref: '#/components/responses/RateLimitedPlain' }
        '503':
          description: The tax authority lookup is not configured or unreachable.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /shop/newsletter:
    post:
      tags: [Catalog]
      operationId: subscribeNewsletter
      summary: Subscribe an address to the shop's newsletter
      description: |
        **Always answers `200`.** An invalid address, a duplicate, and a rate-limited probe are
        indistinguishable by design — the endpoint must not become an address oracle.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email: { type: string, format: email }
      responses:
        '200':
          description: Accepted (whether or not a row was written).
          content:
            application/json:
              schema:
                type: object
                required: [ok]
                properties:
                  ok: { type: boolean, const: true }

  # ───────────────────────────── Payment links ─────────────────────────────
  /shop/pay/{id}:
    get:
      tags: [Payment links]
      operationId: getPaymentLink
      summary: Read a payment link
      description: |
        The link id is a capability token: whoever holds the URL may open it. A cancelled or
        expired link still answers `200` with its status, so the payer sees "no longer valid"
        rather than a `404` that reads as a typo. Another shop's link is simply not found.
      parameters:
        - $ref: '#/components/parameters/PayableId'
      responses:
        '200':
          description: The payment link, display-ready.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PublicPayable' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/pay/{id}/status:
    get:
      tags: [Payment links]
      operationId: getPaymentLinkStatus
      summary: Poll a payment link's status
      description: The small poll a return-from-hosted-checkout page runs. Only a server-confirmed `paid` counts.
      parameters:
        - $ref: '#/components/parameters/PayableId'
      responses:
        '200':
          description: The link's current status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayableStatus' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/pay/{id}/checkout:
    post:
      tags: [Payment links]
      operationId: payPaymentLink
      summary: Open (or reuse) the payment for a link
      description: |
        Opens the hosted payment page for a payment link. Calling it again while the previous
        intent is still open **reuses that intent** rather than opening a second payment
        window, so this endpoint is already idempotent for the duration of the intent
        (`INVOICE_TTL`, 1 hour) and takes no `Idempotency-Key`.

        A payment link is paid once. If the previous intent's window has passed but the payment
        provider still holds it open (the payer may still confirm it in their app), no second
        payment is opened: the answer is `409 payment_pending` — show the message and poll
        `GET /shop/pay/{id}/status` until it is `paid` or `payment_pending` clears.
      parameters:
        - $ref: '#/components/parameters/PayableId'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayableCheckoutRequest' }
      responses:
        '201':
          description: The invoice to pay.
          content:
            application/json:
              schema:
                type: object
                required: [invoice]
                properties:
                  invoice: { $ref: '#/components/schemas/Invoice' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: The link can no longer be paid, or the shop is not live on the rail.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                payableClosed:
                  value: { error: Энэ төлбөрийн холбоос хүчингүй болсон байна. Дэлгүүртэй холбогдоно уу., code: payable_closed }
                paymentsNotReady:
                  value: { error: Энэ дэлгүүр одоогоор онлайн төлбөр хүлээн авах боломжгүй байна. Дэлгүүртэй шууд холбогдож захиалаарай., code: payments_not_ready }
                paymentPending:
                  summary: The previous payment is still awaiting confirmation — poll the status, do not retry.
                  value: { error: Өмнөх төлбөр баталгаажихыг хүлээж байна, code: payment_pending }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }
        '502': { $ref: '#/components/responses/RailUnavailable' }

  # ───────────────────────────── Orders (API key) ─────────────────────────────
  /shop/orders:
    get:
      tags: [Orders]
      operationId: listOrders
      summary: List the shop's orders
      description: |
        Requires `order:read`. Unknown filter values are ignored rather than refused.

        Buyer contact fields (`buyer_name`, `buyer_phone`) additionally need `customer:read`;
        without it they are `null` and the row carries `pii_redacted: true`. Every role and
        API key that held `order:read` before 2026-09-24 was granted `customer:read` too, so
        existing integrations see no change.
      security:
        - apiKey: []
        - appOAuth: [order:read]
        - session: []
      parameters:
        - name: limit
          in: query
          description: 1–1000. Default 200.
          required: false
          schema: { type: integer, minimum: 1, maximum: 1000, default: 200 }
        - name: offset
          in: query
          required: false
          schema: { type: integer, minimum: 0, default: 0 }
        - name: status
          in: query
          required: false
          schema: { $ref: '#/components/schemas/OrderStatus' }
        - name: zone
          in: query
          required: false
          schema: { $ref: '#/components/schemas/DeliveryZone' }
        - name: source
          in: query
          description: First-touch traffic source; `direct` means "no source recorded".
          required: false
          schema: { type: string }
        - name: q
          in: query
          description: Free text over buyer name, phone and item titles.
          required: false
          schema: { type: string }
        - name: coupon
          in: query
          description: |
            One coupon code, matched exactly and case-insensitively: the orders placed with the
            coupon that carries this code, or with this single-use / personal code.
          required: false
          schema: { type: string, maxLength: 64 }
        - name: from
          in: query
          description: Inclusive start day, `YYYY-MM-DD`.
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
        - name: to
          in: query
          description: Inclusive end day, `YYYY-MM-DD`.
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
        - name: fulfilment
          in: query
          description: |
            Delivery fact beside the status: `to_ship` (paid, not shipped, not a pickup),
            `shipped` (paid and marked shipped), `pickup` (paid, collected at a branch),
            `delivered` (fulfilled).
          required: false
          schema: { type: string, enum: [to_ship, shipped, pickup, delivered] }
        - name: payment
          in: query
          description: |
            Payment fact beside the status: `due` (an extra charge is still open), `late`
            (paid after its payment window), `gift_card` (a gift card paid part of it).
          required: false
          schema: { type: string, enum: [due, late, gift_card] }
        - name: sort
          in: query
          description: Sort key; default `created`.
          required: false
          schema: { type: string, enum: [created, total], default: created }
        - name: order
          in: query
          description: Sort direction; default `desc` (newest / largest first).
          required: false
          schema: { type: string, enum: [asc, desc], default: desc }
      responses:
        '200':
          description: A page of orders plus the unpaged total.
          headers:
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema:
                type: object
                required: [orders, total]
                properties:
                  orders:
                    type: array
                    items: { $ref: '#/components/schemas/OrderRow' }
                  total: { type: integer }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }
    post:
      tags: [Orders]
      operationId: createManualOrder
      summary: Create an order for a buyer (console)
      description: |
        A shop member enters an order taken by phone or Messenger. The order is priced by the
        storefront checkout pipeline (sale → bundle → promotions → minimum order / free
        delivery → the shop's automatic coupon → delivery and cargo), placed `pending` with
        `src_source = "manual"` ("Гараар үүсгэсэн") and its hosted payment link is returned
        for the member to send. Nothing is "paid offline": the buyer pays through the link and
        settlement, stock and e-barimt run the normal flow. The link is payable for the
        invoice window (`expires_at`, 1 hour); an unpaid order then expires like any
        checkout. Console session only; requires `order:write`. Same per-IP rate limit as
        checkout. An `Idempotency-Key` header makes a retry safe.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ManualOrderRequest' }
      responses:
        '201':
          description: The pending order and its payment link.
          content:
            application/json:
              schema:
                type: object
                required: [order, source_label, pay_url, pay_window_label]
                properties:
                  order: { $ref: '#/components/schemas/Order' }
                  source_label: { type: string, description: '"Гараар үүсгэсэн".' }
                  pay_url:
                    type: string
                    description: The hosted payment page to send the buyer; "" when the rail has none.
                  expires_at: { type: string, format: date-time, description: Until when the link is payable. }
                  pay_window_label: { type: string, description: Mongolian sentence about the payment window. }
        '400':
          description: |
            `manual_order_invalid` — `field` names the refused field (`buyer_name`,
            `buyer_phone`, `buyer_email`, `buyer_note`, `items`, `fulfillment`,
            `pickup_branch_id`, `delivery_address`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: |
            The checkout's refusals: `payments_not_ready` (the shop cannot take online
            payments yet), `out_of_stock` / `insufficient_stock`, `min_order_not_met`,
            `pickup_unavailable`, `delivery_unavailable`, `buyer_email_required` (digital items).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429': { $ref: '#/components/responses/RateLimitedPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/orders/quote:
    post:
      tags: [Orders]
      operationId: quoteManualOrder
      summary: Price an order before creating it (console)
      description: |
        The exact price `POST /shop/orders` would give this body now — the same checkout
        pipeline run in a transaction that is always rolled back (nothing is kept, no
        promotion or coupon is used up). Without items it returns only the fulfillment
        options for the empty form. Answers with the same refusals as the create. Console
        session only; requires `order:write`.
      security:
        - session: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ManualOrderRequest' }
      responses:
        '200':
          description: Display-ready totals.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OrderQuote' }
        '400':
          description: "`manual_order_invalid` — see `POST /shop/orders`."
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: The checkout's refusals — see `POST /shop/orders`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429': { $ref: '#/components/responses/RateLimitedPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/orders/export:
    get:
      tags: [Orders]
      operationId: exportOrders
      summary: Export the full order history
      description: |
        The whole history (or the rows the list filters select), unpaged; every export is
        recorded in the shop's audit log. `?format=json` returns rows; anything else returns a
        UTF-8 CSV (with a BOM, so Excel renders Cyrillic) as a file attachment. Requires
        `order:read`; buyer contact fields need `customer:read` as well (blank / `null`
        otherwise).

        **Closed to apps**: an `appOAuth` token gets `403 app_route_not_allowed` — an app
        keeps in sync with `GET /shop/orders` and webhooks instead of bulk-exporting PII.
      security:
        - apiKey: []
        - session: []
      parameters:
        - name: format
          in: query
          description: "`json` for rows; omitted or anything else for a CSV attachment."
          required: false
          schema: { type: string, enum: [json, csv] }
        - name: status
          in: query
          description: The same filters as `GET /shop/orders` narrow the export (none = the whole history).
          required: false
          schema: { $ref: '#/components/schemas/OrderStatus' }
        - name: source
          in: query
          required: false
          schema: { type: string }
        - name: q
          in: query
          required: false
          schema: { type: string }
        - name: from
          in: query
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
        - name: to
          in: query
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
        - name: fulfilment
          in: query
          required: false
          schema: { type: string, enum: [to_ship, shipped, pickup, delivered] }
        - name: payment
          in: query
          required: false
          schema: { type: string, enum: [due, late, gift_card] }
      responses:
        '200':
          description: The export.
          headers:
            Content-Disposition:
              description: Present on the CSV variant, e.g. `attachment; filename="orders-demo-2026-09-16.csv"`.
              schema: { type: string }
          content:
            application/json:
              schema:
                type: object
                required: [orders, total]
                properties:
                  orders:
                    type: array
                    items: { $ref: '#/components/schemas/OrderExportRow' }
                  total: { type: integer }
            text/csv:
              schema: { type: string }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/orders/{id}:
    get:
      tags: [Orders]
      operationId: getOrder
      summary: Read one order in full
      description: |
        The authoritative record, including the buyer's contact details, the delivery address,
        the fiscal identifiers and every line. Requires `order:read`. This is where a webhook
        receiver comes for the detail the thin webhook payload deliberately omits.

        The buyer block (`buyer_name`, `buyer_phone`, `consumer_register`, `customer_tin`,
        `delivery_address`) needs `customer:read`; without it those fields are `null` and the
        body carries `pii_redacted: true`.
      security:
        - apiKey: []
        - appOAuth: [order:read]
        - session: []
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '200':
          description: The order.
          headers:
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OrderDetail' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

    patch:
      tags: [Orders]
      operationId: fulfilOrder
      summary: Mark an order delivered, or undo it
      description: |
        Flips `paid` ⇄ `fulfilled`. The body names the **target** state rather than toggling,
        so a double tap or a stale tab is harmless. Any other current state is a `409`.
        Requires `order:write`.
      security:
        - apiKey: []
        - appOAuth: [order:write]
        - session: []
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [fulfilled]
              properties:
                fulfilled:
                  type: boolean
                  description: "`true` = paid → fulfilled. `false` = fulfilled → paid."
      responses:
        '200':
          description: The order's new state.
          content:
            application/json:
              schema:
                type: object
                required: [id, status]
                properties:
                  id: { type: string, format: uuid }
                  status: { $ref: '#/components/schemas/OrderStatus' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: The order is not in a state that allows this transition.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/orders/{id}/shipment:
    put:
      tags: [Orders]
      operationId: setOrderShipment
      summary: Mark an order shipped, or correct its courier and tracking
      description: |
        Records the courier and parcel number the shop shipped a **paid** order with. The order
        `status` does not change: it stays `paid` (shown as `shipped_label`) until it is marked
        delivered with `PATCH /shop/orders/{id}`. The first call stamps `shipment.shipped_at`
        once, emails the buyer once and emits `order.shipped`; a later call on a shipped `paid`
        or `fulfilled` order corrects the details (emits `order.shipped` again, no second email).
        Sending the same details again is a no-op. Requires `order:write`.

        OpenShop does not deliver parcels and has no courier integration — `carrier` is free text.
      security:
        - apiKey: []
        - appOAuth: [order:write]
        - session: []
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [carrier]
              properties:
                carrier: { type: string, maxLength: 80, description: The courier's name as the shop calls it. }
                tracking_number: { type: string, maxLength: 100, description: The parcel number; empty when there is none. }
                tracking_url:
                  type: string
                  maxLength: 500
                  description: Optional absolute `https://` (or `http://`) link to the courier's tracking page.
      responses:
        '200':
          description: The order's shipment.
          content:
            application/json:
              schema:
                type: object
                required: [id, status, shipped, shipment]
                properties:
                  id: { type: string, format: uuid }
                  status: { $ref: '#/components/schemas/OrderStatus' }
                  shipped: { type: boolean, description: "`true` while the order is `paid` and shipped." }
                  shipped_label: { type: string, description: Present when `shipped`. }
                  shipment: { $ref: '#/components/schemas/OrderShipment' }
        '400':
          description: |
            Malformed body, or a field failed validation: `code` = `shipment_invalid` and
            `field` names it (`carrier`, `tracking_number`, `tracking_url`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: "`order_not_shippable` — the first mark needs a `paid` order; a correction a shipped `paid` or `fulfilled` one."
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/variants/{id}:
    patch:
      tags: [Inventory]
      operationId: patchVariant
      summary: Update a variant's price or stock
      description: |
        The POS write. Requires `product:write`.

        **An API key or app token may send only `sku`, `barcode`, `price_mnt`, `stock_qty` and `version`.**
        Any other field — `cost_mnt` above all — is refused with `validation_error` and the
        offending `field`. Fields the body omits are left alone, so a partial patch is safe.
        A console session, by contrast, replaces the whole variant.

        `version` is optimistic locking: send the one you read and a concurrent edit answers
        `409`. Omit it and the current version is used.
      security:
        - apiKey: []
        - appOAuth: [product:write]
        - session: []
      parameters:
        - name: id
          in: path
          required: true
          description: Variant id.
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/VariantPatch' }
      responses:
        '200':
          description: The stored variant. `cost_mnt` is absent for a keyed caller.
          headers:
            X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Variant' }
        '400':
          description: A field is not acceptable, or an API key sent a console-only field.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                forbiddenField:
                  value: { error: "энэ талбарыг API түлхүүрээр өөрчлөх боломжгүй: cost_mnt", code: validation_error, field: cost_mnt }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: The variant changed under you (`version` mismatch), or the SKU is taken.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  # ───────────────────────────── Integration console ─────────────────────────────
  /shop/api-keys:
    get:
      tags: [Integration console]
      operationId: listAPIKeys
      summary: List the shop's API keys
      description: Revoked keys are included — the list is the history. Requires a console session with `integration:manage`; an API key may never call this.
      security:
        - session: []
      responses:
        '200':
          description: Every key this shop has ever minted.
          content:
            application/json:
              schema:
                type: object
                required: [keys]
                properties:
                  keys:
                    type: array
                    items: { $ref: '#/components/schemas/APIKey' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

    post:
      tags: [Integration console]
      operationId: createAPIKey
      summary: Mint an API key
      description: |
        **The plaintext secret is returned exactly once.** Afterwards only the display prefix
        remains. Scopes are immutable: rotation means minting a new key and revoking the old
        one.

        Two limits apply. A key may only carry `product:read`, `product:write`,
        `product:delete`, `order:read`, `order:write` — never a permission that administers
        people or credentials. And an actor may only put on a key the permissions they hold
        themselves (the grant ceiling).
      security:
        - session: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, scopes]
              properties:
                name:
                  type: string
                  description: Display name, clamped to 60 characters.
                  maxLength: 60
                scopes:
                  type: array
                  minItems: 1
                  items: { $ref: '#/components/schemas/KeyScope' }
      responses:
        '201':
          description: The key, with its secret shown for the only time.
          content:
            application/json:
              schema:
                type: object
                required: [key, secret]
                properties:
                  key: { $ref: '#/components/schemas/APIKey' }
                  secret:
                    type: string
                    description: "`osk_live_<43 chars>` (`osk_test_` in development). Store it now."
                    examples: ["osk_live_7Nq2rX9mB4tV1kZ8cY6wP3sL0hJ5dF2gA7nQ1eR4uT8"]
        '400':
          description: The name is empty, or a scope may never be granted to a key.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                scopeInvalid:
                  value: { error: API түлхүүрт олгох боломжгүй эрх байна, code: api_key_scope_invalid }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '409':
          description: The shop already holds the maximum number of live keys.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                limit:
                  value: { error: Түлхүүрийн тоо дээд хэмжээндээ хүрсэн байна, code: api_key_limit_reached }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/api-keys/scopes:
    get:
      tags: [Integration console]
      operationId: listAPIKeyScopes
      summary: List the scopes this actor may grant
      description: The closed key-scope allow-list intersected with what the caller holds, with display labels — so the console never renders a checkbox that cannot be ticked.
      security:
        - session: []
      responses:
        '200':
          description: The grantable scopes.
          content:
            application/json:
              schema:
                type: object
                required: [scopes]
                properties:
                  scopes:
                    type: array
                    items:
                      type: object
                      required: [key, label, category]
                      properties:
                        key: { $ref: '#/components/schemas/KeyScope' }
                        label: { type: string, description: Mongolian display name. }
                        category: { type: string }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/api-keys/{id}:
    delete:
      tags: [Integration console]
      operationId: revokeAPIKey
      summary: Revoke an API key
      description: Immediate — the very next request presenting it is `401`.
      security:
        - session: []
      parameters:
        - name: id
          in: path
          required: true
          description: Key id.
          schema: { type: string, format: uuid }
      responses:
        '204': { description: Revoked. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundCoded' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/storefront/history:
    get:
      tags: [Storefront design]
      operationId: listStorefrontHistory
      summary: List the shop's design publish history
      description: |
        Every published write of the shop's design (console publish, theme switch, the create
        wizard's preset) leaves a snapshot; the newest 20 per shop are kept, newest first.
        Design data only. Requires a console session with `product:write`.
      security:
        - session: []
      responses:
        '200':
          description: The snapshots, newest first (an empty list, never null).
          content:
            application/json:
              schema:
                type: object
                required: [history]
                properties:
                  history:
                    type: array
                    maxItems: 20
                    items: { $ref: '#/components/schemas/StorefrontPublish' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/storefront/history/{id}/restore:
    post:
      tags: [Storefront design]
      operationId: restoreStorefrontHistory
      summary: Load a past design into the server draft
      description: |
        Replaces the shop's server-kept design **draft** with the snapshot (based on the live
        version, so it is not stale). The live storefront never changes here — the merchant
        reviews the draft and publishes it like any edit. Audited as
        `storefront.history_restore`. Requires a console session with `product:write`.
      security:
        - session: []
      parameters:
        - name: id
          in: path
          required: true
          description: Snapshot id from the history list.
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The new draft (the same shape `GET /shop/storefront/draft` returns).
          content:
            application/json:
              schema:
                type: object
                required: [draft]
                properties:
                  draft:
                    type: object
                    additionalProperties: true
                    description: |
                      template_id, tokens, sections, announcement, logo_url, base_version, updated_at,
                      translations, stale, issues. `issues` = the custom blocks' values that block
                      publishing (kept in the draft; `[]` when none): each `{id, key, element?, field?,
                      locale?, code, message}`, codes `custom.*` (openshop-web contract home-blocks.json).
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundPlain' }
        '409':
          description: The snapshot's theme was removed, or it no longer passes today's design checks.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                notRestorable:
                  value: { error: Энэ хувилбарыг сэргээх боломжгүй, code: history_not_restorable }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks:
    get:
      tags: [Integration console]
      operationId: listWebhooks
      summary: List the shop's webhook endpoints
      description: Every endpoint this shop has registered, with its health counters. Secrets are never returned.
      security:
        - session: []
      responses:
        '200':
          description: The registered endpoints.
          content:
            application/json:
              schema:
                type: object
                required: [endpoints]
                properties:
                  endpoints:
                    type: array
                    items: { $ref: '#/components/schemas/WebhookEndpoint' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

    post:
      tags: [Integration console]
      operationId: createWebhook
      summary: Register a webhook endpoint
      description: |
        **The signing secret is returned exactly once.** The URL must be `https` and must
        resolve to a public address — private, loopback and link-local targets are refused
        (`webhook_url_invalid`), and the same check runs again at dial time.

        `ping` is not subscribable; it is only ever produced by the console's test button.
      security:
        - session: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url: { type: string, format: uri, maxLength: 2048 }
                description: { type: string, maxLength: 200 }
                events:
                  type: array
                  minItems: 1
                  items: { $ref: '#/components/schemas/WebhookEventType' }
      responses:
        '201':
          description: The endpoint, with its secret shown for the only time.
          content:
            application/json:
              schema:
                type: object
                required: [endpoint, secret]
                properties:
                  endpoint: { $ref: '#/components/schemas/WebhookEndpoint' }
                  secret: { type: string, description: The HMAC signing secret. Store it now. }
        '400':
          description: The URL or the event list is not acceptable.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                urlInvalid:
                  value: { error: Хаяг https:// байх ба нийтэд нээлттэй сервер рүү заасан байх ёстой, code: webhook_url_invalid }
                eventsInvalid:
                  value: { error: Дор хаяж нэг зөв үйл явдал сонгоно уу, code: webhook_events_invalid }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '409':
          description: The shop already has the maximum number of endpoints (5).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                limit:
                  value: { error: Endpoint-ийн тоо дээд хэмжээндээ хүрсэн байна, code: webhook_limit_reached }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks/events:
    get:
      tags: [Integration console]
      operationId: listWebhookEventTypes
      summary: List the subscribable event catalog
      description: Display-ready — the console renders what this returns and keeps no label map of its own.
      security:
        - session: []
      responses:
        '200':
          description: Every event type, with Mongolian names.
          content:
            application/json:
              schema:
                type: object
                required: [events]
                properties:
                  events:
                    type: array
                    items:
                      type: object
                      required: [key, label, description, group, group_label, since]
                      properties:
                        key: { $ref: '#/components/schemas/WebhookEventKeyOrPing' }
                        label: { type: string }
                        description: { type: string }
                        group:
                          type: string
                          description: The console heading the event sits under (extensible).
                          x-extensible-enum: [orders, products, customers, gift_cards, bookings, reviews, payment_links, surveys, other]
                        group_label: { type: string }
                        since:
                          type: string
                          description: The catalogue version that introduced the event (`2026-09`, `2026-11`).
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks/{id}:
    patch:
      tags: [Integration console]
      operationId: patchWebhook
      summary: Update a webhook endpoint
      description: Omitted fields are left alone. Setting `status` back to `active` is how a merchant revives an auto-disabled endpoint.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/WebhookId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                url: { type: string, format: uri, maxLength: 2048 }
                description: { type: string, maxLength: 200 }
                events:
                  type: array
                  minItems: 1
                  items: { $ref: '#/components/schemas/WebhookEventType' }
                status:
                  type: string
                  enum: [active, disabled]
      responses:
        '200':
          description: The updated endpoint.
          content:
            application/json:
              schema:
                type: object
                required: [endpoint]
                properties:
                  endpoint: { $ref: '#/components/schemas/WebhookEndpoint' }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundCoded' }
        '500': { $ref: '#/components/responses/InternalError' }

    delete:
      tags: [Integration console]
      operationId: deleteWebhook
      summary: Delete a webhook endpoint
      description: Removes the endpoint and stops all future deliveries to it. Its delivery log goes with it — disable the endpoint instead if you want to keep the history.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/WebhookId'
      responses:
        '204': { description: Deleted. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundCoded' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks/{id}/rotate:
    post:
      tags: [Integration console]
      operationId: rotateWebhookSecret
      summary: Rotate an endpoint's signing secret
      description: |
        Mints a new secret and keeps the previous one valid for an overlap window (24 hours,
        `prev_valid_hours`), during which every delivery carries **two** `v1` signatures —
        so the receiver can be redeployed without losing a delivery: deploy the new secret,
        then the old one stops verifying at `prev_expires_at`. The new secret is returned
        **once**, here; afterwards the console only shows its last four characters
        (`secret_last4`). A credential change: needs a recent sign-in (403 `reauth_required`
        otherwise). Audited; the secret is never logged.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/WebhookId'
      responses:
        '200':
          description: The new secret and when the old one stops verifying.
          content:
            application/json:
              schema:
                type: object
                required: [secret, prev_expires_at, prev_valid_hours]
                properties:
                  secret: { type: string }
                  prev_expires_at: { type: string, format: date-time }
                  prev_valid_hours: { type: integer }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundCoded' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks/{id}/test:
    post:
      tags: [Integration console]
      operationId: testWebhook
      summary: Queue a test delivery
      description: |
        Queues a `ping` through the ordinary dispatcher, so a passing test proves the whole
        chain rather than a special case. Five per minute per endpoint.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/WebhookId'
      responses:
        '202':
          description: Queued. Follow it in the delivery log.
          content:
            application/json:
              schema:
                type: object
                required: [delivery_id]
                properties:
                  delivery_id: { type: string, format: uuid }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundCoded' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks/{id}/deliveries:
    get:
      tags: [Integration console]
      operationId: listWebhookDeliveries
      summary: Read an endpoint's delivery log
      description: The log is history — a replay never rewrites an existing row. An unknown `status` filter simply shows everything.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/WebhookId'
        - name: status
          in: query
          required: false
          schema: { $ref: '#/components/schemas/DeliveryStatus' }
      responses:
        '200':
          description: The deliveries.
          content:
            application/json:
              schema:
                type: object
                required: [deliveries]
                properties:
                  deliveries:
                    type: array
                    items: { $ref: '#/components/schemas/WebhookDelivery' }
                  replayable:
                    type: integer
                    description: How many deliveries a bulk replay (`POST /shop/webhooks/{id}/replay`) would move right now.
                  replay_limit:
                    type: integer
                    description: The most one bulk replay request moves (100).
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks/{id}/replay:
    post:
      tags: [Integration console]
      operationId: bulkReplayWebhookDeliveries
      summary: Replay failed and dead deliveries in bulk
      description: |
        For the day after an outage. `dead` deliveries get a **new** replay row each (the
        original is untouched and the replay keeps its `X-OpenShop-Event-Id`); `failed`
        deliveries are already scheduled for retry, so they are pulled forward to "now" instead
        of being copied — nothing is ever sent twice by this call.

        * Per original event at most one replay, and none while that event still has a
          delivery pending, retrying or already delivered. Pressing twice queues nothing new.
        * At most **100** rows per request; `remaining` says how many are left for the next one.
        * One bulk replay per endpoint per minute (`429 rate_limited`), and only into an
          `active` endpoint (`409 webhook_endpoint_inactive`).
        * Audited as `shop.webhook.replay_bulk`.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/WebhookId'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                status:
                  type: string
                  enum: [dead, failed, all]
                  description: Which deliveries to move. Omitted or `all` = both.
                since: { type: string, format: date-time, description: Only deliveries created at or after this moment. }
                until: { type: string, format: date-time, description: Only deliveries created before this moment. }
                limit: { type: integer, minimum: 1, maximum: 100, description: Defaults to 100. }
      responses:
        '202':
          description: Queued.
          content:
            application/json:
              schema:
                type: object
                required: [queued, retried, remaining]
                properties:
                  queued: { type: integer, description: New replay rows (from dead deliveries). }
                  retried: { type: integer, description: Failed deliveries pulled forward to retry now. }
                  remaining: { type: integer, description: Still eligible after this request. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundCoded' }
        '409':
          description: The endpoint is disabled or auto-disabled — re-enable it first.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                inactive:
                  value: { error: Endpoint идэвхгүй байна — эхлээд идэвхжүүлээд дараа нь дахин илгээнэ үү, code: webhook_endpoint_inactive }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  /shop/webhooks/{id}/deliveries/{did}/replay:
    post:
      tags: [Integration console]
      operationId: replayWebhookDelivery
      summary: Replay a delivery
      description: |
        Queues a **new** delivery with the same payload and `X-OpenShop-Event-Id`, pointing back
        at the original. The original row is untouched. Refused (`409 webhook_replay_in_flight`)
        while any delivery of the same event is pending, being sent or waiting for a retry — it
        would otherwise arrive twice. Re-sending an already delivered event is allowed.
      security:
        - session: []
      parameters:
        - $ref: '#/components/parameters/WebhookId'
        - name: did
          in: path
          required: true
          description: The delivery to replay.
          schema: { type: string, format: uuid }
      responses:
        '202':
          description: Queued.
          content:
            application/json:
              schema:
                type: object
                required: [delivery_id]
                properties:
                  delivery_id: { type: string, format: uuid }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/UnauthorizedPlain' }
        '403': { $ref: '#/components/responses/ForbiddenPlain' }
        '404': { $ref: '#/components/responses/NotFoundCoded' }
        '409':
          description: A delivery of this event is still pending or retrying.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                inFlight:
                  value: { error: Энэ үйл явдлын илгээлт хүлээгдэж/дахин оролдогдож байна — дуусахыг хүлээнэ үү, code: webhook_replay_in_flight }
        '500': { $ref: '#/components/responses/InternalError' }

  # ───────────────────────────── Connector (Buildry Chat) ─────────────────────────────
  /connector/chat/tenants:
    get:
      tags: [Connector]
      operationId: connectorSearchTenants
      summary: Search shops available for pairing
      description: |
        Served on `api.openshop.mn` only. Every call must carry `X-Connector-Id: buildry_chat`
        and a valid `X-Connector-Signature`; the whole surface answers `404` until the shared
        secret is configured on this side.
      security:
        - connectorHmac: []
      parameters:
        - $ref: '#/components/parameters/ConnectorIdRequired'
        - $ref: '#/components/parameters/ConnectorSignatureRequired'
        - name: q
          in: query
          description: Shop id, handle or name.
          required: false
          schema: { type: string }
        - name: limit
          in: query
          description: 1–50. Default 20.
          required: false
          schema: { type: integer, minimum: 1, maximum: 50, default: 20 }
      responses:
        '200':
          description: Matching shops.
          content:
            application/json:
              schema:
                type: object
                required: [tenants]
                properties:
                  tenants:
                    type: array
                    items: { $ref: '#/components/schemas/ConnectorTenant' }
        '401': { $ref: '#/components/responses/ConnectorUnauthorized' }
        '404': { $ref: '#/components/responses/ConnectorDisabled' }
        '500': { $ref: '#/components/responses/ConnectorInternal' }

  /connector/chat/links:
    post:
      tags: [Connector]
      operationId: connectorCreateLink
      summary: Create (or confirm) a pairing
      description: |
        Idempotent on `link_id`: replaying the same link answers `200` with the stored row,
        while a first write answers `201`. The shop may be named by `tenant_id` or by
        `tenant_slug`.
      security:
        - connectorHmac: []
      parameters:
        - $ref: '#/components/parameters/ConnectorIdRequired'
        - $ref: '#/components/parameters/ConnectorSignatureRequired'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ConnectorLinkRequest' }
      responses:
        '200':
          description: The pairing already existed and is unchanged.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectorLink' }
        '201':
          description: The pairing was created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectorLink' }
        '400':
          description: A field is malformed.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectorError' }
              examples:
                invalidLinkId: { value: { error: invalid_link_id } }
                invalidWorkspaceId: { value: { error: invalid_workspace_id } }
                invalidLinkedBy: { value: { error: invalid_linked_by } }
                invalidBody: { value: { error: invalid_body } }
        '401': { $ref: '#/components/responses/ConnectorUnauthorized' }
        '404':
          description: No such shop — or the connector surface is switched off.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectorError' }
              examples:
                tenantNotFound: { value: { error: tenant_not_found } }
        '409':
          description: The shop is not active, or it is already linked to another workspace.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectorError' }
              examples:
                tenantInactive: { value: { error: tenant_inactive } }
                alreadyLinked: { value: { error: already_linked_elsewhere } }
        '413': { $ref: '#/components/responses/ConnectorBodyTooLarge' }
        '500': { $ref: '#/components/responses/ConnectorInternal' }

  /connector/chat/links/{link_id}:
    get:
      tags: [Connector]
      operationId: connectorGetLink
      summary: Read a pairing
      description: The pairing as we hold it, so the connector can detect drift between the two sides.
      security:
        - connectorHmac: []
      parameters:
        - $ref: '#/components/parameters/ConnectorIdRequired'
        - $ref: '#/components/parameters/ConnectorSignatureRequired'
        - $ref: '#/components/parameters/LinkId'
      responses:
        '200':
          description: The pairing.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectorLink' }
        '401': { $ref: '#/components/responses/ConnectorUnauthorized' }
        '404': { $ref: '#/components/responses/ConnectorLinkNotFound' }
        '500': { $ref: '#/components/responses/ConnectorInternal' }

    delete:
      tags: [Connector]
      operationId: connectorDeleteLink
      summary: Unlink a pairing
      description: |
        Idempotent: unlinking an already-unlinked pairing answers `200` with the row as it
        stands. The row is never deleted — it is marked `unlinked`, so the history survives.
      security:
        - connectorHmac: []
      parameters:
        - $ref: '#/components/parameters/ConnectorIdRequired'
        - $ref: '#/components/parameters/ConnectorSignatureRequired'
        - $ref: '#/components/parameters/LinkId'
      responses:
        '200':
          description: The unlinked pairing.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ConnectorLink' }
        '401': { $ref: '#/components/responses/ConnectorUnauthorized' }
        '404': { $ref: '#/components/responses/ConnectorLinkNotFound' }
        '500': { $ref: '#/components/responses/ConnectorInternal' }

# ───────────────────────────── Outgoing webhooks ─────────────────────────────
  # ───────────────────────────── Apps (X9 Phase A) ─────────────────────────────
  /oauth2/token:
    servers:
      - url: https://id.openshop.mn
        description: The identity host issues every token.
    post:
      tags: [Apps]
      operationId: appToken
      summary: Exchange an install code, or rotate a refresh token
      description: |
        `grant_type=authorization_code` redeems the code the install page returned (with
        `code_verifier`, the exact `redirect_uri` and client authentication).
        `grant_type=refresh_token` with an `osr_…` token rotates the pair; presenting a spent
        refresh token revokes every token of the installation (`invalid_grant`). Errors use
        the RFC 6749 `{error, error_description}` shape, not the API envelope.
      security:
        - appOAuth: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [grant_type]
              properties:
                grant_type: { type: string, enum: [authorization_code, refresh_token] }
                code: { type: string }
                redirect_uri: { type: string, format: uri }
                code_verifier: { type: string }
                refresh_token: { type: string }
                client_id: { type: string }
                client_secret: { type: string }
      responses:
        '200':
          description: A fresh token pair for one installation.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AppTokenResponse' }
        '400':
          description: RFC 6749 error (`invalid_grant`, `invalid_request`, `unsupported_grant_type`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthError' }
        '401':
          description: Client authentication failed (`invalid_client`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthError' }
        '429':
          description: More than 60 token calls a minute from this client (`slow_down`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthError' }

  /oauth2/revoke:
    servers:
      - url: https://id.openshop.mn
        description: The identity host.
    post:
      tags: [Apps]
      operationId: revokeToken
      summary: Revoke an app token (RFC 7009)
      description: |
        Revokes an `osa_…` or `osr_…` token of the authenticated client (a refresh token takes
        every token rotated from it along). Always `200` — an unknown, foreign or already dead
        token is indistinguishable from a successful revocation.
      security:
        - appOAuth: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [token]
              properties:
                token: { type: string }
                token_type_hint: { type: string, enum: [access_token, refresh_token] }
                client_id: { type: string }
                client_secret: { type: string }
      responses:
        '200':
          description: Revoked (or nothing to revoke).
        '401':
          description: Client authentication failed (`invalid_client`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthError' }

  /shop/apps:
    get:
      tags: [Integration console]
      operationId: listShopApps
      summary: Installed apps and the app directory
      description: |
        The console's «Апп» section: the shop's active installations (display-ready scope
        labels, who installed, last use, webhook health) and the listed directory, each entry
        flagged `installed`. Requires `integration:manage`; browser session only.
      security:
        - session: []
      responses:
        '200':
          description: Installed apps + directory.
          content:
            application/json:
              schema:
                type: object
                required: [installed, directory]
                properties:
                  installed:
                    type: array
                    items: { type: object }
                  directory:
                    type: array
                    items: { type: object }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404':
          description: Apps are not enabled on this deployment.

  /shop/apps/{id}:
    delete:
      tags: [Integration console]
      operationId: uninstallShopApp
      summary: Uninstall an app from the shop
      description: |
        Every token of the installation dies at once, queued deliveries are dropped, the
        app-managed webhook endpoint is switched off, and one final `app.uninstalled` is sent
        to the app. Requires `integration:manage`; browser session only.
      security:
        - session: []
      parameters:
        - name: id
          in: path
          required: true
          description: The installation id.
          schema: { type: string, format: uuid }
      responses:
        '204':
          description: Uninstalled.
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404':
          description: No active installation with this id on this shop.

webhooks:
  openshopEvent:
    post:
      tags: [Integration console]
      operationId: receiveOpenShopEvent
      summary: An event OpenShop delivers to a merchant's endpoint
      description: |
        This is the request **we** make to the URL registered at `POST /shop/webhooks`.

        * **At-least-once, no ordering guarantee.** The same event may arrive twice and two
          events may arrive out of order. Deduplicate on `X-OpenShop-Event-Id`, and treat
          `GET /shop/orders/{id}` as the final truth — an `order.expired` can legitimately be
          followed by an `order.paid` when a buyer pays late.
        * **Verify before parsing.** Compute
          `HMAC-SHA256(secret, t + "." + rawBody)` over the **raw** body and compare it to a
          `v1` value in `X-OpenShop-Signature`. Reject a `t` more than five minutes from your
          clock. During a secret rotation the header carries two `v1` values; either matching
          is valid.
        * **Answer 2xx fast.** The request times out after 10 seconds and we read at most
          64 KiB of your response. Acknowledge first, work afterwards.
        * **Retries.** 5xx, 408, 429 and timeouts are retried after roughly
          1m · 5m · 30m · 2h · 6h · 12h · 24h (±20 % jitter), 8 attempts, about 45 hours in
          total. Any other 4xx stops immediately — repeating a request you called malformed
          changes nothing. `410 Gone` disables the endpoint at once; 50 consecutive failures
          disables it too.
        * **The payload is thin and carries no personal data** — no name, phone, address or
          email. Fetch what you need with your API key.
      parameters:
        - name: X-OpenShop-Event-Id
          in: header
          required: false
          description: Stable id of the **event**. Deduplicate on this. Absent on a console `ping`.
          schema: { type: string, format: uuid }
        - name: X-OpenShop-Delivery-Id
          in: header
          required: true
          description: Id of this **attempt's** delivery row. Differs between a delivery and its replay.
          schema: { type: string, format: uuid }
        - name: X-OpenShop-Event-Type
          in: header
          required: true
          schema: { $ref: '#/components/schemas/WebhookEventTypeOrPing' }
        - name: X-OpenShop-Api-Version
          in: header
          required: true
          description: The payload version (same value as the body's `api_version`).
          schema: { type: string, example: "2026-09" }
        - name: X-OpenShop-Signature
          in: header
          required: true
          description: "`t=<unix seconds>,v1=<hex>` — a second `v1` is appended during a secret rotation."
          schema: { type: string }
          examples:
            single:
              value: t=1750000000,v1=06f35f44b88eceb2f2df6696c68710a8265597b7ca7d225a71d588159757f0d9
        - name: User-Agent
          in: header
          required: true
          schema: { type: string, const: "OpenShop-Webhooks/1.0 (+https://openshop.mn)" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WebhookPayload' }
      responses:
        '200':
          description: Any 2xx means "received". Nothing in the body is read.

  openshopAppEvent:
    post:
      tags: [Apps]
      operationId: receiveOpenShopAppEvent
      summary: An event OpenShop delivers to an app's webhook URL
      description: |
        Same transport, retries and signature scheme as `openshopEvent`, with three
        differences: the signature uses the **app's** webhook secret (one for every
        installation); `X-OpenShop-Installation-Id` and `X-OpenShop-Shop` say which shop the
        event is about; and an installation only receives the events its scopes allow
        (`order.*` needs `order:read`, `product.*` needs `product:read`).

        `app.uninstalled` (data: `installation_id`, `uninstalled_at`) is sent when the merchant
        removes the app. From then on every token of that installation is dead — delete the
        shop's data within 30 days.
      parameters:
        - name: X-OpenShop-Installation-Id
          in: header
          required: true
          schema: { type: string, format: uuid }
        - name: X-OpenShop-Shop
          in: header
          required: true
          description: The shop slug.
          schema: { type: string }
        - name: X-OpenShop-Event-Type
          in: header
          required: true
          schema:
            oneOf:
              - $ref: '#/components/schemas/WebhookEventType'
              - type: string
                const: app.uninstalled
        - name: X-OpenShop-Api-Version
          in: header
          required: true
          description: The payload version (same value as the body's `api_version`).
          schema: { type: string, example: "2026-09" }
        - name: X-OpenShop-Signature
          in: header
          required: true
          description: "`t=<unix seconds>,v1=<hex>` over the raw body with the app's webhook secret."
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WebhookPayload' }
      responses:
        '200':
          description: Any 2xx means "received".

components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      bearerFormat: osk_live_<43 chars>
      description: |
        A per-shop API key: `Authorization: Bearer osk_live_…` (`osk_test_…` in development).
        The key names its own shop, so it works on `api.openshop.mn` where there is no shop in
        the hostname. Presenting a key on **another** shop's host is refused with
        `invalid_api_key` — the same answer as an unknown key, so nothing is learned about
        which shop it belongs to. Every request runs under that shop's row-level security:
        another shop's data can never come back.

        Budgets are per key, never per address: 600 reads and 120 writes a minute.
    session:
      type: apiKey
      in: cookie
      name: os_session
      description: |
        The merchant console's browser session, issued by `id.openshop.mn`. Permissions are
        resolved from the signed-in person's role in this shop. Only the console surface
        requires it; it is listed on other operations because a console page may call them
        too. In production the browser holds it as `__Secure-os_session` (BL-44); the
        legacy `os_session` name is still written and accepted during the transition.
    connectorHmac:
      type: apiKey
      in: header
      name: X-Connector-Signature
      description: |
        The Buildry Chat connector's shared-secret signature, paired with
        `X-Connector-Id: buildry_chat`.

        `X-Connector-Signature: t=<unix seconds>,v1=<hex>` where
        `v1 = HMAC-SHA256(secret, t + "." + METHOD + " " + PATH + "." + rawBody)`. `PATH` is
        the public path with no query string; binding the method and path stops a captured
        signature being replayed against another endpoint. A timestamp more than five minutes
        from our clock is refused.

    appOAuth:
      type: oauth2
      description: |
        A third-party app installed on one shop (X9 Phase A). OAuth 2.0 authorization code
        with **PKCE S256 mandatory**, a confidential client (`client_secret` via HTTP Basic or
        form) and an exact-match `redirect_uri`. Apps are registered by OpenShop or in the
        self-serve developer portal (a draft app installs only on its developer's own shops,
        and its install page says so — "Хөгжүүлэлтийн горим"); the merchant
        picks the shop and consents to **all** requested scopes on `id.openshop.mn/install`
        (the installer can only grant permissions they hold themselves).

        * `scope` = space-separated permission keys from the table below; OIDC scopes
          (`openid`, `profile`, …) are refused. Optional `shop=<slug>` hints the shop; an app
          already installed with the requested scopes gets a code without a second consent.
        * The token response is `{access_token: "osa_live_…", token_type: "Bearer",
          expires_in: 3600, refresh_token: "osr_live_…", scope, installation_id,
          shop: {id, slug, name}}` — never an `id_token`.
        * **Refresh tokens rotate.** Each use returns a new pair; presenting a spent refresh
          token again is treated as theft and revokes **every** token of that installation.
          A refresh token unused for 90 days expires.
        * `POST /oauth2/revoke` (RFC 7009, client-authenticated) revokes an access or refresh
          token (a refresh token takes its successors with it); it always answers `200`.
        * The token names its shop: call `api.openshop.mn/v1/shop/*` (or the shop's own host).
          On another shop's host, or once the merchant uninstalls the app or OpenShop
          suspends it, every call answers `401 invalid_token` — at the very next request.
        * Budgets: 600 reads and 120 writes a minute per installation, plus 6000 a minute
          across all installations of one app.
        * Webhooks: an app with a webhook URL gets one endpoint per installation, filtered by
          the installation's scopes, signed with the **app's** secret and tagged with
          `X-OpenShop-Installation-Id` and `X-OpenShop-Shop`. `app.uninstalled` arrives when
          a merchant removes the app — delete that shop's data within 30 days.
      x-pkce-required: true
      flows:
        authorizationCode:
          authorizationUrl: https://id.openshop.mn/oauth2/authorize
          tokenUrl: https://id.openshop.mn/oauth2/token
          refreshUrl: https://id.openshop.mn/oauth2/token
          scopes:
            product:read: Read the catalog, drafts included.
            product:write: Update variant price and stock.
            product:delete: Delete catalog content (sensitive — justified in review).
            order:read: Read orders, without buyer contact details.
            order:write: Mark orders shipped (courier + tracking) and fulfilled / undo.
            customer:read: Buyer name, phone, delivery address, РД and B2B ТТД on orders (sensitive — justified in review, data location disclosed at install).
      x-scopes:
        - { key: product:read, sensitive: false }
        - { key: product:write, sensitive: false }
        - { key: product:delete, sensitive: true }
        - { key: order:read, sensitive: false }
        - { key: order:write, sensitive: false }
        - { key: customer:read, sensitive: true }

  parameters:
    ContentLang:
      name: lang
      in: query
      required: false
      description: |
        Content language of the merchant's text (`mn` | `en`). Applied only when the shop
        has that language turned on (`storefront_locales`); otherwise the shop's
        `default_locale`. Each field falls back to the Mongolian source when it has no
        translation; `locale` in the response names the language served. Without it (or
        `X-OS-Content-Locale`) the Mongolian source fields are returned. An unsupported
        value is ignored. On this API it also sets the language of labels and errors.
      schema: { type: string, enum: [mn, en] }
    ContentLocaleHeader:
      name: X-OS-Content-Locale
      in: header
      required: false
      description: Same as `?lang=` for the merchant's text, as a header (`?lang=` wins).
      schema: { type: string, enum: [mn, en] }
    IfNoneMatch:
      name: If-None-Match
      in: header
      required: false
      description: The `ETag` from an earlier response. When it still matches, the answer is `304` with no body.
      schema: { type: string }
    Limit:
      name: limit
      in: query
      required: false
      description: Page size.
      schema: { type: integer, minimum: 1, default: 20 }
    Offset:
      name: offset
      in: query
      required: false
      description: Rows to skip.
      schema: { type: integer, minimum: 0, default: 0 }
    ProductId:
      name: id
      in: path
      required: true
      description: Product id.
      schema: { type: string, format: uuid }
    OrderId:
      name: id
      in: path
      required: true
      description: Order id.
      schema: { type: string, format: uuid }
    PayableId:
      name: id
      in: path
      required: true
      description: Payment-link id — a capability token.
      schema: { type: string, format: uuid }
    WebhookId:
      name: id
      in: path
      required: true
      description: Webhook endpoint id.
      schema: { type: string, format: uuid }
    LinkId:
      name: link_id
      in: path
      required: true
      description: Pairing id, chosen by the connector.
      schema: { type: string, format: uuid }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: |
        Optional. A client-chosen key, 1–255 printable ASCII characters (a UUIDv4 is the
        obvious choice), that makes a retry safe.

        The first request with a key runs; its **successful** response is remembered for 24
        hours and replayed verbatim — same status, same body, plus `Idempotent-Replayed: true`
        — to any later request that presents the same key **and the same body**. Same key with
        a different body is refused `422 idempotency_key_reuse`. A request that arrives while
        the first is still running is refused `409 idempotency_in_progress`; retry in a
        second. A first attempt that **failed** releases the key, so you may fix your request
        and reuse it.

        Scope is per shop **and per caller** — the API key, the app installation or the
        signed-in user that made the first request; another caller with the same key is
        processed on its own. Authentication and permission checks run before any replay. The
        record lives in a cache with a 24-hour lifetime, not in the
        order transaction: it removes the ordinary duplicate — a retried POST after a
        timeout, a double tap — and it degrades open if the cache is unavailable. Do not rely
        on it as a distributed lock.
      schema: { type: string, minLength: 1, maxLength: 255 }
    ConnectorId:
      name: X-Connector-Id
      in: header
      required: false
      description: Present only on connector traffic. Its presence is what makes the signature mandatory.
      schema: { type: string, const: buildry_chat }
    ConnectorSignature:
      name: X-Connector-Signature
      in: header
      required: false
      description: Required whenever `X-Connector-Id` is present. See the `connectorHmac` security scheme.
      schema: { type: string }
    ConnectorIdRequired:
      name: X-Connector-Id
      in: header
      required: true
      schema: { type: string, const: buildry_chat }
    ConnectorSignatureRequired:
      name: X-Connector-Signature
      in: header
      required: true
      description: See the `connectorHmac` security scheme.
      schema: { type: string }

  headers:
    RateLimitLimit:
      description: The bucket's size, in requests per minute. Sent only to a caller presenting an API key.
      schema: { type: integer }
    RateLimitRemaining:
      description: Requests left in the current window. Sent only to a caller presenting an API key.
      schema: { type: integer }
    RateLimitReset:
      description: Seconds until the window resets. Sent only to a caller presenting an API key.
      schema: { type: integer }
    RetryAfter:
      description: Seconds to wait before retrying.
      schema: { type: integer }
    IdempotentReplayed:
      description: "`true` when this response was replayed from an earlier request with the same `Idempotency-Key`."
      schema: { type: string, const: "true" }
    FeedETag:
      description: The generation stamp of this feed body. Send it back as `If-None-Match`.
      schema: { type: string }
    FeedCacheControl:
      description: Always `public, max-age=300` — the feed is regenerated at most every five minutes.
      schema: { type: string }
    FeedDisposition:
      description: "`inline; filename=\"<slug>-feed.csv\"` (or `.xml`)."
      schema: { type: string }

  responses:
    FeedNotModified:
      description: The `If-None-Match` value still matches the cached feed. No body; `ETag` and `Cache-Control` are repeated.
      headers:
        ETag: { $ref: '#/components/headers/FeedETag' }
        Cache-Control: { $ref: '#/components/headers/FeedCacheControl' }
    BadRequest:
      description: The request is malformed. Plain envelope with a message.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    ValidationError:
      description: A path or body value is not acceptable.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            badId:
              value: { error: буруу id, code: validation_error }
    Unauthorized:
      description: No credential was presented.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            unauthorized:
              value: { error: authentication required, code: unauthorized }
    UnauthorizedPlain:
      description: No session cookie.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            unauthorized:
              value: { error: authentication required }
    InvalidAPIKey:
      description: A key was presented and it is unknown, revoked, or bound to another shop.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            invalidKey:
              value: { error: API түлхүүр буруу эсвэл хүчингүй болсон, code: invalid_api_key }
    InsufficientScope:
      description: The caller is authenticated but lacks the permission this route needs. `required_scope` names it.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            insufficientScope:
              value: { error: энэ үйлдэлд эрх хүрэхгүй байна, code: insufficient_scope, required_scope: "order:write" }
    ForbiddenPlain:
      description: The signed-in person lacks `integration:manage` in this shop.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            forbidden:
              value: { error: insufficient permission }
    NotFoundPlain:
      description: No such resource — or one you may not see. Plain envelope.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    NotFoundCoded:
      description: No such resource.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            notFound:
              value: { error: endpoint олдсонгүй, code: not_found }
    RateLimited:
      description: The caller's budget is spent.
      headers:
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
        X-RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
        X-RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
        X-RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            rateLimited:
              value: { error: хэт олон хүсэлт — түр хүлээгээд дахин оролдоно уу, code: rate_limited }
    RateLimitedPlain:
      description: Too many requests from this address. Plain envelope, no `code`.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    IdempotencyKeyReuse:
      description: This `Idempotency-Key` was already used with a different request body.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            reuse:
              value: { error: Энэ Idempotency-Key өөр агуулгатай хүсэлтэд аль хэдийн ашиглагдсан байна., code: idempotency_key_reuse }
    RailUnavailable:
      description: The payment rail rejected the request or was unreachable. Retryable.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            railDown:
              value: { error: Төлбөрийн систем түр алдаа өглөө. Түр хүлээгээд дахин оролдоно уу. }
    InternalError:
      description: Something failed on our side.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    ConnectorUnauthorized:
      description: Wrong peer id, bad signature, or a timestamp outside the ±5-minute window.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ConnectorError' }
          examples:
            invalidSignature: { value: { error: invalid_signature } }
    ConnectorDisabled:
      description: The connector surface is switched off on this deployment (no shared secret).
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ConnectorError' }
    ConnectorLinkNotFound:
      description: No such pairing.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ConnectorError' }
          examples:
            linkNotFound: { value: { error: link_not_found } }
    ConnectorBodyTooLarge:
      description: The body exceeded 64 KiB.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ConnectorError' }
          examples:
            tooLarge: { value: { error: body_too_large } }
    ConnectorInternal:
      description: Something failed on our side.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ConnectorError' }
          examples:
            internal: { value: { error: internal_error } }

  schemas:
    Error:
      type: object
      description: |
        The one error shape. `error` is always present and is human-readable copy — usually
        Mongolian, occasionally English on developer-facing validation. `code` is present
        wherever an integrator is expected to branch, and is the only field you should branch
        on. Some errors carry extra fields alongside (`remaining`, `title`, `required_scope`,
        `field`), which is why this object is open.
      required: [error]
      properties:
        error: { type: string }
        code: { $ref: '#/components/schemas/ErrorCode' }
        remaining:
          type: integer
          description: On `out_of_stock` / `insufficient_stock` — how many units are actually left.
        title:
          type: string
          description: On `out_of_stock` / `insufficient_stock` — the product that blocked the order.
        required_scope:
          type: string
          description: On `insufficient_scope` — the permission the route needs.
        field:
          type: string
          description: On `validation_error` — the field that was refused.
      additionalProperties: true

    ErrorCode:
      type: string
      description: |
        The stable machine-readable error vocabulary. Additive: new values appear, existing
        values are never renamed or repurposed. Treat an unrecognised value as a generic
        failure of its HTTP status class rather than crashing. Declared `x-extensible-enum`
        for exactly that reason: the list grows.
      x-extensible-enum:
        - out_of_stock
        - insufficient_stock
        - promotion_not_stackable
        - payments_not_ready
        - pickup_unavailable
        - delivery_unavailable
        - payable_closed
        - payment_pending
        - rate_limited
        - unauthorized
        - invalid_api_key
        - insufficient_scope
        - api_key_scope_invalid
        - api_key_limit_reached
        - webhook_url_invalid
        - webhook_events_invalid
        - webhook_limit_reached
        - not_found
        - validation_error
        - idempotency_key_invalid
        - idempotency_in_progress
        - idempotency_key_reuse
        - endpoint_sunset
        - invalid_signature
        - connector_required
        - connector_not_linked
        - invalid_token
        - app_route_not_allowed
        - webhook_app_managed
        - webhook_endpoint_inactive
        - webhook_replay_in_flight
        - buyer_email_required
        - digital_qty_invalid
        - already_enrolled
        - module_disabled
        - manual_order_invalid
        - min_order_not_met
        - history_not_restorable

    AppTokenResponse:
      type: object
      required: [access_token, token_type, expires_in, refresh_token, scope, installation_id, shop]
      properties:
        access_token: { type: string, description: "`osa_live_…` — opaque, 1 hour." }
        token_type: { type: string, const: Bearer }
        expires_in: { type: integer, const: 3600 }
        refresh_token: { type: string, description: "`osr_live_…` — rotates on every use; 90 days idle." }
        scope: { type: string, description: Space-separated permission keys actually granted. }
        installation_id: { type: string, format: uuid }
        shop:
          type: object
          required: [id]
          properties:
            id: { type: string, format: uuid }
            slug: { type: string }
            name: { type: string }

    OAuthError:
      type: object
      description: RFC 6749 error body (the OAuth endpoints do not use the API envelope).
      required: [error]
      properties:
        error: { type: string }
        error_description: { type: string }

    ConnectorError:
      type: object
      description: The connector surface answers with the code in the `error` field itself — there is no separate message.
      required: [error]
      properties:
        error: { type: string }

    ContentLocale:
      type: string
      enum: [mn, en]
      description: The language the merchant's text in this response is served in (`mn` = the Mongolian source fields).
    ContentTranslations:
      type: object
      description: Per-language translations of the entity's text fields, keyed by locale (only `en` today) then by field name. Missing fields fall back to the Mongolian source.
      additionalProperties:
        type: object
        additionalProperties: { type: string }
    Product:
      type: object
      required: [id, title, price_mnt, status, images, attributes, created_at]
      properties:
        id: { type: string, format: uuid }
        slug: { type: string, description: Empty when the product has no custom handle. }
        title: { type: string }
        description: { type: string, description: Sanitised HTML. }
        product_type:
          type: string
          enum: [physical, digital, course, service]
        digital_kind:
          type: [string, 'null']
          enum: [file, license_key, null]
          description: Set only for `digital` products — a downloadable file or a code (license/voucher).
        delivery_label:
          type: string
          description: Display-ready badge («Татах файл» / «Цахим код» / «Онлайн курс»); empty for shipped goods.
        delivery_mode:
          type: string
          enum: [download, read, both]
          description: >-
            How a `digital` file product is delivered — `download` (the buyer downloads the files),
            `read` (online reader only, nothing is downloadable) or `both`. Always `download` for every
            other product type.
        delivery_mode_label:
          type: string
          description: Display-ready name of `delivery_mode` («Татаж авах» / «Онлайн унших» / «Онлайн унших + татах»); empty unless a digital file product.
        price_mnt: { type: integer, description: The regular price in tögrög. }
        cargo_fee_mnt: { type: integer, description: Per-product shipping surcharge, added to the order total. }
        category_id: { type: [string, 'null'], format: uuid }
        attributes:
          type: object
          additionalProperties: true
        images:
          type: array
          items: { type: string, format: uri }
        status:
          type: string
          enum: [active, draft]
          description: Drafts are visible only to a caller with `product:write`.
        discount_percent: { type: integer, minimum: 0, maximum: 90 }
        discount_amount_mnt: { type: integer, description: Flat discount. A product uses a percentage **or** an amount, never both. }
        discount_ends_at: { type: string, format: date-time }
        sale_price_mnt:
          type: [integer, 'null']
          description: |
            **The only reliable "is it on sale" signal.** Non-null exactly while a sale window
            is open; the discount fields alone do not tell you that. Use it as the price when
            present.
        discount_basis:
          type: string
          enum: ['', reference, inflated, insufficient, legacy]
          description: |
            Why the strike-through below is (or is not) shown. `reference` = the sale is below the
            lowest price of the 30 days before it began; `inflated` = the price was raised and then
            discounted (no strike, no badge); `insufficient` = too little price history; `legacy` =
            the sale predates price history. Empty when no sale is live.
        reference_price_mnt:
          type: [integer, 'null']
          description: Lowest effective price in the 30 days before the current sale began (null when unknown).
        compare_at_price_mnt:
          type: [integer, 'null']
          description: |
            The honest "was" price to strike through next to `sale_price_mnt`. **Null means show no
            strike and no discount badge** — the sale price still applies.
        sale_badge_visible: { type: boolean, description: '`compare_at_price_mnt` is non-null — a strike and a badge may be shown.' }
        sale_badge_percent: { type: integer, description: 'The −N% badge (percent-mode sales), 0 otherwise.' }
        sale_badge_amount_mnt: { type: integer, description: 'The −N₮ badge (amount-mode sales), 0 otherwise.' }
        sale_badge_label:
          type: string
          description: |
            The badge, worded in the shop's style («-20%», «20% OFF» or «20% хямд»; amount sales
            «-10,000₮» …). Empty when no badge may show. Render it verbatim.
        has_variant_discounts:
          type: boolean
          description: |
            Some variant carries its own discount. The card fields (`sale_price_mnt`,
            `compare_at_price_mnt`, the badge, `savings_mnt`) then describe the variant that is
            cheapest to pay; each variant's own price is on `/products/{id}/variants`.
        sale_range_label:
          type: string
          description: |
            «-30% хүртэл» (shop style) when the variants' visible discounts differ — show it in place
            of `sale_badge_label`. Empty otherwise.
        max_discount_percent:
          type: integer
          description: The largest honest, visible discount on the product or any variant. Hidden discounts never count. 0 = none.
        savings_mnt:
          type: integer
          description: Struck price minus the price paid, only while the badge is visible (and the shop shows savings). 0 otherwise.
        savings_label: { type: string, description: Display-ready «Хэмнэлт 10,000₮», or empty. }
        promo_id: { type: [string, 'null'], format: uuid, description: 'The promotion advertised on this product (2026-11, read-only); null = none.' }
        promo_badge:
          type: string
          description: |
            Display-ready promotion badge — "2+1", "1+1", "2 авбал 3 дахь нь 50%", "Бэлэгтэй"; "" = none.
            Only live promotions that really apply: a product on sale shows none unless the promotion
            includes sale items, and a gift promotion whose gift is out of stock shows none.
        promo_label: { type: string, description: 'The product-page line, e.g. "2 авбал 3 дахь нь үнэгүй · 2026-11-30 хүртэл"; "" = none.' }
        promo_ends_at: { type: [string, 'null'], format: date-time }
        sold_out: { type: boolean, description: Every active variant tracks stock and all are at zero. }
        stock_total: { type: [integer, 'null'], description: Remaining units summed across variants; null when stock is not tracked. }
        recent_paid_count:
          type: integer
          description: Buyers in the last seven days. Only ever ≥ 2 — a single buyer is never exposed. Absent when there is nothing to say.
        rating:
          $ref: '#/components/schemas/ProductRating'
        ebarimt_classification_code: { type: string }
        ebarimt_measure_unit: { type: string }
        ebarimt_tax_type: { type: string }
        ebarimt_tax_product_code: { type: string }
        ebarimt_city_tax: { type: boolean }
        ebarimt_barcode: { type: string }
        featured: { type: boolean }
        featured_position: { type: integer }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time, description: Last edit time (sitemap lastmod). }
        translations:
          $ref: '#/components/schemas/ContentTranslations'
          description: 'The stored translations of `title`, `description` (sanitised HTML) and `preorder_note`, e.g. `{"en": {"title": "Red shirt"}}`; `{}` when none.'
        locale: { $ref: '#/components/schemas/ContentLocale' }

    Variant:
      type: object
      required: [id, product_id, sku, price_mnt, stock_qty, position, is_default, status, version]
      properties:
        id: { type: string, format: uuid }
        product_id: { type: string, format: uuid }
        parent_id: { type: string, format: uuid }
        sku:
          type: string
          description: |
            Unique within the shop. A variant created without one is given a generated
            `SKU-<32 hex>`; treat that shape as "no SKU" rather than showing it to a person.
        barcode: { type: [string, 'null'] }
        price_mnt: { type: integer }
        cost_mnt:
          type: [integer, 'null']
          description: The merchant's buying price. **Never returned to an API key or an anonymous caller** — console sessions with `product:write` only.
        weight_g: { type: [integer, 'null'] }
        image_index: { type: [integer, 'null'], description: Index into the product's `images`. }
        stock_qty:
          type: [integer, 'null']
          description: "`null` = stock is not tracked (effectively unlimited). `0` = sold out."
        position: { type: integer }
        is_default: { type: boolean }
        status: { type: string, enum: [active, archived] }
        version: { type: integer, description: Optimistic-locking counter; send it back on a patch. }
        option_value_ids:
          type: array
          description: Which option values this variant represents.
          items: { type: string, format: uuid }
        discount_percent:
          type: [integer, 'null']
          minimum: 0
          maximum: 90
          description: |
            This variant's own discount, overriding the product's. `discount_percent` and
            `discount_amount_mnt` are both null (the variant inherits the product's sale) or both set
            (the unused one 0; both 0 = this variant is not discounted). The end date is always the
            product's `discount_ends_at`.
        discount_amount_mnt: { type: [integer, 'null'], minimum: 0, description: See `discount_percent`. }
        sale_price_mnt:
          type: [integer, 'null']
          description: What checkout charges for this variant while its sale is live; null otherwise. Use it — never recompute.
        discount_basis: { type: string, enum: ['', reference, inflated, insufficient, legacy], description: As on Product, for this variant. }
        compare_at_price_mnt: { type: [integer, 'null'], description: As on Product, for this variant. }
        sale_badge_visible: { type: boolean }
        sale_badge_label: { type: string, description: This variant's badge in the shop's style; empty when hidden. }
        savings_mnt: { type: integer }
        savings_label: { type: string }
        promo_badge: { type: string, description: 'The product''s promotion badge as it applies to this variant; "" = none.' }

    VariantPatch:
      type: object
      description: |
        For an API key, only the fields below may appear and omitted ones are left alone.
        A console session replaces the variant wholesale and may also send `cost_mnt`,
        `weight_g`, `image_index`, `position` and `status`. The discount pair is merged for
        every caller: omit both to leave it, send either to replace the pair.
      properties:
        sku: { type: string }
        barcode: { type: [string, 'null'] }
        price_mnt: { type: integer, minimum: 0 }
        stock_qty: { type: [integer, 'null'], minimum: 0 }
        discount_percent:
          type: [integer, 'null']
          minimum: 0
          maximum: 90
          description: |
            This variant's own discount — a percent OR an amount (below the variant's price), never
            both. Send both null to make the variant follow the product's sale again.
        discount_amount_mnt: { type: [integer, 'null'], minimum: 0 }
        version: { type: integer, description: The version you last read. Omit to skip the concurrency check. }

    ProductOption:
      type: object
      required: [id, name, position]
      properties:
        id: { type: string, format: uuid }
        name: { type: string, description: 'The axis, e.g. "Өнгө" — in the served content language.' }
        position: { type: integer }
        translations:
          $ref: '#/components/schemas/ContentTranslations'
          description: 'Stored translations of `name`, e.g. `{"en": {"name": "Colour"}}`.'
        values:
          type: array
          items:
            type: object
            required: [id, value, position]
            properties:
              id: { type: string, format: uuid }
              value: { type: string }
              position: { type: integer }
              swatch: { type: string, description: A colour for rendering, when the axis is a colour. }
              image_index: { type: [integer, 'null'] }
              translations:
                $ref: '#/components/schemas/ContentTranslations'
                description: 'Stored translations of `value`, e.g. `{"en": {"value": "Red"}}`.'

    ShopCategory:
      type: object
      required: [id, name, slug, position, product_count]
      properties:
        id: { type: string, format: uuid }
        parent_id: { type: [string, 'null'], format: uuid }
        name: { type: string }
        slug: { type: string }
        position: { type: integer }
        image_url: { type: [string, 'null'], format: uri }
        source_category_id:
          type: [string, 'null']
          format: uuid
          description: The standard-taxonomy node this category is mapped to (it drives the product feed's `google_product_category`).
        source_category_name: { type: string, description: Display name of that node; empty when unmapped. }
        product_count: { type: integer }
        locale:
          type: string
          enum: [mn, en]
          description: The language `name` is served in — `en` only when the caller asked for it (`?lang=en` / `X-OS-Content-Locale`) and the shop has English on; a missing translation falls back to Mongolian.
        translations:
          type: object
          description: 'The raw translations of the merchant text, `{"en": {"name": "…"}}`; `{}` when none.'
          additionalProperties:
            type: object
            additionalProperties: { type: string }

    Branch:
      type: object
      description: A physical branch («Салбар»). Every label is display-ready.
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        city: { type: string }
        district: { type: string }
        address_line: { type: string }
        address_label: { type: string, description: "City, district and line composed big → small." }
        phones: { type: array, items: { type: string } }
        phone_links:
          type: array
          items:
            type: object
            properties:
              number: { type: string }
              href: { type: string, description: "`tel:` link." }
        hours:
          type: array
          items:
            type: object
            properties:
              day: { type: integer, minimum: 0, maximum: 6, description: 0 = Sunday. }
              open: { type: string, example: "10:00" }
              close: { type: string, example: "19:00" }
              closed: { type: boolean }
        hours_lines:
          type: array
          items:
            type: object
            properties:
              day: { type: integer }
              day_label: { type: string }
              label: { type: string }
              today: { type: boolean }
        hours_summary: { type: string, example: "Даваа–Баасан 10:00–19:00 · Бямба–Ням Амарна" }
        today_hours_label: { type: string }
        open_now: { type: [boolean, 'null'], description: "`null` when the branch has no hours." }
        open_now_label: { type: string }
        open_detail_label: { type: string }
        lat: { type: [number, 'null'] }
        lng: { type: [number, 'null'] }
        map_url: { type: string, description: OpenStreetMap link (pin, or an address search). }
        image_url: { type: string }
        position: { type: integer }
        active: { type: boolean }
        is_main: { type: boolean }
        main_label: { type: string }
        pickup: { type: boolean, description: Offered as a pickup point at checkout. }

    Bundle:
      type: object
      required: [id, title, price_mnt, regular_total_mnt, available, items]
      properties:
        id: { type: string, format: uuid }
        title: { type: string }
        description: { type: string, description: Sanitised HTML. }
        image_url: { type: string }
        price_mnt: { type: integer, description: The bundle price — never more than the sum of its parts. }
        regular_total_mnt: { type: integer, description: What the components would cost separately. }
        available: { type: boolean, description: False when any component is unavailable. }
        items:
          type: array
          items:
            type: object
            required: [product_id, qty, title, unit_price_mnt, available]
            properties:
              product_id: { type: string, format: uuid }
              variant_id: { type: string, format: uuid }
              qty: { type: integer }
              title: { type: string }
              unit_price_mnt: { type: integer, description: Sale-aware, resolved server-side. }
              available: { type: boolean }

    Suggestion:
      type: object
      required: [id, title]
      properties:
        id: { type: string, format: uuid }
        title: { type: string }

    ReviewList:
      type: object
      required: [average, count, reviews]
      properties:
        average: { type: number, description: Mean rating. }
        count: { type: integer }
        reviews:
          type: array
          items:
            type: object
            required: [id, rating, verified, created_at]
            properties:
              id: { type: string, format: uuid }
              rating: { type: integer, minimum: 1, maximum: 5 }
              comment: { type: string }
              verified: { type: boolean, description: The reviewer actually bought it. }
              created_at: { type: string, format: date-time }

    ProductRating:
      type: object
      description: |
        Verified-purchase rating aggregate, display-ready. Lists carry the brief; the single-product
        read adds `histogram` (5→1) and `out_of_label`. Absent only when the aggregate could not be read.
      required: [average, average_label, count, count_label]
      properties:
        average: { type: number, description: 'Mean, one decimal (0 when there are no reviews).' }
        average_label: { type: string, example: '4.6' }
        count: { type: integer }
        count_label: { type: string, example: '12 сэтгэгдэл' }
        out_of_label: { type: string, example: '/ 5.0' }
        histogram:
          type: array
          items:
            type: object
            properties:
              stars: { type: integer }
              count: { type: integer }
              percent: { type: integer }
              label: { type: string, example: '80% (12)' }

    ProductReviewList:
      type: object
      required: [average, count, summary, filters, sorts, reviews, page, pages, total]
      properties:
        average: { type: number }
        count: { type: integer }
        summary: { $ref: '#/components/schemas/ProductRating' }
        hidden_note: { type: string, description: 'Non-empty when the shop hid some review texts (their stars still count).' }
        reward_note: { type: string, description: 'Non-empty when a listed review earned the shop''s loyalty points — explains the `reward_label` chip (points never depend on the stars).' }
        filters:
          type: array
          items:
            type: object
            properties:
              key: { type: string, description: '`all`, `1`…`5` or `photos`.' }
              label: { type: string, example: 'Бүгд (12)' }
              count: { type: integer }
        filter: { type: string }
        sorts:
          type: array
          items:
            type: object
            properties:
              key: { type: string }
              label: { type: string }
        sort: { type: string }
        page: { type: integer }
        pages: { type: integer }
        total: { type: integer }
        reviews:
          type: array
          items:
            type: object
            required: [id, rating, verified, created_at]
            properties:
              id: { type: string, format: uuid }
              rating: { type: integer, minimum: 1, maximum: 5 }
              comment: { type: string, description: Plain text. }
              author_name: { type: string, description: The name the buyer chose to show. }
              variant_label: { type: string, example: 'Улаан / M' }
              verified: { type: boolean, description: Always true — only verified purchases are public. }
              verified_label: { type: string }
              photos:
                type: array
                items:
                  type: object
                  properties:
                    id: { type: string }
                    url: { type: string, format: uri }
              reply:
                type: [object, 'null']
                description: The shop's public answer.
                properties:
                  body: { type: string }
                  label: { type: string }
                  date_label: { type: string }
              created_at: { type: string, format: date-time }
              date_label: { type: string, example: '2026-10-23' }
              helpful_count: { type: integer, description: Readers who marked it helpful. }
              helpful_label: { type: string, example: 'Тустай' }
              helpful_count_label: { type: string, example: '3 хүнд тустай байсан', description: Empty at 0. }
              reward_label: { type: string, example: 'Оноо авсан', description: 'Non-empty when the buyer received the shop''s loyalty points for writing it (incentive transparency).' }

    CheckoutRequest:
      type: object
      description: At least one of `items` or `bundles` must be non-empty.
      properties:
        buyer_phone: { type: string }
        buyer_name: { type: string }
        customer_tin:
          type: string
          description: |
            The buyer organisation's ТТД for a B2B fiscal receipt — 11 to 14 digits. A 7-digit
            registration number is **not** valid here; resolve it with
            `GET /shop/ebarimt/tin-lookup` first. Setting this clears `consumer_register`.
        consumer_register:
          type: string
          description: The buyer's citizen register (two Cyrillic letters + eight digits) for a personal fiscal receipt.
        items:
          type: array
          maxItems: 100
          items:
            type: object
            required: [product_id, qty]
            properties:
              product_id: { type: string, format: uuid }
              variant_id: { type: string, format: uuid, description: Omit to use the product's default variant. }
              qty: { type: integer, minimum: 1, maximum: 10000 }
              gift_card: { $ref: '#/components/schemas/GiftCardPurchase' }
        bundles:
          type: array
          maxItems: 20
          description: Bundles are expanded into order lines server-side; the saving lands in `discount_mnt`.
          items:
            type: object
            required: [bundle_id, qty]
            properties:
              bundle_id: { type: string, format: uuid }
              qty: { type: integer, minimum: 1, maximum: 100 }
        coupon_code: { type: string }
        buyer_email:
          type: string
          maxLength: 200
          description: |
            Where the delivery link for digital items goes (and the e-barimt receipt). Required
            for a guest whose cart holds a file, a code or a course (`buyer_email_required`).
            A digital-only cart pays no delivery fee and needs no address.
        delivery_zone: { $ref: '#/components/schemas/DeliveryZone' }
        delivery_address: { type: string, maxLength: 500 }
        delivery_address_parts:
          type: object
          description: |
            Structured delivery address. When present the server validates it against
            `GET /api/v1/address/mn` (Улаанбаатар's district and khoroo must come from the tree;
            a rural aimag's sum is typed, its bag optional), derives `delivery_zone` from the city
            and composes `delivery_address` itself — the two plain fields are then ignored. Invalid
            → 400 `address_invalid` with `field`.
          required: [kind, city, district, building]
          properties:
            kind: { type: string, enum: [apartment, house, office] }
            city: { type: string, description: Улаанбаатар or an aimag name. }
            district: { type: string, maxLength: 60 }
            khoroo: { type: string, maxLength: 60, description: Required in Улаанбаатар. }
            building: { type: string, maxLength: 80 }
            unit: { type: string, maxLength: 30 }
            note: { type: string, maxLength: 200 }
        pickup_branch_id:
          type: string
          format: uuid
          description: |
            «Очиж авах»: collect the order at this branch (see `listPublicBranches`). The
            delivery address is ignored and no delivery fee is charged. Refused with
            `pickup_unavailable` (409) unless the shop offers pickup and the branch is an
            active pickup point. Required for a shipping cart when the shop takes pickup
            orders only (`delivery_available: false` on `listPublicBranches`), else
            `delivery_unavailable` (409); a digital-only cart never needs it.
        meta_fbp: { type: string, maxLength: 256, description: Meta attribution cookie, stored only with consent. }
        meta_fbc: { type: string, maxLength: 256, description: Meta attribution cookie, stored only with consent. }
        meta_event_id: { type: string, maxLength: 128 }
        meta_consent: { type: boolean }
        gift_card_codes:
          type: array
          maxItems: 3
          items: { type: string, maxLength: 64 }
          description: |
            Gift cards of THIS shop tendering what is still due after every discount and the
            delivery/cargo fees, in the order given (each card gives min(balance, what is
            due)). A gift card is a payment, not a discount: `total_mnt` stays the order's
            price and `gift_card_mnt` shows the card part; the invoice is for the rest. When
            the cards cover everything the order is `paid` at once and **no invoice** is
            returned. Any unusable code refuses the whole checkout (`gift_card_not_found`
            404, `gift_card_frozen` / `gift_card_voided` / `gift_card_expired` /
            `gift_card_empty` 409). Ignored on connector-signed checkouts. Never send a code
            in a URL.
        gift_card_ids:
          type: array
          maxItems: 3
          items: { type: string, format: uuid }
          description: |
            Cards saved in the signed-in buyer's account (`GET /me/gift-cards`, `spendable`),
            picked without typing the code. Only the buyer's own cards of THIS shop; anything
            else (guest, another person's or shop's card, a malformed id) answers exactly like
            an unknown code (`gift_card_not_found`). `gift_card_codes` + `gift_card_ids` ≤ 3.

    GiftCardPurchase:
      type: object
      description: |
        Buying a gift card (product_type `gift_card`): the cart holds this ONE line and
        nothing else — no bundle, coupon, points or gift-card tender (`gift_card_cart_mixed`,
        `gift_card_purchase_tender`, 409). `buyer_email` is required. The cards are created
        once the order is paid and their codes go by email (on `send_on` for a scheduled gift).
        The card is the merchant's own closed-loop prepaid value for this shop only.
      required: [amount_mnt, mode]
      properties:
        amount_mnt:
          type: integer
          description: One of the product's denominations, or inside its custom range (`gift_card_amount_invalid`).
        mode: { type: string, enum: [self, gift] }
        recipient_name: { type: string, maxLength: 80 }
        recipient_email: { type: string, maxLength: 200, description: Required for `gift` (`gift_card_recipient_required`). }
        message: { type: string, maxLength: 300 }
        send_on: { type: string, format: date, description: 'Ulaanbaatar day to send a gift on (09:00); empty or today = at payment; at most a year ahead.' }

    GiftCardOffer:
      type: object
      properties:
        product_id: { type: string, format: uuid }
        denominations: { type: array, items: { type: integer } }
        allow_custom: { type: boolean }
        custom_min_mnt: { type: integer }
        custom_max_mnt: { type: integer }
        validity_months: { type: integer, description: 0 = no expiry. }
        validity_label: { type: string }
        terms_html: { type: string, description: Server-sanitised HTML. }
        note: { type: string, description: The closed-loop statement to show the buyer. }
        max_qty: { type: integer }
        send_ahead_days: { type: integer }
        max_message: { type: integer }
        receipt_at_sale: { type: boolean, description: 'The shop issues an e-barimt when a card is sold; false = no receipt (and no register needed) at purchase.' }
        bonus_percent: { type: integer, minimum: 0, maximum: 20, description: 'The merchant''s bonus: paying A gives a card of A + floor(A·p/100) (never above 2,000,000₮). The order and any receipt are A only.' }
        bonus_label: { type: string, description: 'Display-ready bonus line ("" = none).' }
        design: { type: string, enum: [classic, minimal, bold, festive, soft], description: 'Card template, painted with the shop''s accent colour.' }

    GiftCardBalance:
      type: object
      properties:
        masked_code: { type: string, example: '••••-••••-••••-WXYZ' }
        balance_mnt: { type: integer }
        initial_mnt: { type: integer }
        status: { type: string, enum: [active, frozen, voided, expired] }
        status_label: { type: string }
        expires_at: { type: string, description: 'YYYY-MM-DD (Ulaanbaatar), empty = no expiry.' }
        expires_label: { type: string }
        usable: { type: boolean }
        reason: { type: string, description: 'Why it cannot pay right now (an error code), empty when usable.' }
        reason_label: { type: string }
        note: { type: string }

    Order:
      type: object
      required: [id, total_mnt, discount_mnt, status, created_at]
      properties:
        id: { type: string, format: uuid, description: Also the receipt token — unguessable, and enough on its own to poll the status. }
        total_mnt: { type: integer }
        discount_mnt: { type: integer, description: Coupon and bundle savings combined. }
        gift_card_mnt: { type: integer, description: 'The part of total_mnt gift cards paid (0 = none); the invoice is for the rest.' }
        status: { $ref: '#/components/schemas/OrderStatus' }
        invoice_id: { type: string, format: uuid }
        created_at: { type: string, format: date-time }
        paid_at:
          type: string
          format: date-time
          description: When the rail settled it. Present only once paid — key your own records on this, not on when your poll noticed.
        payment_state: { $ref: '#/components/schemas/PaymentState' }
        payment_state_label: { type: string, description: Mongolian display label of `payment_state`. }

    PaymentState:
      type: string
      enum: [awaiting_payment, awaiting_confirmation, paid, expired, cancelled, underpaid]
      description: |
        What to show the payer, display-ready — never derive expiry from `created_at` plus a TTL.
        `awaiting_confirmation`: the payment window has passed but the payment is still open at the
        payment provider (some wallets and instalment apps keep their request open for up to about
        30 minutes), so the payer may still confirm it in their app. Keep polling; it ends as
        `paid` or `expired`. Additive: treat an unknown value like `awaiting_payment`.

    OrderStatus:
      type: string
      enum: [pending, paid, fulfilled, cancelled, expired]
      description: |
        `pending` → `paid` → `fulfilled` is the happy path. An unpaid order becomes `expired`
        when its invoice window closes — but a late payment can still move it to `paid`
        afterwards, so `expired` is not final.

    DeliveryZone:
      type: string
      enum: [UB, RURAL]
      description: Ulaanbaatar or the countryside — the two delivery-fee bands.

    Invoice:
      type: object
      required: [id, amount_mnt, status, rail]
      properties:
        id: { type: string, format: uuid }
        amount_mnt: { type: integer }
        status: { type: string }
        rail: { type: string, description: Which payment rail opened it. }
        qr_data: { type: string, description: Present when the rail returned a QR payload. }
        checkout_url:
          type: string
          format: uri
          description: |
            The hosted payment page. Send the payer here. Returning from it is **not** proof of
            payment — confirm with `GET /shop/checkout/{id}`.

    OrderRow:
      type: object
      description: One row of the merchant's order list.
      required: [id, status, total_mnt, discount_mnt, item_count, created_at]
      properties:
        id: { type: string, format: uuid }
        status: { $ref: '#/components/schemas/OrderStatus' }
        total_mnt: { type: integer }
        discount_mnt: { type: integer }
        buyer_name: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        buyer_phone: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        delivery_zone: { $ref: '#/components/schemas/DeliveryZone' }
        item_count: { type: integer }
        items_summary: { type: string, description: A short human summary of the lines. }
        ebarimt_ddtd: { type: string, description: The fiscal receipt number, once issued. }
        created_at: { type: string, format: date-time }
        src_source: { type: string, description: First-touch traffic source; empty means direct. }
        source_label: { type: string, description: Mongolian display name for `src_source`. }
        payment_state: { $ref: '#/components/schemas/PaymentState' }
        payment_state_label: { type: string }
        paid_late: { type: boolean, description: The payment arrived after the order had expired; the order was revived to paid. }
        paid_late_label: { type: string, description: Present when `paid_late`. }
        stock_short: { type: boolean, description: On a late payment, the tracked stock no longer covered the order — ship later or refund. }
        stock_short_label: { type: string, description: Present when `stock_short`. }
        shipped: { type: boolean, description: "The order is `paid` and the shop marked it shipped (see `PUT /shop/orders/{id}/shipment`)." }
        shipped_label: { type: string, description: Present when `shipped`. }
        balance_due_mnt: { type: integer, description: An open extra charge on the order still waiting for payment (0 = none). }
        balance_due_label: { type: string, description: Present when `balance_due_mnt` > 0. }
        coupon_code: { type: string, description: 'The coupon code the order was placed with; "" = none.' }
        paid_with:
          type: array
          description: What the order was paid with (see `PaidWith`); `[]` until a payment settled. Added 2026-11.
          items: { $ref: '#/components/schemas/PaidWith' }
        paid_with_label: { type: string, description: 'The labels of `paid_with` joined, e.g. "QPay + Бэлгийн карт"; "" until paid. Added 2026-11.' }
        pii_redacted: { type: boolean, description: Present (and true) only when the buyer fields were withheld. }

    PaidWith:
      type: object
      description: |
        One instrument a payment went through, recorded at settlement from Wire's server-side
        payment intent (never from a callback). `key` is a closed list — decode an unknown key as
        `unknown`; `label` is display-ready Mongolian (render it as is). A gift card + rail order
        lists both, the rail first.
      required: [key, label]
      properties:
        key:
          type: string
          enum: [qpay, socialpay, paylink, storepay, lendmn, pocket, toki, monpay, gift_card, test, unknown]
          description: |
            The Wire operator id (`paylink` = bank card, `pocket` = Pocket Zero), `gift_card`,
            `test` (sandbox / test rail) or `unknown` (paid, but the operator was not recorded).
        label: { type: string, description: 'e.g. "QPay", "Карт (PayLink)", "StorePay", "Бэлгийн карт", "Тодорхойгүй".' }

    OrderShipment:
      type: object
      description: |
        The courier and parcel number the shop entered (free text — no courier integration).
        Kept after the order is fulfilled.
      required: [carrier, tracking_number, tracking_url, shipped_at]
      properties:
        carrier: { type: string }
        tracking_number: { type: string, description: Empty when the shop gave none. }
        tracking_url: { type: string, description: "Absolute http(s) link, or empty." }
        shipped_at: { type: string, format: date-time, description: When the order was first marked shipped. }

    OrderCharge:
      type: object
      description: |
        An extra charge («Нэмэлт төлбөр») the shop billed on a paid order — international shipping
        weighed on arrival, a weight difference, an agreed balance. It is a payment link: the buyer
        pays it at `pay_url`, and each paid charge gets its own fiscal receipt. The order itself (its
        status, stock and receipt) never changes.
      required: [id, amount_mnt, reason_key, reason_label, note, status, status_label, open, pay_url, created_at]
      properties:
        id: { type: string, format: uuid, description: "The payment link id (`GET /shop/pay/{id}`)." }
        amount_mnt: { type: integer }
        reason_key: { type: string, enum: [intl_shipping, weight_diff, balance, other] }
        reason_label: { type: string, description: Mongolian display name of the reason. }
        note: { type: string, description: "The shop's plain-text note (≤200 characters), may be empty." }
        status: { type: string, enum: [open, paid, cancelled, expired] }
        status_label: { type: string }
        open: { type: boolean, description: Still waiting for payment. }
        pay_url: { type: string, format: uri }
        ebarimt_ddtd: { type: string, description: The charge's own fiscal receipt id, once issued. }
        created_at: { type: string, format: date-time }
        paid_at: { type: string, format: date-time }
        paid_with:
          type: array
          description: What the charge was paid with; `[]` until paid. Added 2026-11.
          items: { $ref: '#/components/schemas/PaidWith' }
        paid_with_label: { type: string, description: '"" until paid. Added 2026-11.' }

    OrderDetail:
      type: object
      required: [id, status, total_mnt, subtotal_mnt, discount_mnt, delivery_fee_mnt, cargo_fee_mnt, created_at, items]
      properties:
        id: { type: string, format: uuid }
        status: { $ref: '#/components/schemas/OrderStatus' }
        subtotal_mnt: { type: integer }
        discount_mnt: { type: integer }
        delivery_fee_mnt: { type: integer }
        cargo_fee_mnt: { type: integer }
        total_mnt: { type: integer, description: subtotal − discount + delivery + cargo. }
        buyer_name: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        buyer_phone: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        consumer_register: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        customer_tin: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        delivery_zone: { $ref: '#/components/schemas/DeliveryZone' }
        delivery_address: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        ebarimt_ddtd: { type: string }
        ebarimt_issued_at: { type: [string, 'null'], format: date-time }
        created_at: { type: string, format: date-time }
        src_source: { type: string }
        pickup:
          description: The branch the buyer collects from (snapshot taken at checkout); `null` for a delivered order.
          oneOf:
            - type: 'null'
            - type: object
              properties:
                branch_id: { type: string, format: uuid }
                label: { type: string }
                name: { type: string }
                address: { type: string }
                phone: { type: string }
        source_label: { type: string }
        payment_state: { $ref: '#/components/schemas/PaymentState' }
        payment_state_label: { type: string }
        paid_late: { type: boolean, description: The payment arrived after the order had expired; the order was revived to paid. }
        paid_late_label: { type: string, description: Present when `paid_late`. }
        stock_short: { type: boolean, description: On a late payment, the tracked stock no longer covered the order — ship later or refund. }
        stock_short_label: { type: string, description: Present when `stock_short`. }
        shipped: { type: boolean, description: "The order is `paid` and the shop marked it shipped." }
        shipped_label: { type: string, description: Present when `shipped`. }
        shipment:
          description: Courier + tracking once shipped; `null` when the order was never marked shipped.
          oneOf:
            - type: 'null'
            - $ref: '#/components/schemas/OrderShipment'
        charges:
          type: array
          description: The order's extra charges, newest first, in every status.
          items: { $ref: '#/components/schemas/OrderCharge' }
        balance_due_mnt: { type: integer, description: The open extra charge still waiting for payment (0 = none). }
        balance_due_label: { type: string, description: Present when `balance_due_mnt` > 0. }
        can_charge: { type: boolean, description: Whether a new extra charge may be created now. }
        charge_blocked_label: { type: string, description: "Why not, when the order is paid but `can_charge` is false." }
        charge_max_mnt: { type: integer, description: "The most one charge may ask: min(3 × the items subtotal, 10,000,000)." }
        charge_reasons:
          type: array
          items:
            type: object
            properties:
              key: { type: string }
              label: { type: string }
        items:
          type: array
          items:
            type: object
            required: [title, qty, unit_price_mnt]
            properties:
              title: { type: string, description: The product name, without the option labels. }
              variant: { type: string, description: 'The option labels, e.g. "Улаан / M".' }
              qty: { type: integer }
              unit_price_mnt: { type: integer, description: The price actually charged, sale included. }
              promo_discount_mnt: { type: integer, description: This line's promotion discount (part of the order's `discount_mnt`). }
              net_mnt: { type: integer, description: unit_price_mnt × qty − promo_discount_mnt — the exact base for a refund of this line. }
              is_gift: { type: boolean, description: A gift line a promotion added (priced, discounted to 0). }
              promo_label: { type: string, description: 'e.g. "2+1 · Хаврын 2+1" or "Бэлэг · …"; "" = none.' }
        promo_discount_mnt: { type: integer, description: The promotions' part of `discount_mnt` (line discounts + gift values). }
        promotions:
          type: array
          description: The promotions this order used.
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              title: { type: string }
              badge: { type: string }
              discount_mnt: { type: integer }
        coupon_discount_mnt: { type: integer, description: The coupons' part of `discount_mnt`. }
        coupons:
          type: array
          description: The coupon code(s) the order was placed with and what each took off.
          items:
            type: object
            properties:
              coupon_id: { type: string, format: uuid }
              code: { type: string, description: The code the buyer entered (the single-use / personal code when there is one). }
              name: { type: string, description: The shop's own name for the coupon. }
              benefit_label: { type: string, description: 'The coupon''s terms in Mongolian, e.g. "10% хөнгөлөлт".' }
              discount_mnt: { type: integer, description: What the coupon took off this order. }
              auto_apply: { type: boolean, description: The checkout applied the coupon without a code. }
              label: { type: string, description: 'Display name of the row, e.g. "Купон BOLD10".' }
        paid_with:
          type: array
          description: What the order was paid with (see `PaidWith`); `[]` until a payment settled. Added 2026-11.
          items: { $ref: '#/components/schemas/PaidWith' }
        paid_with_label: { type: string, description: 'The labels of `paid_with` joined, e.g. "QPay + Бэлгийн карт"; "" until paid. Added 2026-11.' }
        pay_url: { type: string, description: 'A `pending` order''s hosted payment page (absent otherwise) — what the shop sends the buyer. Added 2026-11.' }
        pii_redacted: { type: boolean, description: Present (and true) only when the buyer fields were withheld. }

    ManualOrderRequest:
      type: object
      description: A merchant-built order. Every field may be empty on a quote; a create needs the buyer and items.
      properties:
        buyer_name: { type: string, maxLength: 100 }
        buyer_phone: { type: string, description: '8-digit Mongolian number; spaces, dashes and a +976 prefix are accepted.' }
        buyer_email: { type: string, description: Optional; kept only when the order holds digital items. }
        buyer_note: { type: string, maxLength: 500 }
        items:
          type: array
          maxItems: 100
          items:
            type: object
            required: [product_id, qty]
            properties:
              product_id: { type: string, format: uuid, description: An active product. }
              variant_id: { type: string, format: uuid, description: Omit for the default variant. }
              qty: { type: integer, minimum: 1, maximum: 10000 }
        fulfillment: { type: string, enum: [delivery, pickup], description: Default `delivery`. }
        delivery_zone: { $ref: '#/components/schemas/DeliveryZone' }
        delivery_address: { type: string, maxLength: 500 }
        pickup_branch_id: { type: string, format: uuid, description: Required when `fulfillment` is `pickup`. }

    OrderQuote:
      type: object
      required: [items, subtotal_mnt, discount_mnt, promo_discount_mnt, promotions, coupon_discount_mnt, coupons, delivery_fee_mnt, cargo_fee_mnt, total_mnt, needs_delivery, fulfillment, pay_window_label]
      properties:
        items:
          type: array
          description: The priced lines, promotion gifts included — the same shape as `OrderDetail.items`.
          items: { type: object, additionalProperties: true }
        subtotal_mnt: { type: integer }
        discount_mnt: { type: integer, description: Promotions and the automatic coupon combined. }
        promo_discount_mnt: { type: integer }
        promotions: { type: array, items: { type: object, additionalProperties: true } }
        coupon_discount_mnt: { type: integer }
        coupons: { type: array, items: { type: object, additionalProperties: true } }
        delivery_fee_mnt: { type: integer }
        cargo_fee_mnt: { type: integer }
        total_mnt: { type: integer, description: What the buyer will pay. }
        needs_delivery: { type: boolean, description: Anything in the order ships (false = digital only). }
        pickup:
          description: The chosen pickup branch; `null` for delivery.
          type: [object, 'null']
          additionalProperties: true
        fulfillment:
          type: object
          required: [delivery, pickup, label, branches]
          properties:
            delivery: { type: boolean, description: Delivery may be offered. }
            pickup: { type: boolean, description: Pickup at a branch may be offered. }
            label: { type: string }
            branches:
              type: array
              items:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  name: { type: string }
                  address: { type: string }
        pay_window_label: { type: string }

    OrderExportRow:
      type: object
      required: [id, status, total_mnt, created_at]
      properties:
        id: { type: string, format: uuid }
        status: { $ref: '#/components/schemas/OrderStatus' }
        buyer_name: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        buyer_phone: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        item_count: { type: integer }
        items_summary: { type: string }
        subtotal_mnt: { type: integer }
        discount_mnt: { type: integer }
        delivery_fee_mnt: { type: integer }
        cargo_fee_mnt: { type: integer }
        total_mnt: { type: integer }
        delivery_zone: { $ref: '#/components/schemas/DeliveryZone' }
        delivery_address: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        customer_tin: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        consumer_register: { type: [string, 'null'], description: "`null` when the caller lacks `customer:read`." }
        ebarimt_ddtd: { type: string }
        created_at: { type: string, format: date-time }
        src_source: { type: string }
        source_label: { type: string }
        coupon_code: { type: string, description: 'The coupon code the order was placed with; "" = none.' }
        paid_with:
          type: array
          description: What the order was paid with (see `PaidWith`); `[]` until a payment settled. Added 2026-11.
          items: { $ref: '#/components/schemas/PaidWith' }
        paid_with_label: { type: string, description: 'The labels of `paid_with` joined, e.g. "QPay + Бэлгийн карт"; "" until paid. Added 2026-11.' }
        pii_redacted: { type: boolean, description: Present (and true) only when the buyer fields were withheld. }

    BuyerOrder:
      type: object
      description: The buyer's own view of an order — what a receipt page renders.
      required: [id, shop_slug, shop_name, status, total_mnt, discount_mnt, delivery_fee_mnt, cargo_fee_mnt, created_at, items]
      properties:
        id: { type: string, format: uuid }
        shop_slug: { type: string }
        shop_name: { type: string }
        status: { $ref: '#/components/schemas/OrderStatus' }
        total_mnt: { type: integer }
        discount_mnt: { type: integer }
        delivery_fee_mnt: { type: integer }
        cargo_fee_mnt: { type: integer }
        delivery_zone: { $ref: '#/components/schemas/DeliveryZone' }
        delivery_address: { type: string }
        created_at: { type: string, format: date-time }
        paid_at: { type: string, format: date-time }
        ebarimt_ddtd: { type: string }
        ebarimt_issued_at: { type: string, format: date-time }
        checkout_url:
          type: string
          format: uri
          description: Present only while the order is still payable — the payer can resume here.
        charges:
          type: array
          description: Extra charges the shop billed after payment — open and paid ones only.
          items: { $ref: '#/components/schemas/OrderCharge' }
        balance_due_mnt: { type: integer, description: "The open extra charge to pay (0 = nothing due); pay it at the open charge's `pay_url`." }
        balance_due_label: { type: string, description: Present when `balance_due_mnt` > 0. }
        paid_with:
          type: array
          description: What the order was paid with (see `PaidWith`); `[]` until a payment settled. Added 2026-11.
          items: { $ref: '#/components/schemas/PaidWith' }
        paid_with_label: { type: string, description: 'The labels of `paid_with` joined, e.g. "QPay + Бэлгийн карт"; "" until paid. Added 2026-11.' }
        items:
          type: array
          items:
            type: object
            required: [title, qty, unit_price_mnt]
            properties:
              title: { type: string }
              qty: { type: integer }
              unit_price_mnt: { type: integer }

    CouponQuoteRequest:
      type: object
      required: [subtotal_mnt]
      properties:
        code: { type: string, description: Empty to preview the best automatic discount instead. }
        subtotal_mnt: { type: integer, minimum: 1 }
        lines:
          type: array
          description: The cart lines, so product- and category-restricted coupons can be judged.
          items:
            type: object
            properties:
              product_id: { type: string, format: uuid }
              variant_id: { type: string, format: uuid }
              qty: { type: integer }
              unit_price_mnt: { type: integer }

    PromotionQuoteRequest:
      type: object
      properties:
        items:
          type: array
          maxItems: 100
          items:
            type: object
            required: [product_id, qty]
            properties:
              product_id: { type: string, format: uuid }
              variant_id: { type: string, format: uuid, description: Omit for the product's default variant. }
              qty: { type: integer, minimum: 1 }
        bundles:
          type: array
          maxItems: 20
          description: Bundles never join a promotion; they count toward a spend threshold.
          items:
            type: object
            required: [bundle_id, qty]
            properties:
              bundle_id: { type: string, format: uuid }
              qty: { type: integer, minimum: 1 }

    PromotionQuote:
      type: object
      required: [discount_mnt, gift_value_mnt, goods_subtotal_mnt, subtotal_after_mnt, stack_with_coupon, lines, gifts, applied, hints]
      properties:
        discount_mnt: { type: integer, description: The promotion discount on the cart's own lines (gifts excluded). }
        gift_value_mnt: { type: integer, description: Full price of the gift lines — they cost 0. }
        goods_subtotal_mnt: { type: integer, description: Sale-aware lines + bundle prices, before promotions. }
        subtotal_after_mnt: { type: integer, description: goods_subtotal_mnt − discount_mnt; minimum order, free delivery, coupons and points are judged on this. }
        stack_with_coupon: { type: boolean, description: False when an applied promotion refuses coupons (checkout answers 409 `promotion_not_stackable` to a code). }
        coupon_note: { type: string }
        lines:
          type: array
          items:
            type: object
            properties:
              product_id: { type: string, format: uuid }
              variant_id: { type: string, format: uuid }
              qty: { type: integer }
              promotion_id: { type: string, format: uuid }
              promo_discount_mnt: { type: integer }
              label: { type: string }
        gifts:
          type: array
          description: Lines the server adds at checkout; the buyer cannot change their quantity.
          items:
            type: object
            properties:
              promotion_id: { type: string, format: uuid }
              product_id: { type: string, format: uuid }
              variant_id: { type: string, format: uuid }
              title: { type: string }
              image: { type: string }
              qty: { type: integer }
              unit_price_mnt: { type: integer }
              label: { type: string }
        applied:
          type: array
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              title: { type: string }
              badge: { type: string }
              discount_mnt: { type: integer }
        hints:
          type: array
          items:
            type: object
            properties:
              promotion_id: { type: string, format: uuid }
              product_ids: { type: array, items: { type: string, format: uuid } }
              text: { type: string, description: 'e.g. "Дахиад 1 нэмбэл 1 үнэгүй".' }

    CouponQuote:
      type: object
      required: [discount_mnt, total_mnt]
      properties:
        discount_mnt: { type: integer }
        total_mnt: { type: integer, description: subtotal − discount. Delivery is added later, at checkout. }
        code: { type: string, description: Echoed when a code was quoted. }
        name: { type: string, description: The campaign name, on an automatic discount. }
        type: { type: string, description: How the discount is computed. }
        auto: { type: boolean, description: True when this is the best automatic discount rather than a named code. }

    PublicPayable:
      type: object
      description: A payment link as the payer sees it.
      required: [id, kind, kind_label, title, amount_mnt, status, status_label, payable, fiscal, shop_name, lines]
      properties:
        id: { type: string, format: uuid }
        kind: { type: string, description: "What kind of payable this is (invoice, ticket, course fee, donation, an order's extra charge `order_charge`, …)." }
        kind_label: { type: string, description: Mongolian display name. }
        title: { type: string }
        note: { type: string, description: Sanitised HTML. }
        amount_mnt: { type: integer }
        status: { type: string, enum: [open, paid, cancelled, expired] }
        status_label: { type: string }
        payable: { type: boolean, description: Whether the «Төлөх» action should be offered. }
        fiscal: { type: boolean, description: Whether a fiscal receipt will be issued on payment. }
        expires_at: { type: string, format: date-time }
        paid_at: { type: string, format: date-time }
        shop_name: { type: string }
        shop_phone: { type: string }
        payment_pending:
          type: boolean
          description: |
            A previous payment of this link is still awaiting confirmation at the payment provider.
            Show `payment_pending_label` and poll `GET /shop/pay/{id}/status` instead of offering «Төлөх».
        payment_pending_label: { type: string, description: Present when `payment_pending`. }
        lines:
          type: array
          items:
            type: object
            properties:
              title: { type: string }
              qty: { type: integer }
              unit_price_mnt: { type: integer }
              total_mnt: { type: integer }

    PayableStatus:
      type: object
      required: [id, status, status_label, amount_mnt]
      properties:
        id: { type: string, format: uuid }
        status: { type: string, enum: [open, paid, cancelled, expired] }
        status_label: { type: string }
        amount_mnt: { type: integer }
        paid_at: { type: [string, 'null'], format: date-time }
        payment_pending: { type: boolean, description: A previous payment is still awaiting confirmation — keep polling. }
        payment_pending_label: { type: string, description: Present when `payment_pending`. }

    PayableCheckoutRequest:
      type: object
      required: [payer_name, payer_phone]
      properties:
        payer_name: { type: string, maxLength: 120 }
        payer_phone: { type: string, maxLength: 32 }
        payer_email: { type: string, format: email, maxLength: 200 }
        customer_tin: { type: string, description: 11–14 digits, for a B2B fiscal receipt. }
        consumer_register: { type: string, description: The payer's citizen register, for a personal fiscal receipt. }

    KeyScope:
      type: string
      description: |
        The closed set of permissions an API key may carry. Permissions that administer
        people or credentials (`staff:manage`, `role:manage`, `integration:manage`) are
        deliberately absent: a credential does not administer credentials.
      enum:
        - "product:read"
        - "product:write"
        - "product:delete"
        - "order:read"
        - "order:write"

    APIKey:
      type: object
      required: [id, name, key_prefix, scopes, scope_labels, created_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        key_prefix: { type: string, description: 'The leading characters of the key, for recognising it in a list — e.g. "osk_live_ab1".' }
        scopes:
          type: array
          items: { $ref: '#/components/schemas/KeyScope' }
        scope_labels:
          type: array
          description: Mongolian display names, positionally matching `scopes`.
          items: { type: string }
        created_at: { type: string, format: date-time }
        last_used_at: { type: [string, 'null'], format: date-time, description: Stamped at most once a minute. }
        revoked_at: { type: [string, 'null'], format: date-time, description: Non-null means the key is dead. }

    StorefrontPublish:
      type: object
      required: [id, created_at, version, source, source_label, template_id, template_name, sections_count, author, summary, live]
      properties:
        id: { type: string, format: uuid }
        created_at: { type: string, format: date-time }
        version: { type: integer, description: The published version this snapshot became. }
        source:
          type: string
          enum: [publish, activate, create, baseline]
          description: "`baseline` = the design that was live when the history began."
        source_label: { type: string, description: Display label in the UI language. }
        template_id: { type: string }
        template_name: { type: string, description: The preset's name in the UI language (the id when the preset was removed). }
        sections_count: { type: integer, description: Blocks on all pages, the preset's default home included. }
        author: { type: string, description: The publishing member's display name; empty when unknown. }
        summary: { type: string, description: One display line (source, theme, block count). }
        live: { type: boolean, description: This snapshot is what the storefront renders now. }

    WebhookEventType:
      type: string
      description: |
        The subscribable events. `ping` is excluded — it can only be produced by the console's
        test button. New events are added over time (`order.shipped`, 2026-11; the customer,
        gift card, booking, review, payment link, survey and extra-charge topics, catalogue
        `2026-11`); ignore an event type you do not handle. `GET /shop/webhooks/events` reports
        each event's group and the catalogue version that introduced it (`since`).
      enum:
        - order.created
        - order.paid
        - order.expired
        - order.shipped
        - order.fulfilled
        - order.unfulfilled
        - product.created
        - product.updated
        - product.deleted
        - order.underpaid
        - order.charge_created
        - order.charge_paid
        - product.published
        - customer.created
        - customer.updated
        - gift_card.created
        - booking.confirmed
        - booking.balance_paid
        - booking.cancelled
        - booking.expired
        - review.created
        - review.updated
        - payment_link.paid
        - survey.response_created

    WebhookEventKey:
      type: string
      description: |
        A webhook event as the API reports it back (endpoint subscriptions, the event catalogue,
        delivery logs) — the same values as `WebhookEventType`. Declared `x-extensible-enum`:
        the list grows, existing values are never renamed. Treat an unknown value as an event
        you do not handle.
      x-extensible-enum:
        - order.created
        - order.paid
        - order.expired
        - order.shipped
        - order.fulfilled
        - order.unfulfilled
        - product.created
        - product.updated
        - product.deleted
        - order.underpaid
        - order.charge_created
        - order.charge_paid
        - product.published
        - customer.created
        - customer.updated
        - gift_card.created
        - booking.confirmed
        - booking.balance_paid
        - booking.cancelled
        - booking.expired
        - review.created
        - review.updated
        - payment_link.paid
        - survey.response_created

    WebhookEventKeyOrPing:
      type: string
      description: A reported webhook event (see `WebhookEventKey`), or the console's `ping`.
      x-extensible-enum:
        - order.created
        - order.paid
        - order.expired
        - order.shipped
        - order.fulfilled
        - order.unfulfilled
        - product.created
        - product.updated
        - product.deleted
        - order.underpaid
        - order.charge_created
        - order.charge_paid
        - product.published
        - customer.created
        - customer.updated
        - gift_card.created
        - booking.confirmed
        - booking.balance_paid
        - booking.cancelled
        - booking.expired
        - review.created
        - review.updated
        - payment_link.paid
        - survey.response_created
        - ping

    WebhookEventTypeOrPing:
      description: A subscribable event, or the console's `ping`.
      oneOf:
        - $ref: '#/components/schemas/WebhookEventType'
        - type: string
          const: ping

    WebhookEndpoint:
      type: object
      required: [id, url, events, event_labels, status, status_label, failure_streak, created_at]
      properties:
        id: { type: string, format: uuid }
        url: { type: string, format: uri }
        description: { type: string }
        events:
          type: array
          items: { $ref: '#/components/schemas/WebhookEventKey' }
        event_labels:
          type: array
          description: Mongolian display names, positionally matching `events`.
          items: { type: string }
        status:
          type: string
          enum: [active, disabled, auto_disabled]
          description: "`auto_disabled` is the platform switching the endpoint off after a `410 Gone` or 50 consecutive failures. The merchant re-enables it from the console."
        status_label: { type: string }
        failure_streak: { type: integer, description: Consecutive failed deliveries; reset by any success. }
        last_delivery_at: { type: [string, 'null'], format: date-time }
        last_status_code: { type: [integer, 'null'] }
        secret_prev_expires_at:
          type: [string, 'null']
          format: date-time
          description: Present only while a rotation overlap is running — until then deliveries carry two signatures.
        secret_last4:
          type: string
          description: |
            The signing secret's last four characters (shown masked, e.g. `••••a1B2`) so you can
            tell which secret your server holds. The full secret is only ever returned once, by
            create or rotate. Empty for an app-managed endpoint. Added 2026-11.
        created_at: { type: string, format: date-time }

    DeliveryStatus:
      type: string
      enum: [pending, delivering, delivered, failed, dead]
      description: "`failed` will be retried. `dead` is final: the attempts ran out, or the receiver answered something no retry can fix."

    WebhookDelivery:
      type: object
      required: [id, event_type, event_label, status, status_label, attempt, created_at, payload]
      properties:
        id: { type: string, format: uuid, description: Sent to the receiver as `X-OpenShop-Delivery-Id`. }
        event_type: { $ref: '#/components/schemas/WebhookEventKeyOrPing' }
        event_label: { type: string }
        status: { $ref: '#/components/schemas/DeliveryStatus' }
        status_label: { type: string }
        attempt: { type: integer }
        next_attempt_at: { type: [string, 'null'], format: date-time, description: Present while the delivery is still pending or being retried. }
        last_status_code: { type: [integer, 'null'] }
        last_error: { type: string, description: A short error class — never the receiver's response body. }
        delivered_at: { type: [string, 'null'], format: date-time }
        replay_of: { type: [string, 'null'], format: uuid, description: Set when this delivery is a replay of an earlier one. }
        created_at: { type: string, format: date-time }
        payload:
          $ref: '#/components/schemas/WebhookPayloadRecord'

    WebhookPayload:
      type: object
      description: |
        The thin envelope we POST to a merchant endpoint. It carries identifiers, status and
        money — **never** a name, phone, address or email. Fetch the detail with your API key.
      required: [id, type, created_at, shop, data]
      properties:
        id:
          type: string
          format: uuid
          description: The event id. Stable across retries and echoed in `X-OpenShop-Event-Id` — deduplicate on it.
        type: { $ref: '#/components/schemas/WebhookEventTypeOrPing' }
        created_at:
          type: string
          format: date-time
          description: When the delivery was queued. Kept for compatibility — prefer `occurred_at`.
        occurred_at:
          type: string
          format: date-time
          description: |
            When the event itself happened (stamped inside the change that produced it), not when
            it was queued or sent. Use it to order events and to discard a stale one. Added
            2026-09; absent on deliveries queued before then and on their replays.
        api_version:
          type: string
          example: "2026-09"
          description: |
            Payload version, also sent as `X-OpenShop-Api-Version`. New fields are added without
            changing it; a breaking payload change would ship as a new value. A replay resends the
            original body byte for byte, so replaying a delivery queued before 2026-09 carries no
            `api_version` in the body — the header is always present.
        shop:
          type: object
          required: [slug]
          properties:
            slug: { type: string }
        data:
          description: Depends on `type`.
          oneOf:
            - $ref: '#/components/schemas/WebhookOrderData'
            - $ref: '#/components/schemas/WebhookOrderChargeData'
            - $ref: '#/components/schemas/WebhookProductData'
            - $ref: '#/components/schemas/WebhookCustomerData'
            - $ref: '#/components/schemas/WebhookGiftCardData'
            - $ref: '#/components/schemas/WebhookBookingData'
            - $ref: '#/components/schemas/WebhookReviewData'
            - $ref: '#/components/schemas/WebhookPaymentLinkData'
            - $ref: '#/components/schemas/WebhookSurveyResponseData'
            - $ref: '#/components/schemas/WebhookPingData'

    WebhookPayloadRecord:
      type: object
      description: |
        A delivery's body as the delivery log reports it — the `WebhookPayload` that was sent,
        with `type` declared extensible (see `WebhookEventKey`).
      required: [id, type, created_at, shop, data]
      properties:
        id:
          type: string
          format: uuid
          description: The event id. Stable across retries and echoed in `X-OpenShop-Event-Id` — deduplicate on it.
        type: { $ref: '#/components/schemas/WebhookEventKeyOrPing' }
        created_at:
          type: string
          format: date-time
          description: When the delivery was queued. Kept for compatibility — prefer `occurred_at`.
        occurred_at:
          type: string
          format: date-time
          description: |
            When the event itself happened (stamped inside the change that produced it), not when
            it was queued or sent. Use it to order events and to discard a stale one. Added
            2026-09; absent on deliveries queued before then and on their replays.
        api_version:
          type: string
          example: "2026-09"
          description: |
            Payload version, also sent as `X-OpenShop-Api-Version`. New fields are added without
            changing it; a breaking payload change would ship as a new value. A replay resends the
            original body byte for byte, so replaying a delivery queued before 2026-09 carries no
            `api_version` in the body — the header is always present.
        shop:
          type: object
          required: [slug]
          properties:
            slug: { type: string }
        data:
          description: |
            Depends on `type`. The log reports the body as sent; for the 2026-11 topics (customer,
            gift card, booking, review, payment link, survey, extra charge) the shapes are the ones
            listed on `WebhookPayload.data` (`WebhookCustomerData`, `WebhookBookingData`, …).
          oneOf:
            - $ref: '#/components/schemas/WebhookOrderData'
            - $ref: '#/components/schemas/WebhookProductData'
            - $ref: '#/components/schemas/WebhookPingData'

    WebhookOrderData:
      type: object
      description: The `data` of every `order.*` event.
      required: [order_id, status, total_mnt, discount_mnt]
      properties:
        order_id: { type: string, format: uuid }
        status: { $ref: '#/components/schemas/OrderStatus' }
        total_mnt: { type: integer }
        discount_mnt: { type: integer }
        promo_discount_mnt: { type: integer, description: 'The promotions'' part of `discount_mnt`. Added 2026-11.' }
        lines:
          type: array
          description: |
            The order lines with their exact promotion allocation (ids and money only). Added 2026-11;
            absent on deliveries queued before then.
          items:
            type: object
            properties:
              product_id: { type: [string, 'null'], format: uuid }
              variant_id: { type: [string, 'null'], format: uuid }
              qty: { type: integer }
              unit_price_mnt: { type: integer }
              promo_discount_mnt: { type: integer }
              net_mnt: { type: integer, description: unit_price_mnt × qty − promo_discount_mnt. }
              promotion_id: { type: [string, 'null'], format: uuid }
              is_gift: { type: boolean, description: A gift a promotion added at no cost. }
        paid_at: { type: string, format: date-time, description: Present once the order has been paid. }
        paid_with:
          type: array
          description: What the order was paid with; `[]` until a payment settled. Added 2026-11; absent on deliveries queued before then.
          items: { $ref: '#/components/schemas/PaidWith' }
        paid_late:
          type: boolean
          description: |
            The payment arrived after the order had expired and revived it to `paid` — check stock
            before shipping. Added 2026-11; absent on deliveries queued before then.
        shipment:
          description: |
            Present once the shop marked the order shipped. `order.shipped` is sent on the first
            mark and again when the shop corrects the details — keep the latest `occurred_at`.
          allOf:
            - $ref: '#/components/schemas/OrderShipment'

    WebhookOrderChargeData:
      type: object
      description: |
        The `data` of `order.charge_created` and `order.charge_paid` (2026-11): an extra charge the
        shop invoiced on a paid order. The order itself never changes — read it with
        `GET /shop/orders/{id}`.
      required: [order_id, charge]
      properties:
        order_id: { type: string, format: uuid }
        charge:
          type: object
          required: [charge_id, amount_mnt, status]
          properties:
            charge_id: { type: string, format: uuid }
            amount_mnt: { type: integer }
            reason_key: { type: string, description: The shop's reason (closed list, e.g. international freight). }
            status: { type: string, description: '`open` · `paid` · `cancelled` · `expired`.' }
            paid_at: { type: [string, 'null'], format: date-time }
            created_at: { type: string, format: date-time }

    WebhookCustomerData:
      type: object
      description: |
        The `data` of `customer.created` and `customer.updated` (2026-11). The shop's own labels
        only — **no** name, phone, email or address; a receiver with `customer:read` reads the
        rest with its API key. `customer.created` fires when a buyer first appears in the shop
        (their first order); `customer.updated` when the shop changes the tags or merges / splits
        a guest and an account record (sent for both records).
      required: [customer_id, kind]
      properties:
        customer_id: { type: string, format: uuid }
        kind: { type: string, enum: [account, guest] }
        first_source: { type: string }
        tags: { type: array, items: { type: string } }
        merged_into_id: { type: [string, 'null'], format: uuid, description: Set on a guest record folded into an account record. }
        paid_orders: { type: integer }
        ltv_mnt: { type: integer }
        first_seen_at: { type: string, format: date-time }
        last_order_at: { type: [string, 'null'], format: date-time }

    WebhookGiftCardData:
      type: object
      description: |
        The `data` of `gift_card.created` (2026-11): a new card, bought or issued by hand. Never
        the code (not even its last four) and never the recipient.
      required: [gift_card_id, initial_mnt, status]
      properties:
        gift_card_id: { type: string, format: uuid }
        initial_mnt: { type: integer }
        bonus_mnt: { type: integer, description: The shop's own bonus on top (not a sale). }
        balance_mnt: { type: integer }
        status: { type: string }
        source: { type: string }
        order_id: { type: [string, 'null'], format: uuid }
        product_id: { type: [string, 'null'], format: uuid }
        expires_at: { type: [string, 'null'], format: date-time }
        created_at: { type: string, format: date-time }

    WebhookBookingData:
      type: object
      description: |
        The `data` of every `booking.*` event (2026-11): the slot, the money and the state — never
        the customer's name, phone, email or note.
      required: [booking_id, status, resource_id, starts_at, ends_at]
      properties:
        booking_id: { type: string, format: uuid }
        status: { type: string }
        resource_id: { type: string, format: uuid }
        service_id: { type: [string, 'null'], format: uuid }
        unit: { type: string, description: '`slot` · `night` · `day`.' }
        starts_at: { type: string, format: date-time }
        ends_at: { type: string, format: date-time }
        units: { type: [integer, 'null'] }
        guests: { type: [integer, 'null'] }
        price_mnt: { type: integer }
        deposit_mnt: { type: [integer, 'null'] }
        source: { type: string }
        confirmed_at: { type: [string, 'null'], format: date-time }
        cancelled_at: { type: [string, 'null'], format: date-time }
        cancel_initiator: { type: [string, 'null'] }
        balance_paid_at: { type: [string, 'null'], format: date-time }
        balance_method: { type: [string, 'null'] }

    WebhookReviewData:
      type: object
      description: The `data` of `review.created` and `review.updated` (2026-11) — the rating and state, not the text or photos.
      required: [review_id, product_id, rating]
      properties:
        review_id: { type: string, format: uuid }
        product_id: { type: string, format: uuid }
        rating: { type: integer, minimum: 1, maximum: 5 }
        status: { type: string, description: '`published` · `hidden`.' }
        created_at: { type: string, format: date-time }

    WebhookPaymentLinkData:
      type: object
      description: The `data` of `payment_link.paid` (2026-11) — a payment link or donation link was paid. No title, no payer details.
      required: [payment_link_id, kind, amount_mnt]
      properties:
        payment_link_id: { type: string, format: uuid }
        kind: { type: string, enum: [custom_invoice, donation] }
        amount_mnt: { type: integer }
        status: { type: string }
        paid_at: { type: [string, 'null'], format: date-time }

    WebhookSurveyResponseData:
      type: object
      description: The `data` of `survey.response_created` (2026-11) — ids only; the answers are never sent.
      required: [survey_id, response_id]
      properties:
        survey_id: { type: string, format: uuid }
        response_id: { type: string, format: uuid }
        order_id: { type: [string, 'null'], format: uuid }
        created_at: { type: string, format: date-time }

    WebhookProductData:
      type: object
      description: The `data` of every `product.*` event (`product.published` = the product went live, 2026-11).
      required: [product_id]
      properties:
        product_id: { type: string, format: uuid }
        status: { type: string }
        updated_at: { type: string }

    WebhookPingData:
      type: object
      description: The `data` of a console test.
      properties:
        message: { type: string, const: OpenShop webhook test }

    ConnectorTenant:
      type: object
      required: [tenant_id, tenant_slug, tenant_name, status, eligible]
      properties:
        tenant_id: { type: string, format: uuid }
        tenant_slug: { type: string }
        tenant_name: { type: string }
        status: { type: string }
        eligible: { type: boolean, description: Whether this shop can be paired right now. }

    ConnectorLinkRequest:
      type: object
      required: [link_id, workspace_id]
      description: Name the shop with either `tenant_id` or `tenant_slug`.
      properties:
        link_id: { type: string, format: uuid, description: The connector's own id for this pairing. Replaying it is idempotent. }
        tenant_id: { type: string, format: uuid }
        tenant_slug: { type: string }
        workspace_id: { type: string, format: uuid }
        workspace_name: { type: string }
        linked_by:
          type: string
          enum: [buildry_admin, openshop_admin]
          description: Which side's administrator performed the pairing. Defaults to `buildry_admin`.
        actor: { type: string, description: Who performed it, for the audit trail. }

    ConnectorLink:
      type: object
      required: [link_id, tenant_id, workspace_id, status, linked_by]
      properties:
        link_id: { type: string, format: uuid }
        tenant_id: { type: string, format: uuid }
        tenant_slug: { type: string }
        tenant_name: { type: string }
        workspace_id: { type: string, format: uuid }
        workspace_name: { type: string }
        status:
          type: string
          enum: [active, unlinked]
          description: Rows are never deleted — unlinking sets `unlinked` and stamps `unlinked_at`.
        linked_by: { type: string, enum: [buildry_admin, openshop_admin] }
        actor: { type: string }
        linked_at: { type: string, format: date-time }
        unlinked_at: { type: [string, 'null'], format: date-time }
