openapi: 3.1.0
info:
  title: Rondivo — API замовлень магазину
  version: "1"
  description: |
    API магазину на Rondivo для власної системи клієнта (CRM, облік). Частина 1: замовлення. Частина 2: повідомлення покупців боту магазину.

    - Адреса: `https://<магазин>.rondivo.com/api/v1/…`
    - Ключ: заголовок `Authorization: Bearer rdv_live_…` (робочий) або `rdv_test_…` (тестовий: бачить і змінює лише тестові замовлення — зроблені з акаунта власника магазину або члена команди).
    - Права ключа: `orders:read`, `orders:write`, `messages:read`, `messages:write`, `orders:refund` (повернення грошей — власник магазину вмикає його окремо, для вже створеного ключа). Ключ створює власник магазину в «Інтеграції»; показується один раз.
    - Цей опис кожен магазин віддає сам: `GET /api/v1/openapi.yaml` (відкрито, без ключа).
    - ⛔ Ніколи не передавайте CRM ключ бота магазину (з @BotFather): тоді бот перестане отримувати повідомлення покупців, а платформа попередить власника. Усе, що потрібно CRM, є в цьому API.
    - Не більше 10 запитів за секунду на ключ (запас 30); понад це — `429` з `Retry-After`.
    - Помилки: `{ "error": { "code": "…", "message": "…" } }` — стабільний англійський код, повідомлення українською.
    - Через API не можна позначити оплату. Повернути гроші покупцю може лише ключ із правом `orders:refund`: `POST /orders/{ref}/refund` (див. «Повернення грошей»).
    - Гроші: цілі копійки в полях `…_minor`; час: ISO 8601 зі зміщенням магазину (UTC+2, влітку UTC+3).

    ## Події (webhooks)
    Магазин надсилає `POST` із JSON на адресу, вказану в «Інтеграції», при кожній обраній події:
    `order.created`, `order.status_changed`, `order.paid`, `order.cancelled`, `order.tracking_added` (номер додано або замінено: тоді в `data` є `replaced_tracking_number`),
    `order.tracking_removed` (номер видалено: у `data` — `removed_tracking_number` і `parcel_id`),
    `order.change_requested` (покупець оплаченого, ще не відправленого замовлення просить скасувати його / змінити адресу чи відділення / змінити товари:
    у `data.change_request` — `id`, `kind` (`cancel` | `address` | `items`), `text` (слова покупця або null), `created_at`; магазин відповідає в панелі керування,
    відповідь видно як `order.cancelled` (гроші повернено через банк або вручну) чи `order.delivery_changed`), `order.delivery_changed` (магазин змінив адресу чи відділення
    на прохання покупця: в `data.change_request_id` — запит; нова адреса — у `data.order.delivery`), `order.repriced` (покупець додав промокод до замовлення
    з оплатою при отриманні, яке ще не зібрано: у `data` — `promo_code` і `discount_minor`; нові суми — в `data.order.money`), `return.created`, `return.status_changed`,
    `message.received` (покупець написав боту), `message.sent` (магазин відповів — з панелі керування, через API або автовідповідь).
    Заголовки: `X-Rondivo-Event`, `X-Rondivo-Delivery` (унікальний id доставки), `X-Rondivo-Timestamp` (секунди Unix),
    `X-Rondivo-Signature: sha256=<HMAC-SHA256(secret, timestamp + "." + body)>`.
    Доставка «щонайменше один раз»: дублікати впізнаються за `X-Rondivo-Delivery`; кожна подія замовлення має `data.order.version` -
    подію з меншим номером, що прийшла пізніше, слід пропустити. Відповідь 2xx = доставлено; інакше повтори з дедалі більшими паузами 24 години.
    Тіло: `{ id, type, created_at, shop: { id, domain }, data: { order } }` (для `return.*` — `data: { return, order }`;
    для `message.*` — `data: { conversation, message }`, див. схему `MessageEvent`).

    ## Як замінити накладну
    Накладну скасували в Новій пошті (помилка в даних отримувача, інше відділення) та створили нову для того самого замовлення:
    1. скасуйте стару накладну в кабінеті Нової пошти та створіть нову;
    2. `POST /orders/{ref}/tracking` з `"replace": true` і новим номером (`parcel_id` — коли посилок кілька). Старий номер лишається в «Журнал дій» магазину;
    усе, що стосувалося старої накладної (статус Нової пошти, накладений платіж, виплата), прибирається; статус замовлення НЕ змінюється — замовлення лишається відкритим.
    Покупець замовлення, яке вже «Відправлено», отримує одне повідомлення з новим посиланням для відстеження; до відправлення — нічого.
    Або в два кроки: `DELETE /orders/{ref}/tracking` (номер прибрано, подія `order.tracking_removed`), а потім звичайний `POST …/tracking`, коли нова накладна є.
    Без `"replace": true` посилка з номером відповідає `409 tracking_already_set` — як і раніше.
    Накладну видалили в Новій пошті, а номер у замовленні лишився: магазин бачить це при перевірці (статус «Видалено» або «Номер не знайдено»),
    повідомляє менеджерів магазину, а в `delivery.parcels[].carrier_status` стоїть «Видалено». Номер сам не зникає — його замінює менеджер або CRM.

    ## Відмова та повернення посилки
    Статус посилки в Новій пошті — `delivery.parcels[].carrier_status` (текст Нової пошти, оновлюється кожні ~30 хвилин): «Відмова одержувача», «Закінчився термін зберігання»
    тощо означають, що посилка повертається до відправника. Замовлення при цьому НЕ змінюється саме — лише коли посилка повернулась:
    - оплата при отриманні (`payment.method` = `cod`): `POST /orders/{ref}/status` з `{"status":"cancelled"}` — дозволено лише зі статусу `shipped`; товар повертається в залишки, покупець отримує повідомлення, подія `order.status_changed` (і `order.cancelled`, `cancel_reason` = `parcel_refused`);
    - оплата карткою через monobank: скасування зміною статусу неможливе (гроші вже в магазині) — це повернення грошей: `POST /orders/{ref}/refund` (право `orders:refund`, лише `paid` / `packed`, див. «Повернення грошей»); після відправлення — повернення товару та грошей оформляє магазин у панелі керування («Звернення»), CRM бачить його як `return.created` / `return.status_changed`;
    - оплата частинами: лише через панель керування («Звернення»).
    Посилку отримано → замовлення само стає `delivered` (подія `order.status_changed`); для оплати при отриманні — ще `order.paid`.

    ## Повернення грошей
    `POST /orders/{ref}/refund` із тілом `{}` повертає покупцю ВСЮ суму оплати карткою через monobank — тим самим шляхом, що кнопка «Повернути … через monobank» у панелі керування:
    банк повертає гроші на картку, за потреби робиться фіскальний чек повернення, замовлення стає `cancelled` (`cancel_reason` = `refunded_through_bank`), товар повертається в залишки,
    покупець отримує повідомлення, бонуси та промокод повертаються; події `order.status_changed` та `order.cancelled`. Часткове повернення (окремі позиції) — лише в панелі керування.
    - Право `orders:refund` вмикає ЛИШЕ власник магазину, для окремого ключа, в «Інтеграції» («Повернення коштів»); керівник не може. Тестовий ключ повертає гроші лише за тестові замовлення.
    - Заголовок `Idempotency-Key` обов'язковий (`400 idempotency_key_required`): з нього та ключа утворюється ідентифікатор повернення в банку, тому той самий запит ніколи не поверне гроші двічі — повторний запит отримує ту саму відповідь.
    - Перевірки, по порядку: замовлення є та видиме ключу (`404 order_not_found`) → гроші ще не повернено (`409 nothing_to_refund`: вже повернено повністю, або повернення ще обробляється) →
      оплата карткою через monobank (`409 not_refundable`: частинами, при отриманні, не оплачено) →
      статус `paid` або `packed` (`403 forbidden_transition`: після відправлення чи доставки — через «Звернення» в панелі керування) →
      денний ліміт магазину (`409 refund_limit_reached`).
    - Денний ліміт: власник задає в «Повернення коштів» кількість повернень (типово 10) та суму (типово 20 000 ₴) за календарну добу (UTC+2, влітку UTC+3); рахуються лише повернення через API (успішні та ті, що банк ще обробляє).
      `409 refund_limit_reached` — не повторюйте запит автоматично: решту повертає магазин у панелі керування, або власник змінює ліміт.
    - Відповідь `200` — банк повернув гроші (`refund.status` = `success`, замовлення в `order` вже `cancelled`). `202` — банк ще обробляє (`refund.status` = `processing`): магазин сам дочекається
      результату та завершить скасування; CRM побачить його як `order.cancelled`. `409 provider_refused` — банк відмовив, нічого не повернено. `409 no_credential` — у магазині не підключено monobank.
    - Про кожне повернення через API власник магазину отримує повідомлення в Telegram; у «Журнал дій» — запис «API: <назва ключа>».

    ## Повідомлення покупців (частина 2)
    Покупці пишуть боту магазину у приватному чаті; магазин зберігає кожне повідомлення та відповідає від імені бота.
    CRM читає розмови (`/conversations`) і повідомлення, відповідає (`POST …/messages`, лист іде від бота магазину) та бере вкладення (`/files/{file_id}`).
    Сталі ідентифікатори: `id` повідомлення (наш), `chat_id` і `telegram_message_id` (Telegram). Відповідь із CRM видно в панелі керування як «CRM: <назва ключа>», і навпаки.
    Тестовий ключ бачить лише тестові розмови — де покупцем є власник магазину або член команди (їхні акаунти Telegram).
    Обмеження Telegram: одне повідомлення покупцю за секунду; на `429` від Telegram магазин чекає та повторює. Покупець заблокував бота — `409 buyer_blocked_bot`.
servers:
  - url: https://{shop}.rondivo.com/api/v1
    variables:
      shop:
        default: demo
security:
  - bearerKey: []
paths:
  /ping:
    get:
      summary: Перевірка ключа
      responses:
        "200":
          description: Магазин, назва ключа, його права та вид
          content:
            application/json:
              example:
                ok: true
                shop: { id: demo, domain: demo.rondivo.com }
                key: { name: Моя CRM, kind: live, scopes: [orders:read, orders:write] }
                time: "2026-11-17T12:00:00.000Z"
        "401": { $ref: "#/components/responses/Error" }
        "403": { $ref: "#/components/responses/Error" }
  /orders:
    get:
      summary: Список замовлень
      description: Стабільний курсор за (updated_at, id); не більше 100 за раз.
      parameters:
        - { name: updated_since, in: query, schema: { type: string, format: date-time }, description: "Лише замовлення, змінені після цього моменту" }
        - { name: number, in: query, schema: { type: string, example: "261126-9740" }, description: "Замовлення з цим номером. Спільний номер покупки, що стала кількома замовленнями (261126-9740), знаходить усі її частини: 261126-9740-1, 261126-9740-2, …" }
        - { name: cursor, in: query, schema: { type: string }, description: "`next_cursor` з попередньої відповіді" }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        "200":
          description: Сторінка замовлень
          content:
            application/json:
              schema:
                type: object
                properties:
                  orders: { type: array, items: { $ref: "#/components/schemas/Order" } }
                  next_cursor: { type: [string, "null"] }
  /orders/{ref}:
    get:
      summary: Одне замовлення за id або номером
      description: "Спільний номер покупки, що стала кількома замовленнями (261126-9740), — не одне замовлення: відповідь 404 з кодом `order_split` і полем `parts` — номери частин (261126-9740-1, 261126-9740-2, …)."
      parameters: [{ $ref: "#/components/parameters/ref" }]
      responses:
        "200":
          description: Замовлення
          content:
            application/json:
              schema: { type: object, properties: { order: { $ref: "#/components/schemas/Order" } } }
              example:
                order: { $ref: "#/components/examples/order/value" }
        "404": { $ref: "#/components/responses/Error" }
  /orders/{ref}/status:
    post:
      summary: Змінити статус
      description: |
        Лише переходи, дозволені панелі керування: `packed`, `shipped`, `delivered`, `cancelled`.
        `paid` — ніколи; `cancelled` для оплаченого карткою замовлення — ніколи через цей запит (це повернення грошей: `POST /orders/{ref}/refund`). Покупець отримує
        ті самі повідомлення, що при зміні в панелі; у «Журнал дій» запис «API: <назва ключа>».
      parameters: [{ $ref: "#/components/parameters/ref" }, { $ref: "#/components/parameters/idem" }]
      requestBody:
        content:
          application/json:
            schema: { type: object, required: [status], properties: { status: { type: string, enum: [packed, shipped, delivered, cancelled] } } }
      responses:
        "200": { description: "Змінено", content: { application/json: { example: { ok: true, from: paid, to: packed, order: {} } } } }
        "403": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }
  /orders/{ref}/refund:
    post:
      summary: Повернути гроші покупцю (вся сума, через monobank)
      description: |
        Потрібне право `orders:refund` (вмикає лише власник магазину, окремо для ключа) та заголовок `Idempotency-Key`.
        Лише оплата карткою через monobank, лише статус `paid` або `packed`, лише вся сума, що лишилася; у межах денного ліміту магазину (кількість і сума за добу, UTC+2, влітку UTC+3).
        Робить те саме, що кнопка «Повернути … через monobank» у панелі керування: гроші на картку, чек повернення, замовлення `cancelled`
        (`cancel_reason` = `refunded_through_bank`), товар у залишки, повідомлення покупцю, події `order.status_changed` та `order.cancelled`.
        Власник магазину отримує повідомлення про кожне таке повернення; у «Журнал дій» — «API: <назва ключа>». Див. «Повернення грошей» угорі.
      parameters: [{ $ref: "#/components/parameters/ref" }, { $ref: "#/components/parameters/idemRequired" }]
      requestBody:
        content:
          application/json:
            schema: { type: object, additionalProperties: false, description: "Порожній об'єкт — повертається вся сума" }
            example: {}
      responses:
        "200": { description: "Банк повернув гроші; замовлення скасовано", content: { application/json: { example: { ok: true, refund: { id: 7f3a…, status: success, amount_minor: 80500, created_at: "2026-11-23T12:00:00.000Z" }, order: { status: cancelled, cancel_reason: refunded_through_bank } } } } }
        "202": { description: "Банк ще обробляє повернення (`processing`); магазин завершить скасування сам", content: { application/json: { example: { ok: true, refund: { id: 7f3a…, status: processing, amount_minor: 80500, created_at: "2026-11-23T12:00:00.000Z" }, order: { status: paid } } } } }
        "400": { description: "Немає `Idempotency-Key` (`idempotency_key_required`) або тіло не порожнє (`invalid_body`)", content: { application/json: { schema: { $ref: "#/components/responses/Error/content/application~1json/schema" } } } }
        "403": { description: "Ключ без права (`insufficient_scope`) або замовлення вже відправлено / доставлено / скасовано (`forbidden_transition`)", content: { application/json: { schema: { $ref: "#/components/responses/Error/content/application~1json/schema" } } } }
        "404": { $ref: "#/components/responses/Error" }
        "409": { description: "`not_refundable`, `nothing_to_refund`, `refund_limit_reached`, `provider_refused`, `no_credential`", content: { application/json: { schema: { $ref: "#/components/responses/Error/content/application~1json/schema" } } } }
  /orders/{ref}/tracking:
    post:
      summary: Додати або замінити номер накладної
      description: |
        Ті самі перевірки, що в панелі (Нова пошта — 14 цифр). Без `replace` — лише на посилку без номера (інакше `409 tracking_already_set`).
        З `"replace": true` — посилка з номером отримує новий: старий номер іде в «Журнал дій», усе, що стосувалося старої накладної, прибирається,
        статус замовлення не змінюється; покупець уже відправленого замовлення отримує повідомлення з новим посиланням. `parcel_id` — коли посилок кілька (із `replace` — обов'язково).
        Подія `order.tracking_added`; при заміні в її `data` є `replaced_tracking_number`.
      parameters: [{ $ref: "#/components/parameters/ref" }, { $ref: "#/components/parameters/idem" }]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              required: [tracking_number]
              properties:
                tracking_number: { type: string, example: "20450123456789" }
                parcel_id: { type: string, format: uuid }
                replace: { type: boolean, default: false, description: "true — замінити номер на посилці, що вже має номер (стару накладну спершу скасуйте в Новій пошті)" }
            example: { tracking_number: "20450987654321", replace: true }
      responses:
        "200":
          description: "Додано або замінено; `replaced_tracking_number` — старий номер (null, якщо номера не було)"
          content:
            application/json:
              example: { ok: true, parcel_id: 1b2c3d4e-0000-4000-8000-000000000001, replaced_tracking_number: "20450123456789", order: {} }
        "400": { $ref: "#/components/responses/Error" }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }
    delete:
      summary: Видалити номер накладної
      description: |
        Накладну скасували в Новій пошті; номер прибирається з посилки разом з усім, що стосувалося тієї накладної (статус, накладений платіж, виплата).
        Старий номер лишається в «Журнал дій» як «API: <назва ключа>». Статус замовлення не змінюється, покупець нічого не отримує; автоматична накладна для цієї посилки більше не створюється.
        `parcel_id` (у тілі або в запиті) — обов'язково, коли номери мають кілька посилок. Без номера — `404 no_tracking_number`. Подія `order.tracking_removed`.
      parameters:
        - { $ref: "#/components/parameters/ref" }
        - { $ref: "#/components/parameters/idem" }
        - { name: parcel_id, in: query, required: false, schema: { type: string, format: uuid }, description: "Посилка, з якої прибрати номер (або в тілі JSON)" }
      responses:
        "200":
          description: "Видалено"
          content:
            application/json:
              example: { ok: true, parcel_id: 1b2c3d4e-0000-4000-8000-000000000001, removed_tracking_number: "20450123456789", order: {} }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }
  /orders/{ref}/notes:
    post:
      summary: Внутрішня нотатка менеджера
      description: Покупець її ніколи не бачить; видно в панелі керування на сторінці замовлення.
      parameters: [{ $ref: "#/components/parameters/ref" }, { $ref: "#/components/parameters/idem" }]
      requestBody:
        content:
          application/json:
            schema: { type: object, required: [text], properties: { text: { type: string, maxLength: 2000 } } }
      responses:
        "201": { description: "Створено", content: { application/json: { example: { ok: true, note: { id: 8c2d…, text: "Передзвонити після 18:00", author: "API: Моя CRM", created_at: "2026-11-17T12:10:00.000Z" } } } } }
  /conversations:
    get:
      summary: Розмови з покупцями
      description: Один рядок на покупця, що писав боту. Стабільний курсор за (updated_at, id); не більше 100 за раз. Потрібне право `messages:read`.
      parameters:
        - { name: updated_since, in: query, schema: { type: string, format: date-time }, description: "Лише розмови, змінені після цього моменту" }
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        "200":
          description: Сторінка розмов
          content:
            application/json:
              schema:
                type: object
                properties:
                  conversations: { type: array, items: { $ref: "#/components/schemas/Conversation" } }
                  next_cursor: { type: [string, "null"] }
              example:
                conversations:
                  - { $ref: "#/components/examples/conversation/value" }
                next_cursor: null
        "403": { $ref: "#/components/responses/Error" }
  /conversations/{buyer_id}/messages:
    get:
      summary: Повідомлення однієї розмови
      description: Від найстаршого до найновішого; `since` — лише пізніші за момент; курсор для довгих розмов. Потрібне право `messages:read`.
      parameters:
        - { $ref: "#/components/parameters/buyer_id" }
        - { name: since, in: query, schema: { type: string, format: date-time } }
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 100 } }
      responses:
        "200":
          description: Розмова та її повідомлення
          content:
            application/json:
              schema:
                type: object
                properties:
                  conversation: { $ref: "#/components/schemas/Conversation" }
                  messages: { type: array, items: { $ref: "#/components/schemas/Message" } }
                  next_cursor: { type: [string, "null"] }
              example:
                conversation: { $ref: "#/components/examples/conversation/value" }
                messages:
                  - { $ref: "#/components/examples/messageIn/value" }
                  - { $ref: "#/components/examples/messageOut/value" }
                next_cursor: null
        "404": { $ref: "#/components/responses/Error" }
    post:
      summary: Відповісти покупцю
      description: |
        Текст до 4 000 символів, іде від бота магазину. `reply_to_message_id` — `telegram_message_id` повідомлення покупця, щоб відповідь була цитатою.
        Відповідь зберігається з її `telegram_message_id`, з'являється в панелі керування як «CRM: <назва ключа>» і в «Журнал дій» як «API: <назва ключа>».
        Покупець заблокував бота — `409 buyer_blocked_bot`, нічого не збережено. Потрібне право `messages:write`.
      parameters: [{ $ref: "#/components/parameters/buyer_id" }, { $ref: "#/components/parameters/idem" }]
      requestBody:
        content:
          application/json:
            schema: { type: object, required: [text], properties: { text: { type: string, maxLength: 4000 }, reply_to_message_id: { type: integer } } }
            example: { text: "Вітаю! Замовлення 261117-0003 вже в дорозі, завтра буде у відділенні.", reply_to_message_id: 1041 }
      responses:
        "201":
          description: Надіслано та збережено
          content:
            application/json:
              example:
                ok: true
                message: { $ref: "#/components/examples/messageOut/value" }
                conversation: { $ref: "#/components/examples/conversation/value" }
        "400": { $ref: "#/components/responses/Error" }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }
  /files/{file_id}:
    get:
      summary: Вкладення покупця
      description: Файл береться в Telegram у момент запиту (getFile) і передається як є; не більше 20 МБ (`413 file_too_large`). Лише `file_id` з повідомлень розмов цього ключа. Потрібне право `messages:read`.
      parameters: [{ name: file_id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: "Байти файлу; Content-Type і Content-Disposition від Telegram" }
        "404": { $ref: "#/components/responses/Error" }
        "413": { $ref: "#/components/responses/Error" }
        "502": { $ref: "#/components/responses/Error" }
  /openapi.yaml:
    get:
      summary: Цей опис API
      description: Відкрито, без ключа — для імпорту в CRM.
      security: []
      responses:
        "200": { description: "application/yaml" }
components:
  securitySchemes:
    bearerKey: { type: http, scheme: bearer }
  parameters:
    ref: { name: ref, in: path, required: true, schema: { type: string }, description: "id (uuid) або номер замовлення, напр. 261117-0003; частина розділеної покупки — з індексом, напр. 261126-9740-2" }
    idem: { name: Idempotency-Key, in: header, required: false, schema: { type: string, maxLength: 200 }, description: "Та сама відповідь на повторний запит протягом 24 годин; інше тіло з тим самим ключем — 422" }
    idemRequired: { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 200 }, description: "Обов'язковий для повернення грошей: той самий запит ніколи не поверне гроші двічі (ідентифікатор повернення в банку утворюється з ключа та цього заголовка); інше тіло з тим самим ключем — 422" }
    buyer_id: { name: buyer_id, in: path, required: true, schema: { type: string, format: uuid }, description: "Ідентифікатор розмови (покупця) — `buyer_id` зі списку розмов або з події" }
  responses:
    Error:
      description: Помилка
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: object
                properties:
                  code: { type: string, example: order_not_found }
                  message: { type: string, example: Замовлення не знайдено. }
  schemas:
    Order:
      type: object
      description: Замовлення — та сама форма в API та в подіях
      properties:
        id: { type: string, format: uuid }
        number: { type: string }
        group_id: { type: string, format: uuid, description: "Покупка, до якої належить замовлення: одне оформлення може стати кількома замовленнями (по одному на склад, якщо в магазині ввімкнено «Окреме замовлення для кожного складу»)" }
        group_number: { type: string, description: "Спільний номер покупки. Замовлення однієї покупки, що стала кількома, мають один номер з індексом: 261126-9740-1, 261126-9740-2, … — тут 261126-9740. Для звичайного замовлення — його власний номер" }
        group_index: { type: integer, minimum: 1, description: "Номер замовлення в покупці: 1, 2, …" }
        group_size: { type: integer, minimum: 1, description: "Скільки замовлень у покупці (1 — звичайне замовлення)" }
        created_at: { type: string }
        updated_at: { type: string }
        status: { type: string, enum: [awaiting_payment, confirmed, paid, packed, shipped, delivered, cancelled, expired] }
        test: { type: boolean }
        version: { type: integer, description: "Зростає з кожною подією замовлення" }
        currency: { type: string }
        buyer: { type: object, properties: { name: { type: string }, phone: { type: string }, email: { type: [string, "null"] }, comment: { type: [string, "null"] }, bot_blocked_at: { type: [string, "null"], format: date-time, description: "Коли бот магазину дізнався, що покупець заблокував його в Telegram (повідомлення про замовлення до нього не доходять — зателефонуйте); null = усе гаразд" }, bot_blocked_reason: { type: [string, "null"], enum: [blocked, not_started, deactivated, history, null], description: "Чому повідомлення не доходять: blocked — покупець заблокував бота; not_started — не натискав «Почати»; deactivated — акаунт Telegram видалено; history — позначено з даних до оновлення (заблокував бота); null = усе гаразд" }, telegram_user_id: { type: string, description: "Telegram-ідентифікатор покупця — той самий, що `telegram_user_id` розмови" }, buyer_id: { type: [string, "null"], format: uuid, description: "Той самий `buyer_id`, що в розмові покупця (`/conversations`); null — покупець ще не писав боту" } } }
        delivery:
          type: object
          properties:
            company: { type: string }
            type: { type: string, enum: [branch, postomat, courier] }
            city: { type: [string, "null"] }
            branch: { type: [string, "null"] }
            address: { type: [string, "null"] }
            street: { type: [string, "null"] }
            house: { type: [string, "null"] }
            flat: { type: [string, "null"] }
            call_before_dispatch: { type: [boolean, "null"] }
            price_minor: { type: integer }
            paid_by: { type: [string, "null"], enum: [shop, buyer, null] }
            tracking_numbers: { type: array, items: { type: string } }
            parcels:
              type: array
              description: "Посилки замовлення; `carrier_status` — останній статус Нової пошти словами (null, поки не перевірено; «Видалено» — накладну видалили в Новій пошті)"
              items:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  warehouse: { type: [string, "null"] }
                  city: { type: [string, "null"] }
                  carrier: { type: string }
                  tracking_number: { type: [string, "null"] }
                  carrier_status: { type: [string, "null"] }
                  price_minor: { type: integer }
                  paid_by: { type: [string, "null"], enum: [shop, buyer, null] }
        items:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              sku: { type: string }
              supplier_code: { type: [string, "null"] }
              name: { type: string }
              name_en: { type: string }
              quantity: { type: integer }
              unit_price_minor: { type: integer }
              old_price_minor: { type: [integer, "null"] }
              discount_minor: { type: integer }
              line_total_minor: { type: integer }
              parcel_id: { type: [string, "null"] }
        promo: { type: [object, "null"], properties: { code: { type: string }, discount_minor: { type: integer } } }
        discount_minor: { type: integer }
        bonuses_used_minor: { type: integer }
        subtotal_minor: { type: integer }
        total_minor: { type: integer }
        payment:
          type: object
          properties:
            method: { type: string, enum: [card, cod, parts] }
            state: { type: string, enum: [paid, awaiting, on_delivery, not_paid] }
            paid_at: { type: [string, "null"] }
            parts_count: { type: [integer, "null"] }
            parts_bank: { type: [string, "null"] }
            receipt_url: { type: [string, "null"] }
        cancel_reason: { type: [string, "null"] }
        notes: { type: array, items: { type: object, properties: { id: { type: string }, text: { type: string }, author: { type: string }, created_at: { type: string } } } }
    Conversation:
      type: object
      description: Один покупець, що писав боту
      properties:
        buyer_id: { type: string, format: uuid, description: "Сталий ідентифікатор розмови / покупця в магазині" }
        telegram_user_id: { type: string }
        chat_id: { type: string }
        name: { type: string }
        username: { type: [string, "null"] }
        test: { type: boolean, description: "Акаунт власника або члена команди — бачить лише тестовий ключ" }
        last_message_at: { type: [string, "null"] }
        last_direction: { type: [string, "null"], enum: [in, out, null], description: "in — останнє слово за покупцем («Без відповіді»), out — за магазином" }
        unread: { type: integer }
        blocked: { type: boolean, description: "Покупець заблокував бота (остання спроба відповісти не дійшла)" }
        updated_at: { type: string }
    Message:
      type: object
      properties:
        id: { type: string, format: uuid }
        telegram_message_id: { type: [integer, "null"] }
        direction: { type: string, enum: [in, out], description: "in — від покупця, out — від магазину" }
        kind: { type: string, enum: [text, photo, document, voice, video, sticker, location, contact, other] }
        text: { type: [string, "null"], description: "Текст або підпис до вкладення" }
        attachments:
          type: array
          items: { type: object, properties: { file_id: { type: string }, kind: { type: string }, size: { type: [integer, "null"] }, name: { type: [string, "null"] } } }
        reply_to: { type: [integer, "null"], description: "telegram_message_id повідомлення, на яке це відповідь" }
        author: { type: object, properties: { kind: { type: string, enum: [buyer, staff, api, auto] }, name: { type: [string, "null"], description: "«Олена (Підтримка)», «CRM: Моя CRM», «Автовідповідь»" } } }
        edited: { type: boolean }
        created_at: { type: string }
    MessageEvent:
      type: object
      description: "Тіло подій message.received і message.sent"
      properties:
        id: { type: string, format: uuid }
        type: { type: string, enum: [message.received, message.sent] }
        created_at: { type: string }
        shop: { type: object, properties: { id: { type: string }, domain: { type: string } } }
        data:
          type: object
          properties:
            conversation: { type: object, properties: { buyer_id: { type: string }, telegram_user_id: { type: string }, chat_id: { type: string }, name: { type: string }, username: { type: [string, "null"] }, test: { type: boolean } } }
            message: { $ref: "#/components/schemas/Message" }
  examples:
    conversation:
      summary: Розмова (вигадані дані)
      value:
        buyer_id: 3c1f8e2a-7d4b-4a6e-9f10-5b2c8d7e6a41
        telegram_user_id: "700123456"
        chat_id: "700123456"
        name: Оксана Приклад
        username: oksana_example
        test: false
        last_message_at: "2026-11-17T16:02:11+02:00"
        last_direction: out
        unread: 0
        blocked: false
        updated_at: "2026-11-17T16:02:11+02:00"
    messageIn:
      summary: Повідомлення від покупця (вигадані дані)
      value:
        id: 8a7b6c5d-1111-4000-8000-000000000011
        telegram_message_id: 1041
        direction: in
        kind: photo
        text: "Ось так виглядає посилка"
        attachments: [{ file_id: AgACAgIAAxkBAAIBQmZ0example, kind: photo, size: 184230, name: null }]
        reply_to: null
        author: { kind: buyer, name: Оксана Приклад }
        edited: false
        created_at: "2026-11-17T15:58:40+02:00"
    messageOut:
      summary: Відповідь магазину (вигадані дані)
      value:
        id: 8a7b6c5d-2222-4000-8000-000000000012
        telegram_message_id: 1042
        direction: out
        kind: text
        text: "Вітаю! Замовлення 261117-0003 вже в дорозі, завтра буде у відділенні."
        attachments: []
        reply_to: 1041
        author: { kind: api, name: "CRM: Моя CRM" }
        edited: false
        created_at: "2026-11-17T16:02:11+02:00"
    messageEvent:
      summary: Подія message.received (вигадані дані)
      value:
        id: 5d4c3b2a-3333-4000-8000-000000000013
        type: message.received
        created_at: "2026-11-17T15:58:41+02:00"
        shop: { id: demo, domain: demo.rondivo.com }
        data:
          conversation: { buyer_id: 3c1f8e2a-7d4b-4a6e-9f10-5b2c8d7e6a41, telegram_user_id: "700123456", chat_id: "700123456", name: Оксана Приклад, username: oksana_example, test: false }
          message: { $ref: "#/components/examples/messageIn/value" }
    trackingAddedEvent:
      summary: Подія order.tracking_added після заміни номера (вигадані дані)
      value:
        id: 6e5d4c3b-4444-4000-8000-000000000014
        type: order.tracking_added
        created_at: "2026-11-22T11:40:05+02:00"
        shop: { id: demo, domain: demo.rondivo.com }
        data:
          order: { $ref: "#/components/examples/order/value" }
          parcel_id: 1b2c3d4e-0000-4000-8000-000000000001
          replaced_tracking_number: "20450123456789"
    changeRequestedEvent:
      summary: Подія order.change_requested (вигадані дані)
      value:
        id: 8a7f6e5d-6666-4000-8000-000000000016
        type: order.change_requested
        created_at: "2026-11-23T10:12:00+02:00"
        shop: { id: demo, domain: demo.rondivo.com }
        data:
          order: { $ref: "#/components/examples/order/value" }
          change_request: { id: 2c3d4e5f-0000-4000-8000-000000000002, kind: address, text: "Будь ласка, відділення №12 замість №7", created_at: "2026-11-23T10:12:00+02:00" }
    trackingRemovedEvent:
      summary: Подія order.tracking_removed (вигадані дані)
      value:
        id: 7f6e5d4c-5555-4000-8000-000000000015
        type: order.tracking_removed
        created_at: "2026-11-22T11:35:10+02:00"
        shop: { id: demo, domain: demo.rondivo.com }
        data:
          order: { $ref: "#/components/examples/order/value" }
          parcel_id: 1b2c3d4e-0000-4000-8000-000000000001
          removed_tracking_number: "20450123456789"
    order:
      summary: Приклад замовлення (вигадані дані)
      value:
        id: 7f3a9c2e-5b1d-4e8a-9c6f-2d4b8a1e7c35
        number: "261117-0003"
        group_id: 7d0c2b1e-4f5a-4c3b-9e2d-1a2b3c4d5e6f
        group_number: "261117-0003"
        group_index: 1
        group_size: 1
        created_at: "2026-11-17T14:05:09+02:00"
        updated_at: "2026-11-17T15:20:41+02:00"
        status: packed
        test: false
        version: 3
        currency: UAH
        buyer: { name: Оксана Приклад, phone: "+380501234567", email: oksana@example.com, comment: "Дзвоніть після 18:00", bot_blocked_at: null, bot_blocked_reason: null, telegram_user_id: "700123456", buyer_id: 3c1f8e2a-7d4b-4a6e-9f10-5b2c8d7e6a41 }
        delivery:
          company: novaposhta
          type: branch
          city: Львів
          branch: "Відділення №7"
          address: null
          street: null
          house: null
          flat: null
          call_before_dispatch: true
          price_minor: 7000
          paid_by: buyer
          tracking_numbers: ["20450123456789"]
          parcels:
            - { id: 1b2c3d4e-0000-4000-8000-000000000001, warehouse: Основний склад, city: Київ, carrier: novaposhta, tracking_number: "20450123456789", carrier_status: null, price_minor: 7000, paid_by: buyer }
        items:
          - { id: 9a8b7c6d-0000-4000-8000-000000000002, sku: KET-200, supplier_code: SUP-KET-200, name: Чайник 2 л, name_en: Kettle 2 l, quantity: 1, unit_price_minor: 129900, old_price_minor: 149900, discount_minor: 20000, line_total_minor: 129900, parcel_id: 1b2c3d4e-0000-4000-8000-000000000001 }
          - { id: 9a8b7c6d-0000-4000-8000-000000000003, sku: CUP-SET, supplier_code: null, name: Набір чашок, name_en: Cup set, quantity: 2, unit_price_minor: 25000, old_price_minor: null, discount_minor: 0, line_total_minor: 50000, parcel_id: 1b2c3d4e-0000-4000-8000-000000000001 }
        promo: { code: WELCOME10, discount_minor: 17990 }
        discount_minor: 17990
        bonuses_used_minor: 5000
        subtotal_minor: 179900
        total_minor: 163910
        payment: { method: card, state: paid, paid_at: "2026-11-17T14:07:30+02:00", parts_count: null, parts_bank: null, receipt_url: "https://example.com/receipt/abc" }
        cancel_reason: null
        notes:
          - { id: 5e6f7a8b-0000-4000-8000-000000000004, text: "Передзвонити після 18:00", author: "API: Моя CRM", created_at: "2026-11-17T15:20:41+02:00" }
