openapi: 3.1.0
info:
  title: BloomCore Orders API
  version: 1.9.0
  description: |
    API чтения, создания, безопасного редактирования, полной замены состава и
    создания/изменения ещё не начатой доставки неоплаченного заказа, отдельной
    preview/apply-корректировки состава и существующей доставки оплаченного заказа,
    выпуска исправленной версии документа после применённой корректировки, смены
    статуса, просмотра оплат, регистрации подтверждённой внешней оплаты и
    source-bound внешнего возврата заказов конкретного магазина. Все
    CRM-идентификаторы во внешнем контракте являются UUID. Внутренние числовые ID
    не принимаются и не возвращаются.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: florio
security:
  - bearerAuth: []
tags:
  - name: Orders
    description: Чтение, создание и безопасные ограниченные изменения заказов текущего магазина.
paths:
  /orders:
    get:
      tags: [Orders]
      operationId: listOrders
      summary: Список заказов текущего магазина
      description: |
        Возвращает только заказы магазина, определённого поддоменом и токеном.
        Удалённые заказы не включаются. Сортировка: обновлённые недавно первыми.
      parameters:
        - $ref: '#/components/parameters/StatusFilter'
        - $ref: '#/components/parameters/SourceFilter'
        - $ref: '#/components/parameters/NumberFilter'
        - $ref: '#/components/parameters/DesiredFrom'
        - $ref: '#/components/parameters/DesiredTo'
        - $ref: '#/components/parameters/UpdatedSince'
        - $ref: '#/components/parameters/PerPage'
        - $ref: '#/components/parameters/Page'
      responses:
        '200':
          description: Пагинированный список заказов.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderListResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationFailed'
    post:
      tags: [Orders]
      operationId: createOrder
      summary: Создать заказ в текущем магазине
      description: |
        Создаёт заказ строго в магазине поддомена. Позиции принимаются только по UUID
        опубликованного активного каталога, а цены, скидки, доставка, итог и резерв
        рассчитываются CRM. Передавать цену, итог, status, source или store_id запрещено.
        Заголовок Idempotency-Key обязателен. Повтор того же запроса с тем же ключом
        возвращает исходный результат; другой payload с тем же ключом получает 409.
        Необязательный external_order_id обеспечивает долговременную дедупликацию
        внутри текущих tenant, магазина и API-токена.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateOrderRequest'
            example:
              external_order_id: web-2026-000184
              customer:
                name: Анна Петрова
                phone: '+79990001122'
                email: anna@example.test
              recipient:
                same_as_customer: true
              items:
                - type: product
                  product_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef31
                  quantity: 3
              fulfillment:
                type: pickup
              desired_at: '2026-07-27T12:00:00+06:00'
              payment_method: pay_on_delivery
              comment: Позвонить перед готовностью
      responses:
        '201':
          description: Заказ создан. Возвращаются серверные суммы, UUIDv7 и номер заказа.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateOrderResponse'
        '200':
          description: Ранее созданный заказ возвращён по совпавшему external_order_id.
          headers:
            External-Order-Replayed:
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateOrderResponse'
        '400':
          description: Отсутствует или некорректен Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: Конфликт Idempotency-Key или external_order_id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /orders/{orderId}:
    get:
      tags: [Orders]
      operationId: showOrder
      summary: Детальная карточка заказа
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '200':
          description: Заказ текущего магазина.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderDetailResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags: [Orders]
      operationId: updateOrder
      summary: Исправить операционные данные неоплаченного заказа
      description: |
        Требует scope и CRM-право orders.update. Изменяет только контактные snapshots,
        получателя, desired_at, комментарий, признаки сюрприза/звонка и открытку.
        expected_edit_version обязателен и берётся из детальной карточки или status endpoint.
        Состав, доставка, цены, скидки, оплата, статус, источник, магазин, назначения,
        pipeline и SLA запрещены. После первой успешной оплаты или в финальном статусе
        обычное редактирование блокируется. Idempotency-Key обязателен.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateOrderRequest'
            example:
              expected_edit_version: 2454783eb75898015db1c4178dd8b3a4a7241bf6d8ed62eb22db4625796c45b2
              customer:
                name: Анна Петрова
                phone: '+79990001122'
                email: anna.new@example.test
              recipient:
                same_as_customer: false
                name: Мария Петрова
                phone: '+79990003344'
              desired_at: '2026-07-28T13:30:00+06:00'
              comment: Позвонить покупателю перед готовностью
              is_surprise: true
              do_not_call_recipient: true
              greeting_card:
                message: С праздником!
                signature: Анна
      responses:
        '200':
          description: Изменение выполнено либо возвращён сохранённый idempotent replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateOrderResponse'
        '400':
          description: Отсутствует или некорректен Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            Устаревшая edit version, отсутствие фактических изменений, оплаченный или
            финальный заказ либо конфликт Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Некорректные контакты либо запрещённые/неизвестные поля.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/items:
    put:
      tags: [Orders]
      operationId: replaceOrderItems
      summary: Полностью заменить состав неоплаченного заказа
      description: |
        Требует scope и CRM-право orders.update. Атомарно освобождает прежние
        складские резервы и готовые букеты, удаляет активные строки, повторно
        разрешает новый состав по опубликованному каталогу текущего магазина,
        применяет актуальные серверные цены и перестраивает резервы.
        Клиентские цены, скидки, итоги и лишние поля запрещены. Каждая позиция
        имеет закрытую type-specific форму. expected_edit_version и
        Idempotency-Key обязательны. Команда доступна только до первой успешной
        оплаты и при отсутствии активной платежной сессии, скидки, промокода или
        бонусного списания; иначе требуется специализированная корректировка.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReplaceOrderItemsRequest'
            example:
              expected_edit_version: 2454783eb75898015db1c4178dd8b3a4a7241bf6d8ed62eb22db4625796c45b2
              items:
                - type: product
                  product_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef31
                  quantity: 5
                - type: recipe
                  recipe_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef32
                  variant_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef33
                  quantity: 1
      responses:
        '200':
          description: Состав заменён либо возвращён сохранённый idempotent replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReplaceOrderItemsResponse'
        '400':
          description: Отсутствует или некорректен Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            Устаревшая edit version, финальный заказ, оплата, активная платежная
            сессия, скидочная фиксация либо конфликт Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Закрытая форма нарушена либо позиция недоступна в каталоге/остатках.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/corrections/items/preview:
    post:
      tags: [Orders]
      operationId: previewPaidOrderItemsCorrection
      summary: Рассчитать корректировку состава оплаченного заказа
      description: |
        Read-only preflight для активного заказа, по которому уже была успешная
        оплата. Требует отдельный scope и CRM-право orders.correct. Возвращает
        непрозрачную expected_version, текущие и предлагаемые суммы, финансовую
        дельту, сумму к доплате/доступную к возврату и изменение складского резерва.

        Существующая строка адресуется только UUID строки заказа и сохраняет
        переданные оператором цену/скидку. Новая строка получает клиентский UUIDv7,
        тип и UUID каталога; CRM повторно проверяет актуальную цену и доступность.
        Preview ничего не записывает, не резервирует, не создаёт оплату/возврат и
        не принимает Idempotency-Key. После любого изменения заказа, оплаты,
        payment intent или резерва preview необходимо получить заново.
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OrderItemsCorrectionPreviewRequest'
            example:
              reason: Клиент увеличил количество роз
              items:
                - item_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef34
                  qty: '3.000'
                  unit_price: '350.00'
                  discount_total: '0.00'
                - source: new
                  line_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef35
                  line_type: product
                  catalog_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef31
                  qty: '1.000'
                  expected_unit_price: '525.00'
      responses:
        '200':
          description: Актуальный план корректировки без изменения данных.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderItemsCorrectionPreviewResponse'
        '400':
          description: Для read-only preview ошибочно передан Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет отдельного scope/CRM-права orders.correct.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Заказ неоплачен, завершён либо имеет активное намерение онлайн-оплаты.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Закрытая форма нарушена, причина/цена/количество некорректны или каталог недоступен.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/corrections/items:
    post:
      tags: [Orders]
      operationId: applyPaidOrderItemsCorrection
      summary: Применить рассчитанную корректировку состава
      description: |
        Атомарно применяет только ранее рассчитанный payload к той же версии
        оплаченного заказа. Требует отдельный scope/CRM-право orders.correct,
        expected_version из свежего preview и новый UUIDv7 Idempotency-Key.
        Под row lock повторно проверяются заказ, оплаты, payment intent, каталог,
        остатки и резервы. CRM создаёт immutable before/after revisions и correction,
        пересобирает строки/резервы и обновляет суммы заказа.

        Положительная дельта только формирует amount_to_collect, отрицательная —
        amount_available_to_refund. Endpoint не создаёт оплату, возврат, документ,
        фискальный чек или уведомление автоматически. Повтор тех же path, payload
        и UUIDv7 возвращает исходный результат; повтор ключа с другим запросом
        получает 409. В ответе доступны только публичные UUID и агрегаты.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/CorrectionIdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ApplyOrderItemsCorrectionRequest'
            example:
              expected_version: 2454783eb75898015db1c4178dd8b3a4a7241bf6d8ed62eb22db4625796c45b2
              reason: Клиент увеличил количество роз
              items:
                - item_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef34
                  qty: '3.000'
                  unit_price: '350.00'
                  discount_total: '0.00'
      responses:
        '200':
          description: Корректировка применена либо возвращён безопасный idempotent replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApplyOrderItemsCorrectionResponse'
        '400':
          description: Idempotency-Key отсутствует либо не является UUIDv7.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет отдельного scope/CRM-права orders.correct.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            expected_version устарела, заказ недоступен для корректировки либо
            Idempotency-Key уже связан с другим запросом.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Закрытая форма нарушена либо новая позиция/остаток/цена недоступны.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/corrections/delivery/preview:
    post:
      tags: [Orders]
      operationId: previewPaidOrderDeliveryCorrection
      summary: Рассчитать изменение существующей доставки оплаченного заказа
      description: |
        Read-only preflight изменения адреса, получателя, зоны, интервала и стоимости
        существующей незавершённой доставки. Требует token scope orders.correct и
        CRM-права orders.correct + delivery.update. Доставка, зона и интервал
        разрешаются только в tenant/store заказа.

        В calculated CRM использует актуальный тариф зоны и интервала; delivery_price
        передавать нельзя. В manual стоимость обязательна и повторно нормализуется
        сервером. Preview возвращает только UUID и финансовые агрегаты: адрес, телефон,
        имя получателя и остальные PII не отражаются в response. Команда ничего не
        записывает, не создаёт оплату/возврат и не принимает Idempotency-Key.
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OrderDeliveryCorrectionPreviewRequest'
            example:
              reason: Клиент изменил адрес и интервал доставки
              delivery_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef63
              zone_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef61
              interval_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef62
              recipient_name: Мария Петрова
              recipient_phone: '+79990003344'
              city: Омск
              address: ул. Мира, 8
              entrance: '2'
              floor: '5'
              apartment: '15'
              intercom: '15'
              scheduled_from: '2026-08-02T03:00:00Z'
              scheduled_to: '2026-08-02T05:00:00Z'
              price_mode: manual
              delivery_price: '150.00'
      responses:
        '200':
          description: Актуальный план изменения доставки без записи данных.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderDeliveryCorrectionPreviewResponse'
        '400':
          description: Для read-only preview ошибочно передан Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope orders.correct или одного из обязательных CRM-прав.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Заказ или доставка недоступны для корректировки.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Закрытая форма, адрес, время, стоимость, зона или интервал некорректны.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/corrections/delivery:
    post:
      tags: [Orders]
      operationId: applyPaidOrderDeliveryCorrection
      summary: Применить рассчитанное изменение доставки
      description: |
        Атомарно применяет тот же payload к той же версии существующей доставки.
        Требует scope orders.correct, CRM-права orders.correct + delivery.update,
        expected_version из свежего preview и UUIDv7 Idempotency-Key. Под row lock
        повторно проверяются заказ, доставка, успешная оплата, активный payment intent,
        зона, интервал и тариф.

        Успех обновляет защищённые поля доставки, синхронизирует итог заказа и создаёт
        immutable before/after revisions с correction типа delivery. Положительная
        дельта не списывает деньги, отрицательная не выполняет возврат. Endpoint не
        создаёт и не отменяет доставку, не меняет статус/курьера и не отправляет
        уведомление. Response не содержит PII или внутренних ID.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/CorrectionIdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ApplyOrderDeliveryCorrectionRequest'
            example:
              expected_version: 2454783eb75898015db1c4178dd8b3a4a7241bf6d8ed62eb22db4625796c45b2
              reason: Клиент изменил адрес и интервал доставки
              delivery_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef63
              zone_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef61
              interval_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef62
              recipient_name: Мария Петрова
              recipient_phone: '+79990003344'
              city: Омск
              address: ул. Мира, 8
              scheduled_from: '2026-08-02T03:00:00Z'
              scheduled_to: '2026-08-02T05:00:00Z'
              price_mode: manual
              delivery_price: '150.00'
      responses:
        '200':
          description: Корректировка применена либо возвращён безопасный replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApplyOrderDeliveryCorrectionResponse'
        '400':
          description: Idempotency-Key отсутствует либо не является UUIDv7.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope orders.correct или одного из обязательных CRM-прав.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            expected_version устарела, заказ/доставка недоступны либо
            Idempotency-Key уже связан с другим запросом.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Закрытая форма, адрес, время, стоимость, зона или интервал некорректны.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/corrections/delivery/create/preview:
    post:
      tags: [Orders]
      operationId: previewPaidOrderDeliveryCreation
      summary: Рассчитать добавление доставки к оплаченному заказу
      description: |
        Read-only preflight для оплаченного заказа без карточки доставки. Требует
        token scope orders.correct и CRM-права orders.correct + delivery.create.
        Магазин определяется поддоменом, зона и интервал разрешаются только в его
        активном каталоге. delivery_uuid, store_id, status, courier_id и currency_code
        передавать запрещено.

        Preview возвращает только публичные UUID и финансовые агрегаты, не записывает
        доставку и не принимает Idempotency-Key. Положительная дельта означает сумму,
        которую еще требуется провести отдельной платежной командой.
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OrderDeliveryLifecycleCreatePreviewRequest'
            example:
              reason: Доставка пропущена при оформлении заказа
              zone_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef61
              interval_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef62
              recipient_name: Мария Петрова
              recipient_phone: '+79990003344'
              city: Омск
              address: ул. Мира, 8
              scheduled_from: '2026-08-02T03:00:00Z'
              scheduled_to: '2026-08-02T05:00:00Z'
              price_mode: calculated
      responses:
        '200':
          description: План добавления доставки без записи данных.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderDeliveryLifecyclePreviewResponse'
        '400':
          description: Для preview ошибочно передан Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope orders.correct или обязательного CRM-права.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Заказ не оплачен, завершен либо уже имеет доставку.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /orders/{orderId}/corrections/delivery/create:
    post:
      tags: [Orders]
      operationId: applyPaidOrderDeliveryCreation
      summary: Добавить доставку к оплаченному заказу
      description: |
        Атомарно применяет тот же payload по expected_version из свежего preview.
        Требует UUIDv7 Idempotency-Key. Под row lock повторно проверяет отсутствие
        доставки, права, заказ, оплату, зону, интервал и тариф. CRM сама создаёт UUIDv7
        доставки и статус planned, синхронизирует итог заказа и сохраняет immutable
        before/after revisions.

        Команда не создаёт оплату, возврат или фискальный чек. Сетевой повтор обязан
        использовать тот же ключ и тот же payload. Response не содержит PII и bigint ID.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/CorrectionIdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ApplyOrderDeliveryLifecycleCreateRequest'
      responses:
        '200':
          description: Доставка создана либо возвращён безопасный replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApplyOrderDeliveryCorrectionResponse'
        '400':
          description: Idempotency-Key отсутствует либо не является UUIDv7.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope orders.correct или обязательного CRM-права.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Версия устарела, доставка уже существует или ключ занят другой командой.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /orders/{orderId}/corrections/delivery/cancel/preview:
    post:
      tags: [Orders]
      operationId: previewPaidOrderDeliveryCancellation
      summary: Рассчитать отмену доставки оплаченного заказа
      description: |
        Read-only preflight перевода оплаченного заказа на самовывоз. Требует scope
        orders.correct и CRM-права orders.correct + delivery.update. Body закрыт и
        принимает только reason и UUID доставки этого заказа. Доставленную или уже
        отменённую доставку отменять нельзя. Preview не принимает Idempotency-Key.
      parameters:
        - $ref: '#/components/parameters/OrderId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OrderDeliveryLifecycleCancelPreviewRequest'
            example:
              reason: Клиент выбрал самовывоз после оплаты
              delivery_uuid: 019f7c83-a91d-7238-9c0b-28b10ad9ef63
      responses:
        '200':
          description: План отмены доставки без записи данных.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderDeliveryLifecyclePreviewResponse'
        '400':
          description: Для preview ошибочно передан Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope orders.correct или обязательного CRM-права.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Заказ или доставка недоступны для отмены.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /orders/{orderId}/corrections/delivery/cancel:
    post:
      tags: [Orders]
      operationId: applyPaidOrderDeliveryCancellation
      summary: Отменить доставку оплаченного заказа
      description: |
        По свежей expected_version атомарно переводит доставку в cancelled, обнуляет
        её стоимость и устанавливает заказу delivery_status not_required. Требует
        UUIDv7 Idempotency-Key. Создаёт immutable revisions и correction типа delivery.

        Рассчитанный amount_available_to_refund не является выполненным возвратом:
        деньги и чек обрабатываются отдельным финансовым сценарием. Удаление карточки
        доставки, смена магазина и автоматическое создание новой доставки запрещены.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/CorrectionIdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ApplyOrderDeliveryLifecycleCancelRequest'
      responses:
        '200':
          description: Доставка отменена либо возвращён безопасный replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApplyOrderDeliveryCorrectionResponse'
        '400':
          description: Idempotency-Key отсутствует либо не является UUIDv7.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope orders.correct или обязательного CRM-права.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Версия устарела, доставка недоступна или ключ занят другой командой.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /orders/{orderId}/documents/{documentId}/corrections/preview:
    post:
      tags: [Orders]
      operationId: previewCorrectedOrderDocument
      summary: Проверить возможность выпуска исправленной версии документа
      description: |
        Read-only preflight для действующего документа заказа. Требует отдельный
        token scope documents.correct и CRM-права documents.update + orders.correct
        в магазине поддомена. Source document должен быть generated, не иметь
        successor и предшествовать последней applied-корректировке заказа.

        Body должен быть пустым. Preview возвращает только публичные UUID, тип
        корректировки, HMAC-версию заказа и следующий номер версии документа.
        Причина корректировки, HTML, PDF, S3 key, metadata, request hash и контакты
        клиента не возвращаются. Idempotency-Key запрещён.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/OrderDocumentId'
      responses:
        '200':
          description: Выпуск доступен; возвращены безопасные параметры apply.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderDocumentCorrectionPreviewResponse'
        '400':
          description: Для preview ошибочно передан Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope documents.correct или обязательного CRM-права.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Документ не является действующей версией либо новой корректировки нет.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /orders/{orderId}/documents/{documentId}/corrections:
    post:
      tags: [Orders]
      operationId: issueCorrectedOrderDocument
      summary: Выпустить новую версию документа по корректировке заказа
      description: |
        Атомарно переводит source document в superseded и создаёт generated
        successor по исходному scoped-шаблону и authoritative состоянию заказа.
        Требует scope documents.correct, CRM-права documents.update + orders.correct,
        correction_id и expected_version из свежего preview, обязательную причину и
        новый UUIDv7 Idempotency-Key.

        HTML сохраняется в отдельном private S3 prefix по UUID новой версии, PDF
        ставится в очередь после commit. Replay возвращает тот же документ. Endpoint
        не аннулирует, не отправляет и не скачивает документ; response не содержит
        HTML/PDF, S3 path, PII, metadata, request hash или внутренние ID.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/OrderDocumentId'
        - $ref: '#/components/parameters/CorrectionIdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ApplyOrderDocumentCorrectionRequest'
            example:
              correction_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef71
              expected_version: 2454783eb75898015db1c4178dd8b3a4a7241bf6d8ed62eb22db4625796c45b2
              reason: Выпуск счета после согласованной корректировки заказа
      responses:
        '200':
          description: Новая версия выпущена либо возвращён безопасный replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApplyOrderDocumentCorrectionResponse'
        '400':
          description: Idempotency-Key отсутствует либо не является UUIDv7.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope documents.correct или одного из обязательных CRM-прав.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            expected_version устарела, документ/корректировка недоступны либо
            Idempotency-Key уже связан с другим выпуском.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Закрытый payload, UUID корректировки или причина некорректны.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/delivery:
    put:
      tags: [Orders]
      operationId: upsertOrderDelivery
      summary: Создать или изменить ещё не начатую доставку заказа
      description: |
        Требует scope и CRM-право orders.update. Создаёт доставку для заказа без
        доставки либо полностью заменяет адрес, активную зону и интервал доставки,
        пока существующая доставка имеет статус planned или failed. CRM сама
        устанавливает получателя из заказа, операционный статус planned, время из
        desired_at, валюту и цену по настройкам зоны/интервала текущего магазина.

        Клиенту запрещено передавать цену, валюту, статус, курьера, магазин и другие
        служебные поля. expected_edit_version и Idempotency-Key обязательны.
        Оплаченный или финальный заказ, активная платёжная сессия и доставка в
        статусе assigned, in_delivery, delivered или cancelled возвращают 409.
        Команда не отменяет доставку и не переключает заказ на самовывоз.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpsertOrderDeliveryRequest'
            example:
              expected_edit_version: 2454783eb75898015db1c4178dd8b3a4a7241bf6d8ed62eb22db4625796c45b2
              delivery_zone_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef61
              delivery_interval_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef62
              city: Омск
              address: ул. Ленина, 1
              entrance: '2'
              floor: '5'
              apartment: '15'
              intercom: '15'
              comment: Позвонить заранее
      responses:
        '200':
          description: Доставка создана/изменена либо возвращён сохранённый idempotent replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpsertOrderDeliveryResponse'
        '400':
          description: Отсутствует или некорректен Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            Устаревшая edit version, финальный/оплаченный заказ, активная платёжная
            сессия, уже начатая/завершённая/отменённая доставка либо конфликт
            Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: |
            Закрытая форма нарушена, адрес некорректен либо UUID зоны/интервала
            неактивен или не принадлежит текущему магазину.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/status:
    get:
      tags: [Orders]
      operationId: showOrderStatus
      summary: Текущее состояние заказа
      description: Компактный endpoint для периодической сверки статуса интеграцией.
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '200':
          description: Текущие статусы заказа.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderStatusResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags: [Orders]
      operationId: updateOrderStatus
      summary: Перевести заказ в другой статус
      description: |
        Требует scope orders.update и CRM-право orders.update. Выполняет разрешённый
        переход общей воронки строго в текущем магазине.
        target_status_id и expected_status_id являются UUID статусов CRM. Ожидаемый
        статус защищает от перезаписи конкурентного изменения. Idempotency-Key обязателен.
        Отмена является обычным разрешённым переходом и всегда требует reason.
        pipeline_id, store_id, цены, состав, назначения и SLA-поля передавать запрещено.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateOrderStatusRequest'
            example:
              expected_status_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef42
              target_status_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef43
              reason: Заказ принят менеджером
      responses:
        '200':
          description: Переход выполнен либо возвращён сохранённый idempotent replay.
          headers:
            Idempotency-Replayed:
              description: Присутствует со значением true у cache replay.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateOrderStatusResponse'
        '400':
          description: Отсутствует или некорректен Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            Устаревший expected_status_id, повторный/запрещённый переход,
            финальный заказ либо конфликт Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: Недоступный UUID статуса, отсутствующая причина либо запрещённые поля.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/payments:
    get:
      tags: [Orders]
      operationId: listOrderPayments
      summary: Оплаты и возвраты заказа
      description: |
        Возвращает append-only финансовый ledger заказа текущего магазина. Требует
        scope payments.view, CRM-права orders.view и payments.view. Ответ включает
        суммы заказа, записи оплат/возвратов, безопасные данные способа оплаты,
        фискальный статус и состояние provider-refund. Provider reference, касса,
        смена, сотрудник, комментарий, metadata, credentials и внутренние ID
        намеренно не публикуются. Query-параметры не поддерживаются.
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '200':
          description: Финансовое состояние заказа и хронологический ledger.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderPaymentLedgerResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          description: Передан неподдерживаемый query-параметр.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
    post:
      tags: [Orders]
      operationId: recordConfirmedExternalOrderPayment
      summary: Зарегистрировать подтверждённую внешнюю оплату
      description: |
        Регистрирует деньги, уже безусловно подтверждённые внешним терминалом или
        банковской системой. Требует token scope payments.create и CRM-права
        orders.view, payments.view и payments.create в текущем магазине.

        Разрешены только активные эффективные способы типа card и bank_transfer.
        Наличные проводятся через POS и открытую кассовую смену; online_card — через
        payment intent и подписанный callback провайдера; бонусы и сертификаты —
        через специализированные доменные процессы. Этот endpoint нельзя использовать
        для обхода эквайринга, фискализации, кассовой смены или проверки фактического
        зачисления денег.

        Idempotency-Key защищает сетевой повтор, а external_payment_id обеспечивает
        долговременную дедупликацию в области API-токена. Повтор того же внешнего
        платежа возвращает исходную запись; повтор с другой суммой, заказом или
        способом оплаты получает 409. CRM самостоятельно задаёт UUID операции,
        валюту, status, fiscal_status, provider, paid_at, сотрудника и metadata.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateConfirmedExternalPaymentRequest'
            example:
              external_payment_id: terminal-2026-000184
              payment_method_id: 019f7c83-a91d-7238-9c0b-28b10ad9ef51
              amount: '2500.00'
              expected_order_revision: 8c573d62f67bf73f95dcf3426e6790ebdb1a98d9d3386051407e27ef4c80f9b2
              expected_payment_method_revision: 29f83ce8e4b6653c0437add937d0724eaf7585d404a0a21b2981ed46eb6089a4
              confirmed_external: true
      responses:
        '201':
          description: Подтверждённая внешняя оплата зарегистрирована.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConfirmedExternalPaymentResponse'
        '200':
          description: Возвращён долговременный replay существующей внешней оплаты.
          headers:
            External-Payment-Replayed:
              description: Имеет значение true для replay по external_payment_id.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConfirmedExternalPaymentResponse'
        '400':
          description: Отсутствует или некорректен Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope payments.create либо необходимых CRM-прав.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            Устарела ревизия заказа/способа оплаты, заказ уже оплачен или отменён,
            external_payment_id/Idempotency-Key конфликтует с другим запросом.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: |
            Неподдерживаемый способ оплаты, сумма вне допустимого остатка,
            confirmed_external не равен true либо присутствуют запрещённые поля.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
  /orders/{orderId}/payments/{paymentId}/refunds:
    post:
      tags: [Orders]
      operationId: recordConfirmedExternalOrderRefund
      summary: Зарегистрировать подтверждённый внешний возврат
      description: |
        Фиксирует возврат, уже безусловно подтверждённый внешним терминалом или
        банковской системой. Требует token scope payments.refund и CRM-права
        orders.view, payments.view и payments.refund в текущем магазине.

        Исходная оплата должна быть успешной card либо bank_transfer записью,
        ранее созданной только через POST /orders/{orderId}/payments. Возврат
        source-bound: сумма ограничена остатком конкретной оплаты. POS, CRM,
        online_card/provider, bonus, certificate и subscription платежи этим
        endpoint не возвращаются.

        Получите expected_order_revision, expected_payment_revision,
        refundable_amount и external_refund_available из свежего
        GET /orders/{orderId}/payments. Idempotency-Key защищает сетевой повтор,
        external_refund_id обеспечивает долговременную дедупликацию в области
        текущего API-токена. После ротации токена интеграция обязана хранить
        собственную карту выполненных возвратов.
      parameters:
        - $ref: '#/components/parameters/OrderId'
        - $ref: '#/components/parameters/PaymentId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateConfirmedExternalRefundRequest'
            example:
              external_refund_id: terminal-refund-2026-000184
              amount: '500.00'
              expected_order_revision: 5e6097f28cebb4b76209db8d32c4f8d916dc84cc10d973d9cfba31ab00d290cb
              expected_payment_revision: d47956386639e23ce078dfcb8e209632ab67850208e0e857371d0aa79591ffac
              confirmed_external: true
      responses:
        '201':
          description: Подтверждённый внешний возврат зарегистрирован.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConfirmedExternalRefundResponse'
        '200':
          description: Возвращён долговременный replay существующего внешнего возврата.
          headers:
            External-Refund-Replayed:
              description: Имеет значение true для replay по external_refund_id.
              schema:
                type: string
                const: 'true'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConfirmedExternalRefundResponse'
        '400':
          description: Отсутствует или некорректен Idempotency-Key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          description: Нет scope payments.refund либо необходимых CRM-прав.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            Устарела revision заказа/исходной оплаты, остаток уже возвращён,
            изменилась валюта либо external_refund_id/Idempotency-Key конфликтует.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: |
            Исходная оплата или способ не поддерживается, сумма вне остатка,
            confirmed_external не равен true либо присутствуют запрещённые поля.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: Sanctum
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Уникальный ключ mutation длиной 8–128 символов.
      schema:
        type: string
        minLength: 8
        maxLength: 128
        pattern: '^[A-Za-z0-9._:-]+$'
    CorrectionIdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Новый UUIDv7 для одной попытки применения корректировки.
      schema:
        type: string
        format: uuid
        pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
      example: 019f7c83-a91d-7238-9c0b-28b10ad9ef39
    OrderId:
      name: orderId
      in: path
      required: true
      description: UUID заказа текущего магазина.
      schema:
        type: string
        format: uuid
    OrderDocumentId:
      name: documentId
      in: path
      required: true
      description: UUID действующей версии документа указанного заказа.
      schema:
        type: string
        format: uuid
    PaymentId:
      name: paymentId
      in: path
      required: true
      description: Публичный UUID конкретной исходной оплаты заказа.
      schema:
        type: string
        format: uuid
      example: 019f7c83-a91d-7238-9c0b-28b10ad9ef3a
    StatusFilter:
      name: status
      in: query
      schema:
        type: string
        maxLength: 64
      description: Технический код системного или пользовательского статуса.
    SourceFilter:
      name: source
      in: query
      schema:
        type: string
      description: Активный или исторически используемый код источника tenant.
    NumberFilter:
      name: number
      in: query
      schema:
        type: string
        maxLength: 64
      description: Точный номер заказа.
    DesiredFrom:
      name: desired_from
      in: query
      schema:
        type: string
        format: date-time
    DesiredTo:
      name: desired_to
      in: query
      schema:
        type: string
        format: date-time
    UpdatedSince:
      name: updated_since
      in: query
      schema:
        type: string
        format: date-time
      description: Выбрать заказы, изменённые не раньше указанного момента.
    PerPage:
      name: per_page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 25
    Page:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100000
        default: 1
  responses:
    Unauthenticated:
      description: Bearer token отсутствует или недействителен.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: Нет scope orders.view или права orders.view в текущем магазине.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFound:
      description: UUID не принадлежит текущему магазину либо заказ отсутствует.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ValidationFailed:
      description: Параметры фильтрации не прошли проверку.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  schemas:
    CreateOrderResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderSummary'
        request_id:
          type: string
          format: uuid
    UpdateOrderStatusResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderStatusTransitionResult'
        request_id:
          type: string
          format: uuid
    UpdateOrderResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          allOf:
            - $ref: '#/components/schemas/OrderDetail'
            - type: object
              required: [changed_fields, replayed]
              properties:
                changed_fields:
                  type: array
                  items:
                    type: string
                  description: Имена фактически изменённых server-side полей без значений PII.
                replayed:
                  type: boolean
        request_id:
          type: string
          format: uuid
    ReplaceOrderItemsResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          allOf:
            - $ref: '#/components/schemas/OrderDetail'
            - type: object
              required: [item_count, replayed]
              properties:
                item_count:
                  type: integer
                  minimum: 1
                  maximum: 100
                replayed:
                  type: boolean
        request_id:
          type: string
          format: uuid
    ReplaceOrderItemsRequest:
      type: object
      additionalProperties: false
      required: [expected_edit_version, items]
      properties:
        expected_edit_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Непрозрачная HMAC-версия из актуального OrderDetail или OrderStatusSnapshot.
        items:
          type: array
          description: Пустой массив очищает состав редактируемого неоплаченного заказа.
          maxItems: 100
          items:
            oneOf:
              - $ref: '#/components/schemas/ReplaceOrderProductItem'
              - $ref: '#/components/schemas/ReplaceOrderRecipeItem'
              - $ref: '#/components/schemas/ReplaceOrderReadyBouquetItem'
    OrderItemsCorrectionPreviewRequest:
      type: object
      additionalProperties: false
      required: [reason, items]
      properties:
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        items:
          $ref: '#/components/schemas/OrderCorrectionItems'
    ApplyOrderItemsCorrectionRequest:
      type: object
      additionalProperties: false
      required: [expected_version, reason, items]
      properties:
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Непрозрачная HMAC-версия из свежего preview с тем же payload.
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        items:
          $ref: '#/components/schemas/OrderCorrectionItems'
    OrderCorrectionItems:
      type: array
      description: Пустой массив очищает состав корректировкой, не изменяя ранее проведённые платежи.
      maxItems: 200
      items:
        oneOf:
          - $ref: '#/components/schemas/ExistingOrderCorrectionItem'
          - $ref: '#/components/schemas/NewOrderCorrectionItem'
    ExistingOrderCorrectionItem:
      type: object
      additionalProperties: false
      required: [item_uuid, qty, unit_price, discount_total]
      properties:
        source:
          type: string
          const: existing
        item_uuid:
          type: string
          format: uuid
        qty:
          type: number
          exclusiveMinimum: 0
          maximum: 999999.999
          multipleOf: 0.001
        unit_price:
          type: number
          minimum: 0
          maximum: 999999999.99
          multipleOf: 0.01
        discount_total:
          type: number
          minimum: 0
          maximum: 999999999.99
          multipleOf: 0.01
    NewOrderCorrectionItem:
      type: object
      additionalProperties: false
      required: [source, line_uuid, line_type, catalog_uuid, qty, expected_unit_price]
      properties:
        source:
          type: string
          const: new
        line_uuid:
          type: string
          format: uuid
          pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
        line_type:
          type: string
          enum: [product, recipe, ready_bouquet]
        catalog_uuid:
          type: string
          format: uuid
        qty:
          type: number
          exclusiveMinimum: 0
          maximum: 999999.999
          multipleOf: 0.001
        expected_unit_price:
          type: number
          minimum: 0
          maximum: 999999999.99
          multipleOf: 0.01
    OrderItemsCorrectionPreviewResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderItemsCorrectionPreview'
        request_id:
          type: string
          format: uuid
    OrderItemsCorrectionPreview:
      type: object
      additionalProperties: false
      required: [order_id, currency_code, expected_version, current, proposed, delta, stock]
      properties:
        order_id:
          type: string
          format: uuid
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        current:
          $ref: '#/components/schemas/OrderCorrectionCurrentTotals'
        proposed:
          $ref: '#/components/schemas/OrderCorrectionProposedTotals'
        delta:
          $ref: '#/components/schemas/OrderCorrectionFinancialDelta'
        stock:
          $ref: '#/components/schemas/OrderCorrectionStock'
    OrderCorrectionCurrentTotals:
      type: object
      additionalProperties: false
      required: [total, payment_due, line_count]
      properties:
        total:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        line_count:
          type: integer
          minimum: 0
    OrderCorrectionProposedTotals:
      type: object
      additionalProperties: false
      required: [subtotal, item_discount_total, total, payment_due, amount_to_collect, amount_available_to_refund, line_count]
      properties:
        subtotal:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        item_discount_total:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        total:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        amount_to_collect:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        amount_available_to_refund:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        line_count:
          type: integer
          minimum: 1
          maximum: 200
    OrderCorrectionFinancialDelta:
      type: object
      additionalProperties: false
      required: [total, payment_due]
      properties:
        total:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
    OrderCorrectionStock:
      type: object
      additionalProperties: false
      required: [schema_version, reservation_preview_available, changed_reservation_count, deltas]
      properties:
        schema_version:
          type: integer
          enum: [1, 2]
        reservation_preview_available:
          type: boolean
        changed_reservation_count:
          type: integer
          minimum: 0
        deltas:
          type: array
          items:
            $ref: '#/components/schemas/OrderCorrectionStockDelta'
    OrderCorrectionStockDelta:
      type: object
      additionalProperties: false
      required: [item_uuid, product_uuid, inventory_batch_uuid, before_qty, after_qty, delta_qty]
      properties:
        item_uuid:
          type: string
          format: uuid
        product_uuid:
          type: [string, 'null']
          format: uuid
        inventory_batch_uuid:
          type: [string, 'null']
          format: uuid
        before_qty:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{3}$'
        after_qty:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{3}$'
        delta_qty:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{3}$'
        may_use_alternative:
          type: boolean
    ApplyOrderItemsCorrectionResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/AppliedOrderItemsCorrection'
        request_id:
          type: string
          format: uuid
    AppliedOrderItemsCorrection:
      type: object
      additionalProperties: false
      required: [id, order_id, type, status, reason, currency_code, financial_delta, payment_due_delta, amount_to_collect, amount_available_to_refund, stock, before_revision, after_revision, next_expected_version, applied_at, replayed]
      properties:
        id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        type:
          type: string
          const: items
        status:
          type: string
          const: applied
        reason:
          type: string
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        financial_delta:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        payment_due_delta:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        amount_to_collect:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        amount_available_to_refund:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        stock:
          $ref: '#/components/schemas/OrderCorrectionStock'
        before_revision:
          $ref: '#/components/schemas/OrderCorrectionRevision'
        after_revision:
          $ref: '#/components/schemas/OrderCorrectionRevision'
        next_expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        applied_at:
          type: string
          format: date-time
        replayed:
          type: boolean
    OrderCorrectionRevision:
      type: object
      additionalProperties: false
      required: [id, number]
      properties:
        id:
          type: string
          format: uuid
        number:
          type: integer
          minimum: 1
    OrderDeliveryCorrectionPreviewRequest:
      type: object
      additionalProperties: false
      required: [reason, delivery_uuid, zone_uuid, city, address, price_mode]
      properties:
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        delivery_uuid:
          type: string
          format: uuid
        zone_uuid:
          type: string
          format: uuid
        interval_uuid:
          type: [string, 'null']
          format: uuid
        recipient_name:
          type: [string, 'null']
          maxLength: 255
        recipient_phone:
          type: [string, 'null']
          maxLength: 64
        city:
          type: string
          minLength: 1
          maxLength: 255
        address:
          type: string
          minLength: 1
          maxLength: 500
        entrance:
          type: [string, 'null']
          maxLength: 64
        floor:
          type: [string, 'null']
          maxLength: 64
        apartment:
          type: [string, 'null']
          maxLength: 64
        intercom:
          type: [string, 'null']
          maxLength: 64
        scheduled_from:
          type: [string, 'null']
          format: date-time
        scheduled_to:
          type: [string, 'null']
          format: date-time
        price_mode:
          type: string
          enum: [calculated, manual]
        delivery_price:
          type: [number, 'null']
          minimum: 0
          maximum: 999999999.99
          multipleOf: 0.01
          description: Обязательно только для manual; в calculated должно отсутствовать.
    ApplyOrderDeliveryCorrectionRequest:
      type: object
      additionalProperties: false
      required: [expected_version, reason, delivery_uuid, zone_uuid, city, address, price_mode]
      properties:
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        delivery_uuid:
          type: string
          format: uuid
        zone_uuid:
          type: string
          format: uuid
        interval_uuid:
          type: [string, 'null']
          format: uuid
        recipient_name:
          type: [string, 'null']
          maxLength: 255
        recipient_phone:
          type: [string, 'null']
          maxLength: 64
        city:
          type: string
          minLength: 1
          maxLength: 255
        address:
          type: string
          minLength: 1
          maxLength: 500
        entrance:
          type: [string, 'null']
          maxLength: 64
        floor:
          type: [string, 'null']
          maxLength: 64
        apartment:
          type: [string, 'null']
          maxLength: 64
        intercom:
          type: [string, 'null']
          maxLength: 64
        scheduled_from:
          type: [string, 'null']
          format: date-time
        scheduled_to:
          type: [string, 'null']
          format: date-time
        price_mode:
          type: string
          enum: [calculated, manual]
        delivery_price:
          type: [number, 'null']
          minimum: 0
          maximum: 999999999.99
          multipleOf: 0.01
          description: Обязательно только для manual; в calculated должно отсутствовать.
    OrderDeliveryLifecycleCreatePreviewRequest:
      type: object
      additionalProperties: false
      required: [reason, zone_uuid, city, address, price_mode]
      properties:
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        zone_uuid:
          type: string
          format: uuid
        interval_uuid:
          type: [string, 'null']
          format: uuid
        recipient_name:
          type: [string, 'null']
          maxLength: 255
        recipient_phone:
          type: [string, 'null']
          maxLength: 64
        city:
          type: string
          minLength: 1
          maxLength: 255
        address:
          type: string
          minLength: 1
          maxLength: 500
        entrance:
          type: [string, 'null']
          maxLength: 64
        floor:
          type: [string, 'null']
          maxLength: 64
        apartment:
          type: [string, 'null']
          maxLength: 64
        intercom:
          type: [string, 'null']
          maxLength: 64
        scheduled_from:
          type: [string, 'null']
          format: date-time
        scheduled_to:
          type: [string, 'null']
          format: date-time
        price_mode:
          type: string
          enum: [calculated, manual]
        delivery_price:
          type: [number, 'null']
          minimum: 0
          maximum: 999999999.99
          multipleOf: 0.01
          description: Обязательно только для manual; в calculated должно отсутствовать.
    ApplyOrderDeliveryLifecycleCreateRequest:
      type: object
      additionalProperties: false
      required: [expected_version, reason, zone_uuid, city, address, price_mode]
      properties:
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        zone_uuid:
          type: string
          format: uuid
        interval_uuid:
          type: [string, 'null']
          format: uuid
        recipient_name:
          type: [string, 'null']
          maxLength: 255
        recipient_phone:
          type: [string, 'null']
          maxLength: 64
        city:
          type: string
          minLength: 1
          maxLength: 255
        address:
          type: string
          minLength: 1
          maxLength: 500
        entrance:
          type: [string, 'null']
          maxLength: 64
        floor:
          type: [string, 'null']
          maxLength: 64
        apartment:
          type: [string, 'null']
          maxLength: 64
        intercom:
          type: [string, 'null']
          maxLength: 64
        scheduled_from:
          type: [string, 'null']
          format: date-time
        scheduled_to:
          type: [string, 'null']
          format: date-time
        price_mode:
          type: string
          enum: [calculated, manual]
        delivery_price:
          type: [number, 'null']
          minimum: 0
          maximum: 999999999.99
          multipleOf: 0.01
          description: Обязательно только для manual; в calculated должно отсутствовать.
    OrderDeliveryLifecycleCancelPreviewRequest:
      type: object
      additionalProperties: false
      required: [reason, delivery_uuid]
      properties:
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        delivery_uuid:
          type: string
          format: uuid
    ApplyOrderDeliveryLifecycleCancelRequest:
      type: object
      additionalProperties: false
      required: [expected_version, reason, delivery_uuid]
      properties:
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        delivery_uuid:
          type: string
          format: uuid
    OrderDeliveryLifecyclePreviewResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderDeliveryLifecyclePreview'
        request_id:
          type: string
          format: uuid
    OrderDeliveryLifecyclePreview:
      type: object
      additionalProperties: false
      required: [order_id, operation, currency_code, expected_version, current, proposed, delta]
      properties:
        order_id:
          type: string
          format: uuid
        operation:
          type: string
          enum: [create, cancel]
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        current:
          $ref: '#/components/schemas/OrderDeliveryLifecycleCurrent'
        proposed:
          $ref: '#/components/schemas/OrderDeliveryLifecycleProposed'
        delta:
          $ref: '#/components/schemas/OrderDeliveryCorrectionDelta'
    OrderDeliveryLifecycleCurrent:
      type: object
      additionalProperties: false
      required: [delivery_uuid, delivery_price, total, payment_due]
      properties:
        delivery_uuid:
          type: [string, 'null']
          format: uuid
        delivery_price:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        total:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
    OrderDeliveryLifecycleProposed:
      type: object
      additionalProperties: false
      required: [delivery_uuid, delivery_price, total, payment_due, amount_to_collect, amount_available_to_refund]
      properties:
        delivery_uuid:
          type: [string, 'null']
          format: uuid
        delivery_price:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        total:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        amount_to_collect:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        amount_available_to_refund:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
    OrderDeliveryCorrectionPreviewResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderDeliveryCorrectionPreview'
        request_id:
          type: string
          format: uuid
    OrderDeliveryCorrectionPreview:
      type: object
      additionalProperties: false
      required: [order_id, currency_code, expected_version, current, proposed, delta]
      properties:
        order_id:
          type: string
          format: uuid
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        current:
          $ref: '#/components/schemas/OrderDeliveryCorrectionCurrent'
        proposed:
          $ref: '#/components/schemas/OrderDeliveryCorrectionProposed'
        delta:
          $ref: '#/components/schemas/OrderDeliveryCorrectionDelta'
    OrderDeliveryCorrectionCurrent:
      type: object
      additionalProperties: false
      required: [delivery_uuid, zone_uuid, interval_uuid, delivery_price, total, payment_due]
      properties:
        delivery_uuid:
          type: string
          format: uuid
        zone_uuid:
          type: [string, 'null']
          format: uuid
        interval_uuid:
          type: [string, 'null']
          format: uuid
        delivery_price:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        total:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
    OrderDeliveryCorrectionProposed:
      type: object
      additionalProperties: false
      required: [delivery_uuid, zone_uuid, interval_uuid, delivery_price, total, payment_due, amount_to_collect, amount_available_to_refund]
      properties:
        delivery_uuid:
          type: string
          format: uuid
        zone_uuid:
          type: string
          format: uuid
        interval_uuid:
          type: [string, 'null']
          format: uuid
        delivery_price:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        total:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        amount_to_collect:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        amount_available_to_refund:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
    OrderDeliveryCorrectionDelta:
      type: object
      additionalProperties: false
      required: [delivery_price, total, payment_due]
      properties:
        delivery_price:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        total:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        payment_due:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
    ApplyOrderDeliveryCorrectionResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/AppliedOrderDeliveryCorrection'
        request_id:
          type: string
          format: uuid
    AppliedOrderDeliveryCorrection:
      type: object
      additionalProperties: false
      required: [id, order_id, delivery_id, type, status, reason, currency_code, financial_delta, payment_due_delta, amount_to_collect, amount_available_to_refund, stock, before_revision, after_revision, next_expected_version, applied_at, replayed]
      properties:
        id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        delivery_id:
          type: string
          format: uuid
        delivery_operation:
          type: string
          enum: [create, cancel]
          description: Присутствует только для lifecycle-команд создания и отмены.
        type:
          type: string
          const: delivery
        status:
          type: string
          const: applied
        reason:
          type: string
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        financial_delta:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        payment_due_delta:
          type: string
          pattern: '^-?[0-9]+\.[0-9]{2}$'
        amount_to_collect:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        amount_available_to_refund:
          type: string
          pattern: '^[0-9]+\.[0-9]{2}$'
        stock:
          $ref: '#/components/schemas/OrderCorrectionStock'
        before_revision:
          $ref: '#/components/schemas/OrderCorrectionRevision'
        after_revision:
          $ref: '#/components/schemas/OrderCorrectionRevision'
        next_expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        applied_at:
          type: string
          format: date-time
        replayed:
          type: boolean
    OrderDocumentCorrectionPreviewResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderDocumentCorrectionPreview'
        request_id:
          type: string
          format: uuid
    OrderDocumentCorrectionPreview:
      type: object
      additionalProperties: false
      required: [order_id, source_document_id, source_document_version, correction_id, correction_type, expected_version, next_document_version]
      properties:
        order_id:
          type: string
          format: uuid
        source_document_id:
          type: string
          format: uuid
        source_document_version:
          type: integer
          minimum: 1
        correction_id:
          type: string
          format: uuid
        correction_type:
          type: string
          enum: [items, delivery]
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        next_document_version:
          type: integer
          minimum: 2
    ApplyOrderDocumentCorrectionRequest:
      type: object
      additionalProperties: false
      required: [correction_id, reason, expected_version]
      properties:
        correction_id:
          type: string
          format: uuid
          description: UUIDv7 последней applied-корректировки из preview.
        reason:
          type: string
          minLength: 5
          maxLength: 1000
        expected_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
    ApplyOrderDocumentCorrectionResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/AppliedOrderDocumentCorrection'
        request_id:
          type: string
          format: uuid
    AppliedOrderDocumentCorrection:
      type: object
      additionalProperties: false
      required: [id, order_id, previous_document_id, correction_id, order_revision_id, version, number, type, status, pdf, issued_at, replayed]
      properties:
        id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        previous_document_id:
          type: string
          format: uuid
        correction_id:
          type: string
          format: uuid
        order_revision_id:
          type: string
          format: uuid
        version:
          type: integer
          minimum: 2
        number:
          type: string
        type:
          type: string
        status:
          type: string
          const: generated
        pdf:
          type: object
          additionalProperties: false
          required: [status, available]
          properties:
            status:
              type: string
              enum: [pending, processing, ready, failed]
            available:
              type: boolean
        issued_at:
          type: string
          format: date-time
        replayed:
          type: boolean
    UpsertOrderDeliveryResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          allOf:
            - $ref: '#/components/schemas/OrderDetail'
            - type: object
              required: [delivery_changed, replayed]
              properties:
                delivery_changed:
                  type: string
                  enum: [created, updated]
                replayed:
                  type: boolean
        request_id:
          type: string
          format: uuid
    UpsertOrderDeliveryRequest:
      type: object
      additionalProperties: false
      required: [expected_edit_version, delivery_zone_id, address]
      properties:
        expected_edit_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Непрозрачная HMAC-версия из актуального OrderDetail или OrderStatusSnapshot.
        delivery_zone_id:
          type: string
          format: uuid
          description: UUID активной зоны текущего магазина.
        delivery_interval_id:
          type: [string, 'null']
          format: uuid
          description: UUID активного общего интервала либо интервала выбранной зоны.
        city:
          type: [string, 'null']
          maxLength: 255
          description: Если не передан, CRM использует город магазина.
        address:
          type: string
          minLength: 1
          maxLength: 500
        entrance:
          type: [string, 'null']
          maxLength: 64
        floor:
          type: [string, 'null']
          maxLength: 64
        apartment:
          type: [string, 'null']
          maxLength: 64
        intercom:
          type: [string, 'null']
          maxLength: 64
        comment:
          type: [string, 'null']
          maxLength: 1000
    ReplaceOrderProductItem:
      type: object
      additionalProperties: false
      required: [type, product_id, quantity]
      properties:
        type:
          type: string
          const: product
        product_id:
          type: string
          format: uuid
        quantity:
          type: number
          minimum: 0.001
          maximum: 999
          multipleOf: 0.001
    ReplaceOrderRecipeItem:
      type: object
      additionalProperties: false
      required: [type, recipe_id, variant_id, quantity]
      properties:
        type:
          type: string
          const: recipe
        recipe_id:
          type: string
          format: uuid
        variant_id:
          type: string
          format: uuid
        quantity:
          type: number
          minimum: 0.001
          maximum: 999
          multipleOf: 0.001
    ReplaceOrderReadyBouquetItem:
      type: object
      additionalProperties: false
      required: [type, ready_bouquet_id, quantity]
      properties:
        type:
          type: string
          const: ready_bouquet
        ready_bouquet_id:
          type: string
          format: uuid
        quantity:
          type: number
          minimum: 0.001
          maximum: 999
          multipleOf: 0.001
    UpdateOrderRequest:
      type: object
      additionalProperties: false
      required: [expected_edit_version]
      properties:
        expected_edit_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Непрозрачная HMAC-версия из актуального OrderDetail или OrderStatusSnapshot.
        customer:
          $ref: '#/components/schemas/UpdateOrderCustomer'
        recipient:
          $ref: '#/components/schemas/UpdateOrderRecipient'
        desired_at:
          type: string
          format: date-time
        comment:
          type: [string, 'null']
          maxLength: 2000
        is_surprise:
          type: boolean
        do_not_call_recipient:
          type: boolean
        greeting_card:
          $ref: '#/components/schemas/UpdateOrderGreetingCard'
    UpdateOrderCustomer:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        name:
          type: [string, 'null']
          maxLength: 255
        phone:
          type: [string, 'null']
          maxLength: 64
        email:
          type: [string, 'null']
          format: email
          maxLength: 255
    UpdateOrderRecipient:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        same_as_customer:
          type: boolean
        name:
          type: [string, 'null']
          maxLength: 255
        phone:
          type: [string, 'null']
          maxLength: 64
    UpdateOrderGreetingCard:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        message:
          type: [string, 'null']
          maxLength: 500
        signature:
          type: [string, 'null']
          maxLength: 120
    UpdateOrderStatusRequest:
      type: object
      additionalProperties: false
      required: [target_status_id, expected_status_id]
      properties:
        target_status_id:
          type: string
          format: uuid
          description: UUID активного целевого статуса текущего магазина.
        expected_status_id:
          type: string
          format: uuid
          description: UUID статуса, который интеграция получила до mutation.
        reason:
          type: [string, 'null']
          maxLength: 255
          description: Обязателен для отмены и переходов, настроенных с требованием причины.
    CreateOrderRequest:
      type: object
      additionalProperties: false
      required: [customer, recipient, fulfillment, desired_at, payment_method]
      properties:
        external_order_id:
          type: [string, 'null']
          maxLength: 128
          pattern: '^[A-Za-z0-9._:-]+$'
          description: Внешний идентификатор интеграции для долговременной дедупликации. Не является CRM UUID.
        customer:
          $ref: '#/components/schemas/CreateOrderCustomer'
        recipient:
          $ref: '#/components/schemas/CreateOrderRecipient'
        items:
          type: array
          description: Можно опустить или передать пустой массив для создания заказа без состава.
          maxItems: 100
          items:
            $ref: '#/components/schemas/CreateOrderItem'
        fulfillment:
          $ref: '#/components/schemas/CreateOrderFulfillment'
        desired_at:
          type: string
          format: date-time
        payment_method:
          type: string
          enum: [pay_on_delivery, card_on_delivery, online]
        comment:
          type: [string, 'null']
          maxLength: 2000
        promo_code:
          type: [string, 'null']
          maxLength: 64
        bonus_amount:
          type: [number, 'null']
          minimum: 0
        is_surprise:
          type: boolean
          default: false
        do_not_call_recipient:
          type: boolean
          default: false
        greeting_card:
          $ref: '#/components/schemas/CreateOrderGreetingCard'
    CreateOrderCustomer:
      type: object
      additionalProperties: false
      required: [name, phone]
      properties:
        id:
          type: [string, 'null']
          format: uuid
          description: UUID существующего активного клиента; если не передан, CRM сопоставляет или создаёт профиль по контактам.
        name:
          type: string
          maxLength: 255
        phone:
          type: string
          maxLength: 64
        email:
          type: [string, 'null']
          format: email
          maxLength: 255
    CreateOrderRecipient:
      type: object
      additionalProperties: false
      required: [same_as_customer]
      properties:
        same_as_customer:
          type: boolean
        id:
          type: [string, 'null']
          format: uuid
        name:
          type: [string, 'null']
          maxLength: 255
        phone:
          type: [string, 'null']
          maxLength: 64
    CreateOrderItem:
      type: object
      additionalProperties: false
      required: [type, quantity]
      properties:
        type:
          type: string
          enum: [product, recipe, ready_bouquet]
        product_id:
          type: [string, 'null']
          format: uuid
          description: Обязателен для type=product.
        recipe_id:
          type: [string, 'null']
          format: uuid
          description: Обязателен для type=recipe.
        variant_id:
          type: [string, 'null']
          format: uuid
          description: Обязателен для type=recipe; состав и цена берутся из варианта.
        ready_bouquet_id:
          type: [string, 'null']
          format: uuid
          description: Обязателен для type=ready_bouquet.
        quantity:
          type: number
          minimum: 0.001
          maximum: 999
          multipleOf: 0.001
    CreateOrderFulfillment:
      type: object
      additionalProperties: false
      required: [type]
      properties:
        type:
          type: string
          enum: [delivery, pickup]
        delivery_zone_id:
          type: [string, 'null']
          format: uuid
          description: Обязателен для delivery и должен принадлежать текущему магазину.
        delivery_interval_id:
          type: [string, 'null']
          format: uuid
        city:
          type: [string, 'null']
          maxLength: 255
        address:
          type: [string, 'null']
          maxLength: 500
        entrance:
          type: [string, 'null']
          maxLength: 64
        floor:
          type: [string, 'null']
          maxLength: 64
        apartment:
          type: [string, 'null']
          maxLength: 64
        intercom:
          type: [string, 'null']
          maxLength: 64
        comment:
          type: [string, 'null']
          maxLength: 1000
    CreateOrderGreetingCard:
      type: [object, 'null']
      additionalProperties: false
      properties:
        message:
          type: [string, 'null']
          maxLength: 500
        signature:
          type: [string, 'null']
          maxLength: 120
    OrderListResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [items, meta]
          properties:
            items:
              type: array
              items:
                $ref: '#/components/schemas/OrderSummary'
            meta:
              $ref: '#/components/schemas/PaginationMeta'
        request_id:
          type: string
          format: uuid
    OrderDetailResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderDetail'
        request_id:
          type: string
          format: uuid
    OrderPaymentLedgerResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderPaymentLedger'
        request_id:
          type: string
          format: uuid
    ConfirmedExternalPaymentResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/ConfirmedExternalPaymentResult'
        request_id:
          type: string
          format: uuid
    ConfirmedExternalRefundResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/ConfirmedExternalRefundResult'
        request_id:
          type: string
          format: uuid
    CreateConfirmedExternalPaymentRequest:
      type: object
      additionalProperties: false
      required:
        - external_payment_id
        - payment_method_id
        - amount
        - expected_order_revision
        - expected_payment_method_revision
        - confirmed_external
      properties:
        external_payment_id:
          type: string
          minLength: 8
          maxLength: 128
          pattern: '^[A-Za-z0-9._:-]+$'
          description: |
            Неизменяемый идентификатор подтверждённой операции во внешней системе.
            Не является CRM UUID и не возвращается в публичном ответе.
        payment_method_id:
          type: string
          format: uuid
          description: UUID активного card или bank_transfer способа из GET /payment-methods.
        amount:
          type: string
          pattern: '^(?:0|[1-9][0-9]{0,7})(?:\.[0-9]{1,2})?$'
          description: Положительная сумма не больше актуального payment_due.
          example: '2500.00'
        expected_order_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Актуальный edit_version заказа до регистрации оплаты.
        expected_payment_method_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Актуальная revision из GET /payment-methods.
        confirmed_external:
          type: boolean
          const: true
          description: Явное подтверждение, что внешняя система уже безусловно приняла деньги.
    ConfirmedExternalPaymentResult:
      type: object
      additionalProperties: false
      required: [payment, order, replayed]
      properties:
        payment:
          $ref: '#/components/schemas/ConfirmedExternalPayment'
        order:
          $ref: '#/components/schemas/ConfirmedExternalPaymentOrder'
        replayed:
          type: boolean
    ConfirmedExternalPayment:
      type: object
      additionalProperties: false
      required:
        - id
        - order_id
        - payment_method_id
        - amount
        - currency_code
        - status
        - fiscal_status
        - paid_at
      properties:
        id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        payment_method_id:
          type: string
          format: uuid
        amount:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        status:
          type: string
          const: succeeded
        fiscal_status:
          type: string
          enum: [not_required, pending]
        paid_at:
          type: [string, 'null']
          format: date-time
    ConfirmedExternalPaymentOrder:
      type: object
      additionalProperties: false
      required:
        - id
        - payment_status
        - total
        - paid_total
        - refunded_total
        - payment_due
        - currency_code
        - edit_version
      properties:
        id:
          type: string
          format: uuid
        payment_status:
          type: string
          enum: [unpaid, partial, paid, refunded]
        total:
          $ref: '#/components/schemas/Money'
        paid_total:
          $ref: '#/components/schemas/Money'
        refunded_total:
          $ref: '#/components/schemas/Money'
        payment_due:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        edit_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
    CreateConfirmedExternalRefundRequest:
      type: object
      additionalProperties: false
      required:
        - external_refund_id
        - amount
        - expected_order_revision
        - expected_payment_revision
        - confirmed_external
      properties:
        external_refund_id:
          type: string
          minLength: 8
          maxLength: 128
          pattern: '^[A-Za-z0-9._:-]+$'
          description: |
            Неизменяемый идентификатор подтверждённого возврата во внешней системе.
            Не является CRM UUID и не возвращается в публичном ответе.
        amount:
          type: string
          pattern: '^(?:0|[1-9][0-9]{0,7})(?:\.[0-9]{1,2})?$'
          description: Положительная сумма не больше refundable_amount исходной оплаты.
          example: '500.00'
        expected_order_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Актуальный edit_version из GET /orders/{orderId}/payments.
        expected_payment_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Актуальная revision конкретной исходной оплаты.
        confirmed_external:
          type: boolean
          const: true
          description: Явное подтверждение, что внешняя система уже безусловно вернула деньги.
    ConfirmedExternalRefundResult:
      type: object
      additionalProperties: false
      required: [refund, original_payment, order, replayed]
      properties:
        refund:
          $ref: '#/components/schemas/ConfirmedExternalRefund'
        original_payment:
          $ref: '#/components/schemas/ConfirmedExternalRefundSource'
        order:
          $ref: '#/components/schemas/ConfirmedExternalPaymentOrder'
        replayed:
          type: boolean
    ConfirmedExternalRefund:
      type: object
      additionalProperties: false
      required:
        - id
        - order_id
        - original_payment_id
        - payment_method_id
        - amount
        - currency_code
        - status
        - fiscal_status
        - refunded_at
      properties:
        id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        original_payment_id:
          type: string
          format: uuid
        payment_method_id:
          type: string
          format: uuid
        amount:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        status:
          type: string
          const: succeeded
        fiscal_status:
          type: string
          enum: [not_required, pending]
        refunded_at:
          type: [string, 'null']
          format: date-time
    ConfirmedExternalRefundSource:
      type: object
      additionalProperties: false
      required: [id, refundable_amount, external_refund_available, revision]
      properties:
        id:
          type: string
          format: uuid
        refundable_amount:
          $ref: '#/components/schemas/Money'
        external_refund_available:
          type: boolean
        revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
    OrderStatusResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/OrderStatusSnapshot'
        request_id:
          type: string
          format: uuid
    OrderSummary:
      type: object
      required:
        - id
        - number
        - store_id
        - source
        - status
        - payment_status
        - delivery_status
        - subtotal
        - discount_total
        - delivery_price
        - total
        - paid_total
        - refunded_total
        - payment_due
        - currency_code
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
        number:
          type: string
        store_id:
          type: string
          format: uuid
        source:
          $ref: '#/components/schemas/OrderSource'
        type:
          type: [string, 'null']
        status:
          $ref: '#/components/schemas/OrderStatus'
        payment_status:
          type: string
        delivery_status:
          type: string
        desired_at:
          type: [string, 'null']
          format: date-time
        subtotal:
          $ref: '#/components/schemas/Money'
        discount_total:
          $ref: '#/components/schemas/Money'
        delivery_price:
          $ref: '#/components/schemas/Money'
        total:
          $ref: '#/components/schemas/Money'
        paid_total:
          $ref: '#/components/schemas/Money'
        refunded_total:
          $ref: '#/components/schemas/Money'
        payment_due:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    OrderPaymentLedger:
      type: object
      additionalProperties: false
      required:
        - order_id
        - order_number
        - payment_status
        - total
        - paid_total
        - refunded_total
        - payment_due
        - currency_code
        - edit_version
        - payments
      properties:
        order_id:
          type: string
          format: uuid
        order_number:
          type: string
        payment_status:
          type: string
        total:
          $ref: '#/components/schemas/Money'
        paid_total:
          $ref: '#/components/schemas/Money'
        refunded_total:
          $ref: '#/components/schemas/Money'
        payment_due:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        edit_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Актуальная optimistic revision заказа для финансовой mutation.
        payments:
          type: array
          items:
            $ref: '#/components/schemas/PublicOrderPayment'
    PublicOrderPayment:
      type: object
      additionalProperties: false
      required:
        - id
        - type
        - status
        - amount
        - currency_code
        - payment_method
        - fiscal_status
        - paid_at
        - refunded_at
        - created_at
        - revision
        - refundable_amount
        - external_refund_available
        - refunds
      properties:
        id:
          type: string
          format: uuid
        type:
          type: string
          enum: [payment, refund]
        status:
          type: string
          enum: [pending, succeeded, failed, cancelled]
        amount:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        payment_method:
          oneOf:
            - $ref: '#/components/schemas/PublicPaymentMethod'
            - type: 'null'
        fiscal_status:
          type: string
          enum: [not_required, pending, sent, succeeded, failed]
        paid_at:
          type: [string, 'null']
          format: date-time
        refunded_at:
          type: [string, 'null']
          format: date-time
        created_at:
          type: [string, 'null']
          format: date-time
        revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: Непрозрачная revision source-bound состояния конкретной ledger-записи.
        refundable_amount:
          $ref: '#/components/schemas/Money'
        external_refund_available:
          type: boolean
          description: true только для доступной подтверждённой внешней оплаты Public API.
        refunds:
          type: array
          description: Provider-refund операции, инициированные для этой исходной оплаты.
          items:
            $ref: '#/components/schemas/PublicOnlineRefund'
    PublicPaymentMethod:
      type: object
      additionalProperties: false
      required: [id, code, name, type]
      properties:
        id:
          type: string
          format: uuid
        code:
          type: string
        name:
          type: string
        type:
          type: string
    PublicOnlineRefund:
      type: object
      additionalProperties: false
      required:
        - id
        - ledger_payment_id
        - status
        - amount
        - currency_code
        - reason_code
        - requested_at
        - completed_at
      properties:
        id:
          type: string
          format: uuid
        ledger_payment_id:
          type: [string, 'null']
          format: uuid
          description: UUID созданной строки возврата после успешного завершения; null до проведения.
        status:
          type: string
          enum: [draft, pending, succeeded, failed, cancelled, requires_manual_review]
        amount:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        reason_code:
          type: string
        requested_at:
          type: [string, 'null']
          format: date-time
        completed_at:
          type: [string, 'null']
          format: date-time
    OrderDetail:
      allOf:
        - $ref: '#/components/schemas/OrderSummary'
        - type: object
          required: [edit_version]
          properties:
            edit_version:
              type: string
              pattern: '^[a-f0-9]{64}$'
              description: Непрозрачная HMAC-версия для optimistic update.
            customer_id:
              type: [string, 'null']
              format: uuid
            recipient_customer_id:
              type: [string, 'null']
              format: uuid
            customer:
              $ref: '#/components/schemas/OrderCustomer'
            recipient:
              $ref: '#/components/schemas/OrderRecipient'
            greeting_card:
              $ref: '#/components/schemas/GreetingCard'
            reserve_stock:
              type: boolean
            reserved_at:
              type: [string, 'null']
              format: date-time
            completed_at:
              type: [string, 'null']
              format: date-time
            cancelled_at:
              type: [string, 'null']
              format: date-time
            comment:
              type: [string, 'null']
            items:
              type: array
              items:
                $ref: '#/components/schemas/OrderItem'
            delivery:
              oneOf:
                - $ref: '#/components/schemas/OrderDelivery'
                - type: 'null'
    OrderStatusSnapshot:
      type: object
      required: [id, number, status, payment_status, delivery_status, edit_version, updated_at]
      properties:
        id:
          type: string
          format: uuid
        number:
          type: string
        status:
          $ref: '#/components/schemas/OrderStatus'
        payment_status:
          type: string
        delivery_status:
          type: string
        desired_at:
          type: [string, 'null']
          format: date-time
        edit_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        updated_at:
          type: string
          format: date-time
    OrderStatusTransitionResult:
      type: object
      required: [transition_id, order_id, previous_status, status, edit_version, changed_at, replayed]
      properties:
        transition_id:
          type: string
          format: uuid
          description: UUIDv7 неизменяемой записи истории перехода.
        order_id:
          type: string
          format: uuid
        previous_status:
          $ref: '#/components/schemas/OrderStatus'
        status:
          $ref: '#/components/schemas/OrderStatus'
        edit_version:
          type: string
          pattern: '^[a-f0-9]{64}$'
        changed_at:
          type: string
          format: date-time
        replayed:
          type: boolean
          description: false у первого выполнения, true у ответа из idempotency cache.
    OrderSource:
      type: object
      required: [id, code, name]
      properties:
        id:
          type: [string, 'null']
          format: uuid
        code:
          type: string
        name:
          type: string
    OrderStatus:
      type: object
      required: [id, code, name, color]
      properties:
        id:
          type: [string, 'null']
          format: uuid
        code:
          type: [string, 'null']
        name:
          type: string
        color:
          type: [string, 'null']
    OrderCustomer:
      type: object
      properties:
        name:
          type: [string, 'null']
        phone:
          type: [string, 'null']
        email:
          type: [string, 'null']
    OrderRecipient:
      type: object
      properties:
        same_as_customer:
          type: boolean
        name:
          type: [string, 'null']
        phone:
          type: [string, 'null']
        is_surprise:
          type: boolean
        do_not_call:
          type: boolean
    GreetingCard:
      type: object
      properties:
        message:
          type: [string, 'null']
        signature:
          type: [string, 'null']
    OrderItem:
      type: object
      required: [id, type, name, quantity, unit_price, discount_total, total, is_stock_tracked]
      properties:
        id:
          type: string
          format: uuid
        type:
          type: string
        name:
          type: string
        product_id:
          type: [string, 'null']
          format: uuid
        ready_bouquet_id:
          type: [string, 'null']
          format: uuid
        bouquet_recipe_id:
          type: [string, 'null']
          format: uuid
        bouquet_recipe_variant_id:
          type: [string, 'null']
          format: uuid
        quantity:
          type: string
          pattern: '^-?[0-9]+(\.[0-9]{1,3})?$'
        unit_price:
          $ref: '#/components/schemas/Money'
        discount_total:
          $ref: '#/components/schemas/Money'
        total:
          $ref: '#/components/schemas/Money'
        is_stock_tracked:
          type: boolean
    OrderDelivery:
      type: object
      additionalProperties: false
      required:
        - id
        - delivery_zone_id
        - delivery_interval_id
        - status
        - delivery_price
        - currency_code
        - zone_check_status
      properties:
        id:
          type: string
          format: uuid
        delivery_zone_id:
          type: [string, 'null']
          format: uuid
        delivery_interval_id:
          type: [string, 'null']
          format: uuid
        status:
          type: string
          enum: [planned, assigned, in_delivery, delivered, failed, cancelled]
        recipient_name:
          type: [string, 'null']
        recipient_phone:
          type: [string, 'null']
        city:
          type: [string, 'null']
        address:
          type: [string, 'null']
        entrance:
          type: [string, 'null']
        floor:
          type: [string, 'null']
        apartment:
          type: [string, 'null']
        intercom:
          type: [string, 'null']
        scheduled_from:
          type: [string, 'null']
          format: date-time
        scheduled_to:
          type: [string, 'null']
          format: date-time
        delivery_price:
          $ref: '#/components/schemas/Money'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        zone_check_status:
          type: string
        delivered_at:
          type: [string, 'null']
          format: date-time
        comment:
          type: [string, 'null']
    PaginationMeta:
      type: object
      required: [total, per_page, current_page, last_page]
      properties:
        total:
          type: integer
        per_page:
          type: integer
        current_page:
          type: integer
        last_page:
          type: integer
    Money:
      type: string
      pattern: '^-?[0-9]+\.[0-9]{2}$'
      example: '3500.00'
    ErrorResponse:
      type: object
      required: [success, error, request_id]
      properties:
        success:
          type: boolean
          const: false
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
            message:
              type: string
            details:
              type: object
              additionalProperties: true
        request_id:
          type: string
          format: uuid
