openapi: 3.1.0
info:
  title: BloomCore POS Client API
  version: 1.22.0
  description: |
    Служебный API v1 для официального POS-приложения BloomCore на Windows и macOS.
    Это не интеграционный API владельца: устройство активируется одноразовым кодом,
    получает отдельный device token, а сотрудник открывает ограниченную смену шестизначным PIN.
    Токены являются секретами, показываются клиенту один раз и не должны попадать в логи,
    резервные копии интерфейса, аналитику или сообщения об ошибках. Все CRM-идентификаторы
    в URL, запросах и ответах являются UUID; внутренние bigint ID БД не поддерживаются.
    POS обязан хранить токены в защищенном системном хранилище операционной системы.
    Offline-операции разрешаются только при наличии короткоживущего Ed25519-подписанного
    offline lease; приватный ключ подписи никогда не передается POS-клиенту. После каждого
    PIN-входа POS запускает bootstrap либо продолжает инкрементальную синхронизацию по durable
    UUID checkpoint, атомарно сохраняет полученные коллекции в локальную БД и только после
    успешного завершения разрешает рабочие операции.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1/pos
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина, к которому привязано POS-устройство.
tags:
  - name: DeviceActivation
    description: Одноразовая привязка установленного POS к зарегистрированному устройству.
  - name: DeviceUpdates
    description: Серверная политика совместимости версии и безопасного обновления POS.
  - name: EmployeeSession
    description: Вход сотрудника по PIN и управление ограниченной POS-сессией.
  - name: OfflineLease
    description: Подписанный сервером допуск и непересекающийся диапазон счетчиков offline-операций.
  - name: BootstrapSync
    description: Начальная UUID-only копия настроек, каталога, клиентов, касс, способов оплаты и воронки заказов без секретов провайдеров.
  - name: DeltaSync
    description: Инкрементальный UUID-only поток upsert/remove после подтвержденного bootstrap или предыдущей delta.
  - name: Assignments
    description: Получение и подтверждение назначений заказов текущего сотрудника.
  - name: TaskNotifications
    description: UUID-only лента уведомлений о задачах текущего сотрудника в магазине активного устройства.
  - name: POSSubscriptionNotifications
    description: Уведомления exact POS-устройства об окончании его SaaS-подписки без финансовых и управляющих данных.
  - name: Receipts
    description: UUID-only проекция заказа для просмотра и печати квитанции в POS.
  - name: OrderWorkflow
    description: Server-authoritative команды рабочего жизненного цикла заказа.
paths:
  /devices/activate:
    post:
      tags: [DeviceActivation]
      summary: Активировать зарегистрированное POS-устройство
      description: |
        UUID устройства и одноразовый код создаются владельцем или администратором в CRM.
        Код действует 30 минут и блокируется после пяти неверных попыток. Для активации
        требуются действующая базовая CRM-подписка магазина и POS-подписка этого UUID устройства.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ActivateDeviceRequest'
      responses:
        '201':
          description: Устройство активировано; device token возвращен только в этом ответе.
          headers:
            Cache-Control:
              description: Ответ запрещено кэшировать.
              schema:
                type: string
                example: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActivateDeviceResponse'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /orders/{orderId}/receipt/email:
    post:
      tags: [Receipts]
      summary: Поставить актуальную квитанцию в очередь email
      description: |
        Online-only команда официального POS. Получатель не принимается из запроса:
        сервер использует только проверенный `customer_email` текущего заказа и возвращает
        его в маскированном виде. Требуются `orders.view`, `payments.view` и
        `payments.create`, активное устройство, employee session и подписка POS.
        Для неизменившейся проекции квитанции повторный запрос возвращает ту же UUIDv7
        delivery; после изменения оплаты или возврата создается новый content-bound event.
        Терминально неуспешную delivery явный повтор переводит обратно в `pending` с новым
        зашифрованным payload, а уже отправленное неизменившееся письмо повторно не создается.
      security:
        - employeeBearer: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Квитанция идемпотентно поставлена в durable email outbox.
          headers:
            Cache-Control:
              description: Статус доставки и адрес запрещено кэшировать.
              schema:
                type: string
                example: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PosReceiptDeliveryResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '422':
          $ref: '#/components/responses/ValidationError'
        '426':
          $ref: '#/components/responses/UpgradeRequired'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /updates/check:
    post:
      tags: [DeviceUpdates]
      summary: Проверить совместимость установленной версии POS
      description: |
        Требуется действующий device token. Endpoint намеренно не блокируется минимальной
        версией, чтобы устаревшее приложение всегда могло получить безопасный URL, SHA-256,
        подпись и причину блокировки. Канал выпуска определяется сервером для устройства;
        POS не может самостоятельно перейти на beta или staging. Результат имеет статус
        ok, recommended_update, required_update либо blocked. Все остальные защищенные
        POS-endpoint возвращают HTTP 426 при required_update/blocked.
      security:
        - deviceBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PosUpdateCheckRequest'
      responses:
        '200':
          description: Актуальная серверная политика совместимости для устройства.
          headers:
            Cache-Control:
              description: Политику нельзя сохранять в общем HTTP-кэше.
              schema:
                type: string
                example: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PosUpdateCheckResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '503':
          $ref: '#/components/responses/Unavailable'
  /auth/pin:
    post:
      tags: [EmployeeSession]
      summary: Войти в POS по PIN сотрудника
      description: |
        Требуется device token. После пяти неверных PIN устройство блокирует новые попытки
        на 15 минут. Успешный ответ содержит employee session token на 12 часов.
      security:
        - deviceBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PinLoginRequest'
      responses:
        '200':
          description: Ограниченная сессия сотрудника создана.
          headers:
            Cache-Control:
              description: Ответ запрещено кэшировать.
              schema:
                type: string
                example: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PinLoginResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /profile:
    get:
      tags: [EmployeeSession]
      summary: Получить профиль активной POS-сессии
      security:
        - employeeBearer: []
      responses:
        '200':
          description: Сотрудник, устройство, магазин, timezone, валюта и разрешенные POS capabilities.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProfileResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
  /auth/logout:
    post:
      tags: [EmployeeSession]
      summary: Завершить текущую POS-сессию сотрудника
      security:
        - employeeBearer: []
      responses:
        '200':
          description: Session token отозван и больше не принимается.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LogoutResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
  /offline-leases:
    post:
      tags: [OfflineLease]
      summary: Получить новый подписанный offline-допуск
      description: |
        Требуется employee session с правом pos.offline_sync и обязательный UUID Idempotency-Key.
        Новый lease отзывает предыдущий активный lease устройства и резервирует непересекающийся
        диапазон monotonic counter. valid_until не превышает POS-сессию, базовую CRM/POS-подписку
        с grace period и серверный максимум offline-доступа.
      security:
        - employeeBearer: []
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '201':
          description: Новый offline lease создан и подписан Ed25519.
          headers:
            Cache-Control:
              description: Ответ запрещено кэшировать промежуточными узлами.
              schema:
                type: string
                example: no-store
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OfflineLeaseResponse'
        '200':
          description: Повтор безопасно возвращает ранее созданный lease без новой выдачи диапазона.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OfflineLeaseResponse'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '503':
          $ref: '#/components/responses/Unavailable'
  /offline-leases/current:
    get:
      tags: [OfflineLease]
      summary: Восстановить текущий lease активной employee session
      description: Возвращает тот же проверяемый пакет только для текущих device, store, employee и session UUID.
      security:
        - employeeBearer: []
      responses:
        '200':
          description: Действующий offline lease найден.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OfflineLeaseResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '503':
          $ref: '#/components/responses/Unavailable'
  /orders/{orderId}/receipt:
    get:
      tags: [Receipts]
      summary: Получить актуальную квитанцию заказа
      description: |
        Возвращает только заказ текущего магазина POS-устройства. Требуются права
        `orders.view` и `payments.view`. В ответ входят публичные UUID, строки заказа,
        успешные оплаты и возвраты, итоговые суммы и агрегированный статус фискализации.
        Внутренние bigint ID, metadata и секреты провайдеров не выдаются. До статуса
        `fiscal_receipt` POS обязан обозначать документ как предварительную или
        нефискальную квитанцию, а не как фискальный чек.
      security:
        - employeeBearer: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Актуальная проекция квитанции сформирована.
          headers:
            Cache-Control:
              description: Финансовый документ запрещено кэшировать промежуточным узлам.
              schema:
                type: string
                example: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PosReceiptResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /orders/{orderId}/status:
    post:
      tags: [OrderWorkflow]
      summary: Изменить статус активного заказа
      description: |
        Online-only команда официального POS. Сервер повторно проверяет `orders.update`,
        tenant/store устройства, актуальную SHA-256 revision UUID-only проекции, активный
        целевой статус, source-specific переход и обязательную причину. Изменение выполняет
        общий OrderWorkflowService со складскими, бонусными, payroll, почтовыми и webhook
        последствиями. POS не должен оптимистично менять локальную запись и не ставит эту
        команду в offline-журнал. Terminal-статус возвращает `removed_from_active_orders=true`
        и удаляет заказ из локальной active-проекции.
      security:
        - employeeBearer: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
            format: uuid
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PosOrderStatusCommandRequest'
      responses:
        '200':
          description: Переход подтвержден сервером либо возвращен сохраненный idempotent result.
          headers:
            Cache-Control:
              schema: { type: string, example: no-store, private }
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PosOrderStatusCommandResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
  /orders/{orderId}/payments:
    get:
      tags: [OrderWorkflow]
      summary: Получить source-bound историю оплат активного заказа
      description: |
        Возвращает успешные оплаты и возвраты exact активного заказа, остаток возврата по каждой
        исходной оплате и безопасную причину недоступности. Требуются `orders.view` и `payments.view`.
        Подписочная оплата показывается, но возвращается только отдельным серверным сценарием.
        PII, bigint ID, provider credential и metadata не передаются.
      security:
        - employeeBearer: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Актуальная UUID-only история оплат и возвратов.
          headers:
            Cache-Control:
              schema:
                type: string
                example: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PosActiveOrderPaymentLedgerResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
    post:
      tags: [OrderWorkflow]
      summary: Принять оплату активного заказа
      description: |
        Online-only команда официального POS для заказа, уже существующего в CRM. Сервер под
        блокировкой повторно проверяет `orders.view`, `payments.view`, `payments.create`, tenant/store
        устройства, SHA-256 revision заказа и способа оплаты, остаток к оплате и UUIDv7 платежа.
        Для наличных дополнительно требуются `cash_shifts.view`, выбранная касса и открытая смена;
        для карты или банковского перевода требуется явное подтверждение внешней операции.
        Поддерживаются только cash, card и bank_transfer. Команда не помещается в offline-журнал,
        POS не меняет локальные суммы оптимистично и применяет только подтвержденную сервером
        UUID-only проекцию. Повтор того же запроса безопасно возвращает сохраненный результат.
      security:
        - employeeBearer: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
            format: uuid
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PosActiveOrderPaymentRequest'
      responses:
        '200':
          description: Платеж проведен либо возвращен сохраненный idempotent result.
          headers:
            Cache-Control:
              schema:
                type: string
                example: no-store, private
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PosActiveOrderPaymentResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
  /orders/{orderId}/payments/{paymentId}/refunds:
    post:
      tags: [OrderWorkflow]
      summary: Вернуть сумму exact исходной оплаты активного заказа
      description: |
        Online-only source-bound возврат. Сервер блокирует заказ, исходную успешную оплату и уже
        проведенные возвраты, повторно проверяет revisions, remaining amount и способ возврата.
        Cash требует открытую смену, card/bank_transfer — внешнее подтверждение, bonus возвращается
        в тот же бонусный ledger. Subscription source этим endpoint не поддерживается.
      security:
        - employeeBearer: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: paymentId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PosActiveOrderRefundRequest'
      responses:
        '200':
          description: Возврат проведен либо возвращен сохраненный idempotent result.
          headers:
            Cache-Control:
              schema:
                type: string
                example: no-store, private
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PosActiveOrderRefundResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
  /sync/bootstrap:
    post:
      tags: [BootstrapSync]
      summary: Начать согласованную bootstrap-синхронизацию POS
      description: |
        Требуются employee session, действующий offline lease этой же сессии и обязательный
        UUID Idempotency-Key. Сервер фиксирует snapshot и manifest выбранных коллекций на 30 минут.
        Повтор с тем же ключом и теми же параметрами возвращает ту же sync session. Новая сессия
        помечает предыдущую активную bootstrap-сессию этого устройства и сотрудника abandoned.
        Внешний ответ не содержит внутренних bigint ID или внутренних позиций manifest.
      security:
        - employeeBearer: []
      parameters:
        - $ref: '#/components/parameters/syncIdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BootstrapSyncRequest'
      responses:
        '201':
          description: Новая bootstrap-сессия создана.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BootstrapSyncStartResponse'
        '200':
          description: Возвращена ранее созданная сессия для того же Idempotency-Key.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BootstrapSyncStartResponse'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
  /sync/sessions/{sessionId}/collections/{collection}:
    get:
      tags: [BootstrapSync]
      summary: Получить страницу коллекции bootstrap-сессии
      description: |
        Страницы читаются keyset-способом. next_cursor является зашифрованным и аутентифицированным
        opaque token, привязанным к session UUID, коллекции и сроку сессии. POS не должен разбирать,
        изменять или формировать cursor самостоятельно. Скрытые/неактивные категории, их потомки и
        товары таких категорий не возвращаются. Рецепты включают только активные для точки варианты
        с доступным составом и аналогами. Готовые букеты включаются только для текущего магазина,
        когда статус available и остаток больше нуля. Клиенты доступны по всему tenant-у только при
        `customers.view`; архивные/удаленные записи и лишние PII-поля не возвращаются. Кассы,
        способы оплаты и статусы требуют соответственно `cash_shifts.view`, `payments.view` и
        `orders.view`. Их `settings`, `metadata`, фискальные ключи и платежные секреты не выдаются.
        Ответ нужно записать в локальную staging-транзакцию.
      security:
        - employeeBearer: []
      parameters:
        - $ref: '#/components/parameters/sessionId'
        - $ref: '#/components/parameters/syncCollection'
        - name: cursor
          in: query
          schema:
            type: string
            maxLength: 2048
          description: Непрозрачный next_cursor из предыдущего ответа этой же коллекции.
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 200
      responses:
        '200':
          description: Страница UUID-only записей и следующий opaque cursor.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BootstrapSyncCollectionResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
  /sync/sessions/{sessionId}/complete:
    post:
      tags: [BootstrapSync]
      summary: Завершить bootstrap и получить sync cursor с новым lease
      description: |
        Команда принимается только после полной загрузки всех заявленных коллекций. POS сначала
        фиксирует staging-данные локально, затем вызывает complete и атомарно переключает активный
        локальный snapshot на выданный sync_cursor. Сервер отзывает исходный offline lease и выдает
        новый подписанный lease с непересекающимся диапазоном счетчиков. UUID Idempotency-Key обязателен.
      security:
        - employeeBearer: []
      parameters:
        - $ref: '#/components/parameters/sessionId'
        - $ref: '#/components/parameters/syncIdempotencyKey'
      responses:
        '200':
          description: Bootstrap завершен; возвращены UUID cursor и обновленный подписанный lease.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BootstrapSyncCompleteResponse'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '503':
          $ref: '#/components/responses/Unavailable'
  /sync/changes:
    get:
      tags: [DeltaSync]
      summary: Получить страницу изменений после подтвержденного sync cursor
      description: |
        sync_cursor является UUID checkpoint, выданным успешным bootstrap complete либо последней
        завершенной delta. Сервер фиксирует верхнюю границу журнала при первой странице; next_cursor
        зашифрован и привязан к устройству, сотруднику, исходному checkpoint и набору коллекций.
        Каждая запись содержит UUID события и сущности. operation=upsert возвращает полную актуальную
        POS-проекцию агрегата, operation=remove требует удалить сущность из активной локальной проекции.
        Архивирование, скрытие, потеря store-visibility, reserved/sold/written_off готового букета и
        soft delete возвращаются как remove. Внутренние bigint позиции журнала не раскрываются.
        next_sync_cursor появляется только на последней странице; клиент сохраняет его после атомарного
        применения всех страниц и использует в следующем цикле.
      security:
        - employeeBearer: []
      parameters:
        - name: sync_cursor
          in: query
          required: true
          schema:
            type: string
            format: uuid
          description: Последний durable UUID checkpoint текущих устройства, магазина и сотрудника.
        - name: cursor
          in: query
          schema:
            type: string
            maxLength: 4096
          description: Непрозрачный next_cursor предыдущей страницы этого delta-цикла.
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 200
      responses:
        '200':
          description: Страница изменений и новый sync checkpoint на последней странице.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeltaSyncResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
  /sync/entities:
    post:
      tags: [DeltaSync]
      summary: Проверить актуальные версии конкретных POS-сущностей
      description: |
        Read-only preflight перед продажей, оплатой, резервом, возвратом или другой mutation.
        За один запрос принимается до 50 уникальных пар collection+UUID. expected_revision берется
        из последнего bootstrap/delta/preflight item и является SHA-256 разрешенной POS-проекции,
        а не DB row version. Поэтому revision меняется при цене, остатке, штрихкоде, составе, media,
        effective store configuration или видимости. Неизвестная, чужая, архивная или недоступная
        запись возвращается как remove без подтверждения ее существования в другой области.
      security:
        - employeeBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/EntityPreflightRequest'
      responses:
        '200':
          description: Актуальные UUID-only проекции и результат сравнения revision.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EntityPreflightResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /sync/push:
    post:
      tags: [DeltaSync]
      summary: Передать пакет offline-операций в серверный inbox
      description: |
        Принимает до 100 операций, созданных внутри срока выданного lease и его counter range.
        UUID, idempotency key и counter уникальны для устройства. Точный повтор воспроизводит queued
        result без дубля; конфликт идентичности отклоняется. queued означает только надежный прием,
        а не применение продажи/оплаты. Payload и expected revisions хранятся зашифрованно.
      security:
        - employeeBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OfflinePushRequest'
      responses:
        '200':
          description: Результат приема каждой операции.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OfflinePushResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationError'
  /sync/operations/status:
    post:
      tags: [DeltaSync]
      summary: Получить статусы offline-операций
      description: |
        Возвращает состояние до 100 UUID в исходном порядке. Чужая и неизвестная операция
        одинаково возвращается как not_found. Для terminal operation сервер выдает result_revision
        и только безопасный result с allowlisted code и UUID references.
      security:
        - employeeBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OfflineStatusRequest'
      responses:
        '200':
          description: Текущие UUID-only состояния операций.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OfflineStatusResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /sync/operations/ack:
    post:
      tags: [DeltaSync]
      summary: Подтвердить полученные terminal результаты
      description: |
        Идемпотентно подтверждает до 100 applied/conflict/rejected результатов. Клиент обязан
        передать точную result_revision из status response. queued, unknown и изменившийся result
        не подтверждаются; acknowledgement не удаляет серверную историю операции.
      security:
        - employeeBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OfflineAckRequest'
      responses:
        '200':
          description: Результат подтверждения каждого UUID.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OfflineAckResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /assignments:
    get:
      tags: [Assignments]
      summary: Получить назначения текущего сотрудника
      description: Возвращаются только назначения сотрудника в магазине активного устройства.
      security:
        - employeeBearer: []
      parameters:
        - name: status
          in: query
          schema:
            type: string
            enum: [pending_acceptance, active]
            default: pending_acceptance
        - name: updated_after
          in: query
          schema:
            type: string
            format: date-time
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
      responses:
        '200':
          description: Назначения текущего сотрудника.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AssignmentListResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
  /notifications:
    get:
      tags: [TaskNotifications]
      summary: Получить новые уведомления о задачах текущего сотрудника
      description: |
        Возвращает только уведомления с контрактом task-notification.v1, адресованные POS,
        текущему сотруднику и магазину активного устройства. В ответе используются только UUID;
        внутренние bigint идентификаторы, URL CRM и лишние данные исходного database notification
        не возвращаются. При первом запросе сервер отдает ограниченное окно последних событий в
        хронологическом порядке. Следующие запросы используют пару cursor_created_at + cursor_id.
        Чтение этой ленты не изменяет состояние уведомления в CRM.
      security:
        - employeeBearer: []
      parameters:
        - name: cursor_created_at
          in: query
          description: UTC-время последнего сохраненного события; передается только вместе с cursor_id.
          schema:
            type: string
            format: date-time
        - name: cursor_id
          in: query
          description: UUID последнего сохраненного события; передается только вместе с cursor_created_at.
          schema:
            type: string
            format: uuid
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
      responses:
        '200':
          description: Новые уведомления о задачах и следующий durable cursor.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TaskNotificationFeedResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /notifications/acknowledge:
    post:
      tags: [TaskNotifications]
      summary: Подтвердить прочтение уведомлений на текущем POS-устройстве
      description: |
        Создает неизменяемые подтверждения только для событий задач текущего сотрудника,
        магазина и активного POS-устройства. Exact replay идемпотентен. Подтверждение одного
        POS не изменяет Laravel read_at в CRM и не отмечает событие прочитанным на другом
        POS-устройстве или в будущем мобильном клиенте. Неизвестные и недоступные UUID
        отсутствуют в результате без раскрытия чужого scope.
      security:
        - employeeBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TaskNotificationAcknowledgementRequest'
      responses:
        '200':
          description: Подтверждения, принадлежащие exact POS-устройству и сотруднику.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TaskNotificationAcknowledgementResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /notifications/subscriptions:
    get:
      tags: [POSSubscriptionNotifications]
      summary: Получить уведомления об окончании подписки текущего POS-устройства
      description: |
        Возвращает только события subscription_ending, выпущенные для exact активного
        POS-устройства и его магазина. Сервер повторно проверяет актуальную подписку,
        scope устройства и точную дату окончания; после продления старое предупреждение
        перестает попадать в ленту. Ответ не содержит цены, валюты, внутренних bigint ID,
        URL SaaS-панели или команд управления подпиской. Первичный запрос возвращает
        ограниченное окно последних событий в хронологическом порядке, последующие
        используют durable cursor_created_at + cursor_id.
      security:
        - employeeBearer: []
      parameters:
        - name: cursor_created_at
          in: query
          description: UTC-время последнего сохраненного события; передается только вместе с cursor_id.
          schema:
            type: string
            format: date-time
        - name: cursor_id
          in: query
          description: UUID последнего сохраненного события; передается только вместе с cursor_created_at.
          schema:
            type: string
            format: uuid
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
      responses:
        '200':
          description: Актуальные предупреждения exact POS-устройства и следующий durable cursor.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/POSSubscriptionNotificationFeedResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /notifications/subscriptions/acknowledge:
    post:
      tags: [POSSubscriptionNotifications]
      summary: Подтвердить прочтение предупреждений о подписке текущим POS-устройством
      description: |
        Создает идемпотентные подтверждения только для доступных событий exact
        POS-устройства, магазина и сотрудника активной POS-сессии. Неизвестные,
        продленные и чужие события отсутствуют в результате без раскрытия их существования.
        Подтверждение не меняет состояние уведомлений сотрудников SaaS-панели.
      security:
        - employeeBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/POSSubscriptionNotificationAcknowledgementRequest'
      responses:
        '200':
          description: Подтверждения, принадлежащие exact POS-устройству и сотруднику.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/POSSubscriptionNotificationAcknowledgementResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /assignments/{assignmentId}/accept:
    post:
      tags: [Assignments]
      summary: Принять назначение заказа
      security:
        - employeeBearer: []
      parameters:
        - $ref: '#/components/parameters/assignmentId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AssignmentCommandRequest'
      responses:
        '200':
          description: Назначение принято или воспроизведен результат той же команды.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AssignmentResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
  /assignments/{assignmentId}/decline:
    post:
      tags: [Assignments]
      summary: Отклонить назначение заказа
      security:
        - employeeBearer: []
      parameters:
        - $ref: '#/components/parameters/assignmentId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeclineAssignmentRequest'
      responses:
        '200':
          description: Назначение отклонено с обязательной причиной.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AssignmentResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
components:
  securitySchemes:
    deviceBearer:
      type: http
      scheme: bearer
      bearerFormat: opaque-pos-device-token
      description: Device token, полученный один раз при активации устройства.
    employeeBearer:
      type: http
      scheme: bearer
      bearerFormat: opaque-pos-employee-session
      description: Employee session token, полученный после успешного PIN-входа.
  parameters:
    sessionId:
      name: sessionId
      in: path
      required: true
      schema:
        type: string
        format: uuid
    syncCollection:
      name: collection
      in: path
      required: true
      schema:
        type: string
        enum: [settings, categories, units, products, promo_codes, recipes, ready_bouquets, customers, cash_registers, payment_methods, order_statuses, orders]
    syncIdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Новый UUIDv7 для логической bootstrap-команды; повтор команды обязан использовать тот же UUID.
      schema:
        type: string
        format: uuid
    assignmentId:
      name: assignmentId
      in: path
      required: true
      schema:
        type: string
        format: uuid
    idempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: UUID, совпадающий с idempotency_key в JSON. Рекомендуется передавать всегда.
      schema:
        type: string
        format: uuid
  headers:
    IdempotencyReplayed:
      description: true, если возвращен ранее сохраненный успешный результат той же команды.
      schema:
        type: string
  responses:
    Unauthenticated:
      description: Токен отсутствует, истек, отозван либо имеет другой тип.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: Нарушена область tenant/store, подписка или права сотрудника.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFound:
      description: Ресурс не найден в области текущего устройства и сотрудника.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Conflict:
      description: Конфликт версии или повторное использование idempotency key с другим запросом.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ValidationError:
      description: Ошибка проверки параметров или состояния операции.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    TooManyRequests:
      description: Превышен rate limit или временно заблокирован перебор кода/PIN.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    UpgradeRequired:
      description: Версия POS ниже обязательного минимума либо выпуск заблокирован SaaS.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unavailable:
      description: Ed25519 signing key или обязательный криптографический модуль недоступен.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  schemas:
    PosOrderStatusCommandRequest:
      type: object
      additionalProperties: false
      required: [target_status_id, expected_revision, idempotency_key]
      properties:
        target_status_id:
          type: string
          format: uuid
        expected_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
        idempotency_key:
          type: string
          format: uuid
          description: UUIDv7, совпадающий с заголовком Idempotency-Key.
        reason:
          type: [string, 'null']
          maxLength: 512
    PosOrderStatusCommandResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          additionalProperties: false
          required: [result]
          properties:
            result:
              $ref: '#/components/schemas/PosOrderStatusResult'
        request_id: { type: string, format: uuid }
    PosOrderStatusResult:
      type: object
      additionalProperties: false
      required: [order_id, store_id, previous_revision, removed_from_active_orders, removed_revision, order]
      properties:
        order_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        previous_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
        removed_from_active_orders: { type: boolean }
        removed_revision:
          type: [string, 'null']
          pattern: '^[a-f0-9]{64}$'
        order:
          oneOf:
            - $ref: '#/components/schemas/PosActiveOrderProjection'
            - type: 'null'
    PosActiveOrderPaymentRequest:
      type: object
      additionalProperties: false
      required: [payment_id, payment_method_id, amount, expected_order_revision, expected_payment_method_revision, idempotency_key, confirmed_external]
      properties:
        payment_id:
          type: string
          format: uuid
          description: Новый UUIDv7 платежа, созданный POS для этой команды.
        payment_method_id:
          type: string
          format: uuid
        cash_register_id:
          type: [string, 'null']
          format: uuid
          description: Обязателен только для наличной оплаты.
        amount:
          type: string
          pattern: '^(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,2})?$'
        expected_order_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
        expected_payment_method_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
        idempotency_key:
          type: string
          format: uuid
          description: UUIDv7, совпадающий с заголовком Idempotency-Key.
        reference:
          type: [string, 'null']
          maxLength: 255
        comment:
          type: [string, 'null']
          maxLength: 1000
        confirmed_external:
          type: boolean
    PosActiveOrderPaymentResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          additionalProperties: false
          required: [result]
          properties:
            result:
              $ref: '#/components/schemas/PosActiveOrderPaymentResult'
        request_id:
          type: string
          format: uuid
    PosActiveOrderPaymentResult:
      type: object
      additionalProperties: false
      required: [payment, previous_order_revision, order]
      properties:
        payment:
          $ref: '#/components/schemas/PosActiveOrderPayment'
        previous_order_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
        order:
          $ref: '#/components/schemas/PosActiveOrderProjection'
    PosActiveOrderPayment:
      type: object
      additionalProperties: false
      required: [id, order_id, payment_method_id, cash_register_id, cash_shift_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
        cash_register_id:
          type: [string, 'null']
          format: uuid
        cash_shift_id:
          type: [string, 'null']
          format: uuid
        amount:
          type: string
        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
          format: date-time
    PosActiveOrderPaymentLedgerResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          additionalProperties: false
          required: [result]
          properties:
            result:
              $ref: '#/components/schemas/PosActiveOrderPaymentLedger'
        request_id: { type: string, format: uuid }
    PosActiveOrderPaymentLedger:
      type: object
      additionalProperties: false
      required: [contract, order_id, order_revision, currency_code, paid_total, refunded_total, payment_due, sources, operations, server_time]
      properties:
        contract: { type: string, const: pos-order-payment-ledger.v1 }
        order_id:
          type: string
          format: uuid
        order_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
        currency_code: { type: string, pattern: '^[A-Z]{3}$' }
        paid_total: { type: string }
        refunded_total: { type: string }
        payment_due: { type: string }
        sources:
          type: array
          maxItems: 500
          items:
            $ref: '#/components/schemas/PosActiveOrderPaymentSource'
        operations:
          type: array
          maxItems: 500
          items:
            $ref: '#/components/schemas/PosActiveOrderPaymentOperation'
        server_time: { type: string, format: date-time }
    PosActiveOrderPaymentSource:
      type: object
      additionalProperties: false
      required: [id, payment_method_id, payment_method_revision, payment_method_name, method_type, is_cash, requires_external_confirmation, amount, refunded_amount, remaining_amount, currency_code, fiscal_status, paid_at, refundable, unavailable_code, unavailable_reason]
      properties:
        id:
          type: string
          format: uuid
        payment_method_id:
          type: [string, 'null']
          format: uuid
        payment_method_revision: { type: [string, 'null'], pattern: '^[a-f0-9]{64}$' }
        payment_method_name: { type: string, maxLength: 160 }
        method_type: { type: [string, 'null'], enum: [cash, card, bank_transfer, bonus, null] }
        is_cash: { type: boolean }
        requires_external_confirmation: { type: boolean }
        amount: { type: string }
        refunded_amount: { type: string }
        remaining_amount: { type: string }
        currency_code: { type: string, pattern: '^[A-Z]{3}$' }
        fiscal_status: { type: string, enum: [not_required, pending, sent, succeeded, failed] }
        paid_at: { type: string, format: date-time }
        refundable: { type: boolean }
        unavailable_code: { type: [string, 'null'], maxLength: 80 }
        unavailable_reason: { type: [string, 'null'], maxLength: 255 }
    PosActiveOrderPaymentOperation:
      type: object
      additionalProperties: false
      required: [id, type, original_payment_id, payment_method_id, payment_method_name, method_type, amount, currency_code, fiscal_status, occurred_at]
      properties:
        id:
          type: string
          format: uuid
        type: { type: string, enum: [payment, refund] }
        original_payment_id:
          type: [string, 'null']
          format: uuid
        payment_method_id:
          type: [string, 'null']
          format: uuid
        payment_method_name: { type: string, maxLength: 160 }
        method_type: { type: [string, 'null'], enum: [cash, card, bank_transfer, bonus, null] }
        amount: { type: string }
        currency_code: { type: string, pattern: '^[A-Z]{3}$' }
        fiscal_status: { type: string, enum: [not_required, pending, sent, succeeded, failed] }
        occurred_at: { type: string, format: date-time }
    PosActiveOrderRefundRequest:
      type: object
      additionalProperties: false
      required: [refund_id, amount, expected_order_revision, expected_payment_method_revision, idempotency_key, confirmed_external]
      properties:
        refund_id:
          type: string
          format: uuid
          description: Новый UUIDv7 возврата.
        cash_register_id:
          type: [string, 'null']
          format: uuid
        amount: { type: string, pattern: '^(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,2})?$' }
        expected_order_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
        expected_payment_method_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
        idempotency_key: { type: string, format: uuid }
        reference: { type: [string, 'null'], maxLength: 255 }
        comment: { type: [string, 'null'], maxLength: 1000 }
        confirmed_external: { type: boolean }
    PosActiveOrderRefundResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          additionalProperties: false
          required: [result]
          properties:
            result:
              $ref: '#/components/schemas/PosActiveOrderRefundResult'
        request_id: { type: string, format: uuid }
    PosActiveOrderRefundResult:
      type: object
      additionalProperties: false
      required: [refund, previous_order_revision, order]
      properties:
        refund:
          $ref: '#/components/schemas/PosActiveOrderRefund'
        previous_order_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
        order:
          $ref: '#/components/schemas/PosActiveOrderProjection'
    PosActiveOrderRefund:
      type: object
      additionalProperties: false
      required: [id, order_id, original_payment_id, payment_method_id, cash_register_id, cash_shift_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
        cash_register_id:
          type: [string, 'null']
          format: uuid
        cash_shift_id:
          type: [string, 'null']
          format: uuid
        amount: { type: string }
        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, format: date-time }
    PosActiveOrderProjection:
      type: object
      additionalProperties: false
      required: [id, store_id, number, source, type, status_id, status_code, status_name, status_color, payment_status, delivery_status, reserve_stock, desired_at, subtotal, discount_total, delivery_price, total, paid_total, refunded_total, payment_due, items_count, items_truncated, items, created_at, updated_at, revision]
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        number: { type: [string, 'null'] }
        source: { type: string, maxLength: 64 }
        type: { type: [string, 'null'], maxLength: 64 }
        status_id:
          type: [string, 'null']
          format: uuid
        status_code: { type: string, maxLength: 64 }
        status_name: { type: string, maxLength: 160 }
        status_color: { type: string, maxLength: 32 }
        payment_status: { type: string, maxLength: 64 }
        delivery_status: { type: string, maxLength: 64 }
        reserve_stock: { type: boolean }
        desired_at: { type: [string, 'null'], format: date-time }
        subtotal: { type: string }
        discount_total: { type: string }
        delivery_price: { type: string }
        total: { type: string }
        paid_total: { type: string }
        refunded_total: { type: string }
        payment_due: { type: string }
        items_count: { type: integer, minimum: 0 }
        items_truncated: { type: boolean }
        items:
          type: array
          maxItems: 200
          items:
            type: object
            additionalProperties: false
            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 }
              quantity: { type: string }
              unit_price: { type: string }
              discount_total: { type: string }
              total: { type: string }
              is_stock_tracked: { type: boolean }
        created_at: { type: [string, 'null'], format: date-time }
        updated_at: { type: [string, 'null'], format: date-time }
        revision: { type: string, pattern: '^[a-f0-9]{64}$' }
    PosReceiptResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/PosReceipt'
        request_id:
          type: string
          format: uuid
    PosReceipt:
      type: object
      additionalProperties: false
      required: [contract, order_id, order_number, document_kind, document_label, created_at, store, items, totals, payments, fiscal_status, delivery, server_time]
      properties:
        contract:
          type: string
          const: pos-receipt.v1
        order_id:
          type: string
          format: uuid
        order_number:
          type: string
        document_kind:
          type: string
          enum: [provisional, non_fiscal_receipt, fiscal_pending, fiscal_failed, fiscal_receipt]
        document_label:
          type: string
        created_at:
          type: string
          format: date-time
        store:
          type: object
          additionalProperties: false
          required: [id, name, timezone, currency_code]
          properties:
            id:
              type: string
              format: uuid
            name:
              type: string
            timezone:
              type: string
            currency_code:
              type: string
              pattern: '^[A-Z]{3}$'
        items:
          type: array
          maxItems: 100
          items:
            type: object
            additionalProperties: false
            required: [id, type, name, quantity, unit_price, discount_total, total]
            properties:
              id:
                type: string
                format: uuid
              type:
                type: string
              name:
                type: string
              quantity:
                type: string
              unit_price:
                type: string
              discount_total:
                type: string
              total:
                type: string
        totals:
          type: object
          additionalProperties: false
          required: [subtotal, discount_total, delivery_price, total, paid_total, refunded_total, payment_due, currency_code]
          properties:
            subtotal: { type: string }
            discount_total: { type: string }
            delivery_price: { type: string }
            total: { type: string }
            paid_total: { type: string }
            refunded_total: { type: string }
            payment_due: { type: string }
            currency_code: { type: string, pattern: '^[A-Z]{3}$' }
        payments:
          type: array
          maxItems: 100
          items:
            type: object
            additionalProperties: false
            required: [id, type, amount, currency_code, method, reference, fiscal_status, occurred_at]
            properties:
              id:
                type: string
                format: uuid
              type: { type: string, enum: [payment, refund] }
              amount: { type: string }
              currency_code: { type: string, pattern: '^[A-Z]{3}$' }
              method:
                type: object
                nullable: true
                additionalProperties: false
                required: [id, name, type]
                properties:
                  id:
                    type: string
                    format: uuid
                  name: { type: string }
                  type: { type: string }
              reference: { type: string, nullable: true }
              fiscal_status:
                type: string
                enum: [not_required, pending, sent, succeeded, failed]
              occurred_at: { type: string, format: date-time, nullable: true }
        fiscal_status:
          type: string
          enum: [not_required, pending, succeeded, failed]
        delivery:
          type: object
          additionalProperties: false
          required: [email_available, email_masked, delivery_id, status]
          properties:
            email_available:
              type: boolean
            email_masked:
              type: [string, 'null']
              description: Маскированный адрес; полный email POS API не возвращает.
            delivery_id:
              type: [string, 'null']
              format: uuid
            status:
              type: [string, 'null']
              enum: [pending, sending, retry, sent, failed, cancelled, null]
        server_time:
          type: string
          format: date-time
    PosReceiptDeliveryResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          additionalProperties: false
          required: [contract, delivery_id, channel, recipient_masked, status, queued_at]
          properties:
            contract:
              type: string
              const: pos-receipt-delivery.v1
            delivery_id:
              type: string
              format: uuid
            channel:
              type: string
              const: email
            recipient_masked:
              type: string
            status:
              type: string
              enum: [pending, sending, retry, sent, failed, cancelled]
            queued_at:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    ActivateDeviceRequest:
      type: object
      additionalProperties: false
      required: [device_id, activation_code, device_identifier, platform, app_version, build_number]
      properties:
        device_id:
          type: string
          format: uuid
        activation_code:
          type: string
          minLength: 8
          maxLength: 32
        device_identifier:
          type: string
          minLength: 16
          maxLength: 255
          description: Стабильный непубличный идентификатор установки, сформированный POS-клиентом.
        platform:
          type: string
          enum: [windows, macos]
        app_version:
          type: string
          pattern: '^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$'
          maxLength: 32
        build_number:
          type: integer
          minimum: 1
        os_version:
          type: string
          maxLength: 128
      example:
        device_id: 123e4567-e89b-42d3-a456-426614174010
        activation_code: F6R8K2M4Q9
        device_identifier: install-6d7dd0e2-28dc-4ee8-a0d8-c63d41d6d33f
        platform: windows
        app_version: 1.0.0
        build_number: 100
        os_version: Windows 11
    PosUpdateCheckRequest:
      type: object
      additionalProperties: false
      required: [platform, app_version, build_number]
      properties:
        platform:
          type: string
          enum: [windows, macos]
        app_version:
          type: string
          pattern: '^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$'
          maxLength: 32
        build_number:
          type: integer
          minimum: 1
        os_version:
          type: string
          maxLength: 128
      example:
        platform: macos
        app_version: 0.1.0
        build_number: 1
        os_version: macOS 15.5
    PosVersionTarget:
      type: object
      additionalProperties: false
      required: [version, build_number]
      properties:
        version: { type: string }
        build_number: { type: integer, minimum: 1 }
    PosUpdatePolicy:
      type: object
      required: [contract, status, platform, channel, current, minimum, recommended, latest, checked_at, valid_until]
      properties:
        contract: { type: string, const: pos-update-policy.v1 }
        status:
          type: string
          enum: [ok, recommended_update, required_update, blocked]
        platform: { type: string, enum: [windows, macos] }
        channel: { type: string, enum: [stable, staging, beta] }
        current: { $ref: '#/components/schemas/PosVersionTarget' }
        minimum: { $ref: '#/components/schemas/PosVersionTarget' }
        recommended: { $ref: '#/components/schemas/PosVersionTarget' }
        latest: { $ref: '#/components/schemas/PosVersionTarget' }
        download_url: { type: [string, 'null'], format: uri }
        checksum_sha256: { type: [string, 'null'], pattern: '^[a-f0-9]{64}$' }
        signature_url: { type: [string, 'null'], format: uri }
        release_notes: { type: [string, 'null'] }
        blocked_reason: { type: [string, 'null'] }
        published_at: { type: [string, 'null'], format: date-time }
        checked_at: { type: string, format: date-time }
        valid_until: { type: string, format: date-time }
    PinLoginRequest:
      type: object
      required: [pin]
      properties:
        pin:
          type: string
          pattern: '^\d{6}$'
          writeOnly: true
    BootstrapSyncRequest:
      type: object
      required: [offline_lease_id]
      properties:
        offline_lease_id:
          type: string
          format: uuid
          description: UUID действующего lease текущих employee session и POS-устройства.
        collections:
          type: array
          minItems: 1
          maxItems: 11
          uniqueItems: true
          items:
            type: string
            enum: [settings, categories, units, products, promo_codes, recipes, ready_bouquets, customers, cash_registers, payment_methods, order_statuses, orders]
          default: [settings, categories, units, products, promo_codes, recipes, ready_bouquets, customers, cash_registers, payment_methods, order_statuses, orders]
        client_schema_version:
          type: string
          maxLength: 32
    BootstrapSyncSession:
      type: object
      required: [id, mode, status, snapshot_at, expires_at]
      properties:
        id:
          type: string
          format: uuid
        mode:
          type: string
          const: bootstrap
        status:
          type: string
          enum: [active, completed]
        snapshot_at:
          type: string
          format: date-time
        expires_at:
          type: string
          format: date-time
    BootstrapSyncCollectionSummary:
      type: object
      required: [key, estimated_items, etag]
      properties:
        key:
          type: string
          enum: [settings, categories, units, products, promo_codes, recipes, ready_bouquets, customers, cash_registers, payment_methods, order_statuses, orders]
        estimated_items:
          type: integer
          minimum: 0
        etag:
          type: string
          pattern: '^[a-f0-9]{64}$'
    BootstrapSyncSettings:
      type: object
      required: [id, tenant_id, store_id, device_id, employee_id, name, currency_code, locale, timezone, uses_inventory_batches, loyalty, server_time]
      properties:
        id:
          type: string
          format: uuid
          description: Совпадает с UUID магазина и является ID записи settings snapshot.
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        device_id:
          type: string
          format: uuid
        employee_id:
          type: string
          format: uuid
        name:
          type: string
        public_name:
          type: string
          nullable: true
        country_code:
          type: string
          nullable: true
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        locale:
          type: string
        timezone:
          type: string
        uses_inventory_batches:
          type: boolean
        loyalty:
          type: object
          additionalProperties: false
          required: [redemption_enabled, max_redeem_percent]
          properties:
            redemption_enabled:
              type: boolean
            max_redeem_percent:
              type: string
              pattern: '^(0|[1-9][0-9]?|100)(\.[0-9]{1,2})?$'
              description: Базовый лимит магазина; индивидуальная группа клиента повторно учитывается сервером при проведении.
        server_time:
          type: string
          format: date-time
    BootstrapSyncCategory:
      type: object
      required: [id, name, is_required, sort_order]
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
          nullable: true
        parent_id:
          type: string
          format: uuid
          nullable: true
        name:
          type: string
        color:
          type: string
          nullable: true
        icon:
          type: string
          nullable: true
        system_key:
          type: string
          nullable: true
        is_required:
          type: boolean
        sort_order:
          type: integer
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncUnit:
      type: object
      required: [id, code, name, short_name, precision, is_system]
      properties:
        id:
          type: string
          format: uuid
        code:
          type: string
        name:
          type: string
        short_name:
          type: string
        precision:
          type: integer
          minimum: 0
          maximum: 3
        is_system:
          type: boolean
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncProductPrice:
      type: object
      required: [regular, effective, currency_code]
      properties:
        regular:
          type: string
          pattern: '^\d+(?:\.\d{2})$'
        discount:
          type: string
          pattern: '^\d+(?:\.\d{2})$'
          nullable: true
        effective:
          type: string
          pattern: '^\d+(?:\.\d{2})$'
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
    BootstrapSyncProductStock:
      type: object
      required: [available, reserved, total, version]
      properties:
        id:
          type: string
          format: uuid
          nullable: true
        available:
          type: string
        reserved:
          type: string
        total:
          type: string
        version:
          type: integer
          minimum: 0
    BootstrapSyncBarcode:
      type: object
      required: [id, value, type, is_primary]
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
          nullable: true
        value:
          type: string
        type:
          type: string
        is_primary:
          type: boolean
    BootstrapSyncMedia:
      type: object
      required: [url, type, is_primary]
      properties:
        url:
          type: string
          format: uri
        type:
          type: string
          enum: [image, video]
        is_primary:
          type: boolean
        alt:
          type: string
          nullable: true
    BootstrapSyncProduct:
      type: object
      required: [id, type, name, is_stock_tracked, is_popular, allow_negative_stock, allow_fractional_quantity, min_stock_qty, price, stock, barcodes, media, version]
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
          nullable: true
        category_id:
          type: string
          format: uuid
          nullable: true
        unit_id:
          type: string
          format: uuid
          nullable: true
        type:
          type: string
        name:
          type: string
        description:
          type: string
          nullable: true
        sku:
          type: string
          nullable: true
        is_stock_tracked:
          type: boolean
        is_popular:
          type: boolean
        allow_negative_stock:
          type: boolean
        allow_fractional_quantity:
          type: boolean
        min_stock_qty:
          type: string
        freshness_days:
          type: integer
          nullable: true
        price:
          $ref: '#/components/schemas/BootstrapSyncProductPrice'
        stock:
          $ref: '#/components/schemas/BootstrapSyncProductStock'
        barcodes:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncBarcode'
        media:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncMedia'
        version:
          type: integer
          minimum: 1
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncRecipeAlternative:
      type: object
      required: [id, product_id, priority]
      properties:
        id:
          type: string
          format: uuid
        product_id:
          type: string
          format: uuid
        quantity:
          type: string
          nullable: true
        priority:
          type: integer
          minimum: 0
        comment:
          type: string
          nullable: true
    BootstrapSyncRecipeItem:
      type: object
      required: [id, product_id, quantity, role, is_required, sort_order, alternatives]
      properties:
        id:
          type: string
          format: uuid
        product_id:
          type: string
          format: uuid
        unit_id:
          type: string
          format: uuid
          nullable: true
        quantity:
          type: string
        role:
          type: string
          enum: [component, flower, greenery, packaging, service]
        is_required:
          type: boolean
        sort_order:
          type: integer
          minimum: 0
        comment:
          type: string
          nullable: true
        alternatives:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncRecipeAlternative'
    BootstrapSyncRecipeVariant:
      type: object
      required: [id, name, is_default, sort_order, price, media, composition]
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        sku:
          type: string
          nullable: true
        size_label:
          type: string
          nullable: true
        width_cm:
          type: string
          nullable: true
        height_cm:
          type: string
          nullable: true
        is_default:
          type: boolean
        sort_order:
          type: integer
          minimum: 0
        price:
          $ref: '#/components/schemas/BootstrapSyncProductPrice'
        media:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncMedia'
        composition:
          type: array
          minItems: 1
          items:
            $ref: '#/components/schemas/BootstrapSyncRecipeItem'
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncRecipe:
      type: object
      required: [id, category_ids, name, show_composition, sort_order, media, variants, version]
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
          nullable: true
        category_id:
          type: string
          format: uuid
          nullable: true
        category_ids:
          type: array
          uniqueItems: true
          items:
            type: string
            format: uuid
        name:
          type: string
        description:
          type: string
          nullable: true
        sku:
          type: string
          nullable: true
        show_composition:
          type: boolean
          description: Управляет показом состава покупателю; POS всегда получает состав для сборки.
        sort_order:
          type: integer
          minimum: 0
        media:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncMedia'
        variants:
          type: array
          minItems: 1
          items:
            $ref: '#/components/schemas/BootstrapSyncRecipeVariant'
        version:
          type: integer
          minimum: 1
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncReadyBouquetPrice:
      type: object
      required: [composition, markup_percent, markup_amount, discount_percent, discount_amount, effective, currency_code]
      properties:
        composition:
          type: string
        markup_percent:
          type: string
        markup_amount:
          type: string
        discount_percent:
          type: string
        discount_amount:
          type: string
        effective:
          type: string
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
    BootstrapSyncReadyBouquetItem:
      type: object
      required: [id, product_id, quantity, is_substitution, sort_order]
      properties:
        id:
          type: string
          format: uuid
        product_id:
          type: string
          format: uuid
        product_name:
          type: string
          nullable: true
        unit_id:
          type: string
          format: uuid
          nullable: true
        quantity:
          type: string
        is_substitution:
          type: boolean
        sort_order:
          type: integer
          minimum: 0
        comment:
          type: string
          nullable: true
    BootstrapSyncReadyBouquet:
      type: object
      required: [id, store_id, name, price, quantity_available, show_composition, media, composition, version]
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        category_id:
          type: string
          format: uuid
          nullable: true
        recipe_id:
          type: string
          format: uuid
          nullable: true
        recipe_variant_id:
          type: string
          format: uuid
          nullable: true
        name:
          type: string
        description:
          type: string
          nullable: true
        sku:
          type: string
          nullable: true
        size_label:
          type: string
          nullable: true
        width_cm:
          type: string
          nullable: true
        height_cm:
          type: string
          nullable: true
        price:
          $ref: '#/components/schemas/BootstrapSyncReadyBouquetPrice'
        quantity_available:
          type: string
        assembled_at:
          type: string
          format: date-time
          nullable: true
        expires_at:
          type: string
          format: date-time
          nullable: true
        show_composition:
          type: boolean
        media:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncMedia'
        composition:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncReadyBouquetItem'
        version:
          type: integer
          minimum: 1
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncCustomerContact:
      type: object
      required: [id, type, value, is_primary, can_receive_marketing]
      properties:
        id:
          type: string
          format: uuid
        type:
          type: string
          enum: [phone, email, whatsapp, telegram, instagram]
        value:
          type: string
        normalized_value:
          type: string
          nullable: true
        is_primary:
          type: boolean
        can_receive_marketing:
          type: boolean
    BootstrapSyncCustomer:
      type: object
      required: [id, name, is_blacklisted, bonus_balance, contacts, version]
      description: |
        Минимизированная offline-проекция клиента. Не содержит даты рождения, пола, комментариев,
        metadata, закрепленного менеджера и адресов. Локальная БД POS обязана быть зашифрована.
      properties:
        id:
          type: string
          format: uuid
        primary_store_id:
          type: string
          format: uuid
          nullable: true
        name:
          type: string
        first_name:
          type: string
          nullable: true
        last_name:
          type: string
          nullable: true
        phone:
          type: string
          nullable: true
        phone_normalized:
          type: string
          nullable: true
        email:
          type: string
          format: email
          nullable: true
        email_normalized:
          type: string
          format: email
          nullable: true
        is_blacklisted:
          type: boolean
        bonus_balance:
          type: string
          pattern: '^\d+(?:\.\d{2})$'
          description: Информационный снимок; списание бонусов требует отдельной server-side операции.
        contacts:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncCustomerContact'
        version:
          type: integer
          minimum: 1
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncCashRegister:
      type: object
      required: [id, store_id, code, name, currency_code, is_default, sort_order, version]
      description: Активная касса текущего магазина без metadata и фискальных реквизитов.
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        code:
          type: string
        name:
          type: string
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
          description: Каноническая валюта магазина из SaaS-настроек.
        is_default:
          type: boolean
        sort_order:
          type: integer
          minimum: 0
        version:
          type: integer
          minimum: 1
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncPaymentMethod:
      type: object
      required: [id, code, name, type, currency_code, is_cash, requires_fiscalization, supports_refund, sort_order, version]
      description: |
        Активный способ оплаты для текущей точки. `provider_code` является только публичным кодом
        маршрутизации; settings, metadata, API-ключи, merchant secrets и фискальные credentials отсутствуют.
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
          nullable: true
        code:
          type: string
        name:
          type: string
        type:
          type: string
          enum: [cash, card, bank_transfer, online_card, bonus, certificate, other]
        provider_code:
          type: string
          nullable: true
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
        is_cash:
          type: boolean
        requires_fiscalization:
          type: boolean
        supports_refund:
          type: boolean
        sort_order:
          type: integer
          minimum: 0
        version:
          type: integer
          minimum: 1
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncOrderStatusTransition:
      type: object
      required: [to_status_id, requires_reason, sort_order]
      properties:
        to_status_id:
          type: string
          format: uuid
        source:
          type: string
          nullable: true
          description: null означает переход для любого источника заказа.
        requires_reason:
          type: boolean
        sort_order:
          type: integer
          minimum: 0
    BootstrapSyncOrderStatus:
      type: object
      required: [id, code, name, color, sort_order, is_initial, is_terminal, reserve_stock, release_stock, consume_stock, requires_reason, allow_any_transition, allowed_transitions, version]
      description: Эффективный активный статус воронки текущего магазина без metadata и внутренних bigint ID.
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
          nullable: true
        code:
          type: string
        name:
          type: string
        color:
          type: string
        description:
          type: string
          nullable: true
        sort_order:
          type: integer
          minimum: 0
        is_initial:
          type: boolean
        is_terminal:
          type: boolean
        reserve_stock:
          type: boolean
        release_stock:
          type: boolean
        consume_stock:
          type: boolean
        requires_reason:
          type: boolean
        allow_any_transition:
          type: boolean
        allowed_transitions:
          type: array
          items:
            $ref: '#/components/schemas/BootstrapSyncOrderStatusTransition'
        version:
          type: integer
          minimum: 1
        updated_at:
          type: string
          format: date-time
          nullable: true
    BootstrapSyncPage:
      type: object
      required: [limit, count, has_more]
      properties:
        limit:
          type: integer
        count:
          type: integer
        has_more:
          type: boolean
        next_cursor:
          type: string
          nullable: true
          description: Непрозрачный зашифрованный cursor; не является CRM identifier.
    BootstrapSyncStartResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, session, collections, server_time]
          properties:
            contract:
              type: string
              const: pos-bootstrap-sync.v1
            session:
              $ref: '#/components/schemas/BootstrapSyncSession'
            collections:
              type: array
              items:
                $ref: '#/components/schemas/BootstrapSyncCollectionSummary'
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    BootstrapSyncCollectionResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, session_id, collection, items, page, snapshot_at, server_time]
          properties:
            contract:
              type: string
              const: pos-bootstrap-sync.v1
            session_id:
              type: string
              format: uuid
            collection:
              type: string
              enum: [settings, categories, units, products, promo_codes, recipes, ready_bouquets, customers, cash_registers, payment_methods, order_statuses, orders]
            items:
              type: array
              items:
                oneOf:
                  - $ref: '#/components/schemas/BootstrapSyncSettings'
                  - $ref: '#/components/schemas/BootstrapSyncCategory'
                  - $ref: '#/components/schemas/BootstrapSyncUnit'
                  - $ref: '#/components/schemas/BootstrapSyncProduct'
                  - $ref: '#/components/schemas/BootstrapSyncRecipe'
                  - $ref: '#/components/schemas/BootstrapSyncReadyBouquet'
                  - $ref: '#/components/schemas/BootstrapSyncCustomer'
                  - $ref: '#/components/schemas/BootstrapSyncCashRegister'
                  - $ref: '#/components/schemas/BootstrapSyncPaymentMethod'
                  - $ref: '#/components/schemas/BootstrapSyncOrderStatus'
            page:
              $ref: '#/components/schemas/BootstrapSyncPage'
            snapshot_at:
              type: string
              format: date-time
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    BootstrapSyncCompleteResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, session, sync_cursor, offline_lease, server_time]
          properties:
            contract:
              type: string
              const: pos-bootstrap-sync.v1
            session:
              type: object
              required: [id, status, completed_at]
              properties:
                id:
                  type: string
                  format: uuid
                status:
                  type: string
                  const: completed
                completed_at:
                  type: string
                  format: date-time
            sync_cursor:
              type: object
              required: [id, snapshot_at]
              properties:
                id:
                  type: string
                  format: uuid
                snapshot_at:
                  type: string
                  format: date-time
            offline_lease:
              $ref: '#/components/schemas/OfflineLease'
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    DeltaSyncChange:
      type: object
      required: [id, collection, entity_id, operation, item, occurred_at]
      properties:
        id:
          type: string
          format: uuid
          description: UUID события для идемпотентного локального применения.
        collection:
          type: string
          enum: [settings, categories, units, products, promo_codes, recipes, ready_bouquets, customers, cash_registers, payment_methods, order_statuses, orders]
        entity_id:
          type: string
          format: uuid
        operation:
          type: string
          enum: [upsert, remove]
        item:
          type: [object, 'null']
          additionalProperties: true
          description: Полная актуальная проекция при upsert; null при remove.
        occurred_at:
          type: string
          format: date-time
    DeltaSyncResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, source_sync_cursor, changes, page, next_sync_cursor, server_time]
          properties:
            contract:
              type: string
              const: pos-delta-sync.v1
            source_sync_cursor:
              type: object
              required: [id]
              properties:
                id:
                  type: string
                  format: uuid
            changes:
              type: array
              items:
                $ref: '#/components/schemas/DeltaSyncChange'
            page:
              $ref: '#/components/schemas/BootstrapSyncPage'
            next_sync_cursor:
              type: [object, 'null']
              properties:
                id:
                  type: string
                  format: uuid
                created_at:
                  type: string
                  format: date-time
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    EntityPreflightRequest:
      type: object
      required: [entities]
      properties:
        entities:
          type: array
          minItems: 1
          maxItems: 50
          items:
            type: object
            required: [collection, id]
            properties:
              collection:
                type: string
                enum: [settings, categories, units, products, promo_codes, recipes, ready_bouquets, customers, cash_registers, payment_methods, order_statuses, orders]
              id:
                type: string
                format: uuid
              expected_revision:
                type: [string, 'null']
                pattern: '^[a-f0-9]{64}$'
                description: Revision из последней локально примененной POS-проекции.
    EntityPreflightResult:
      type: object
      required: [collection, entity_id, operation, expected_revision, current_revision, matches, item]
      properties:
        collection:
          type: string
        entity_id:
          type: string
          format: uuid
        operation:
          type: string
          enum: [upsert, remove]
        expected_revision:
          type: [string, 'null']
          pattern: '^[a-f0-9]{64}$'
        current_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
        matches:
          type: [boolean, 'null']
          description: null, если expected_revision не передан.
        item:
          type: [object, 'null']
          additionalProperties: true
    EntityPreflightResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, all_current, entities, checked_at, server_time]
          properties:
            contract:
              type: string
              const: pos-entity-preflight.v1
            all_current:
              type: boolean
              description: true, только если каждый переданный expected_revision совпал.
            entities:
              type: array
              items:
                $ref: '#/components/schemas/EntityPreflightResult'
            checked_at:
              type: string
              format: date-time
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    PosManualPriceAdjustment:
      type: object
      additionalProperties: false
      required: [mode, value, final_unit_price]
      description: |
        Запрошенное сотрудником изменение цены строки. Сервер не доверяет final_unit_price:
        он повторно получает базовую цену из каталога, вычисляет результат по mode/value и
        отклоняет операцию при несовпадении. Требует orders.discount и в текущем профиле,
        и в подписанном offline lease.
      properties:
        mode:
          type: string
          enum: [discount_percent, discount_amount, markup_percent, markup_amount, custom_price]
        value:
          type: string
          pattern: '^(0|[1-9][0-9]{0,9})(\.[0-9]{1,3})?$'
          description: Процент с точностью до 0.001 либо денежная величина с точностью до 0.01 в зависимости от mode.
        final_unit_price:
          type: string
          pattern: '^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$'
          description: Рассчитанная POS итоговая цена единицы; используется только как проверяемое утверждение клиента.
      examples:
        - mode: discount_percent
          value: '10.000'
          final_unit_price: '90.00'
    PosOfflineSaleV4Line:
      type: object
      additionalProperties: false
      required: [id, type, quantity]
      properties:
        id:
          type: string
          format: uuid
          description: UUIDv7 строки заказа.
        type:
          type: string
          enum: [product, recipe, ready_bouquet]
        product_id:
          type: string
          format: uuid
        recipe_id:
          type: string
          format: uuid
        recipe_variant_id:
          type: string
          format: uuid
        ready_bouquet_id:
          type: string
          format: uuid
        quantity:
          type: string
          pattern: '^[0-9]{1,9}(\.[0-9]{1,3})?$'
        price_adjustment:
          $ref: '#/components/schemas/PosManualPriceAdjustment'
      oneOf:
        - required: [product_id]
        - required: [recipe_id, recipe_variant_id]
        - required: [ready_bouquet_id]
    PosOfflineSaleV4Payload:
      type: object
      additionalProperties: false
      required: [contract, order_id, items]
      properties:
        contract:
          type: string
          const: pos-offline-sale.v4
        order_id:
          type: string
          format: uuid
          description: UUIDv7 заказа.
        customer_id:
          type: string
          format: uuid
        customer_create_operation_id:
          type: string
          format: uuid
        items:
          type: array
          minItems: 1
          maxItems: 50
          items:
            $ref: '#/components/schemas/PosOfflineSaleV4Line'
        promo_code:
          type: object
          additionalProperties: false
          required: [id, discount_amount]
          description: UUIDv7 промокода и локально рассчитанная скидка. Сервер повторно проверяет ревизию, срок, магазин, клиента, лимиты, состав корзины и точную сумму до создания заказа.
          properties:
            id:
              type: string
              format: uuid
            discount_amount:
              type: string
              pattern: '^(0|[1-9][0-9]{0,9})\.[0-9]{2}$'
        comment:
          type: string
          maxLength: 2000
    PosOfflinePaymentV2Payload:
      type: object
      additionalProperties: false
      required: [contract, payment_id, order_id, payment_method_id, amount]
      description: |
        Платеж POS версии v2. Для способа type=bonus сервер под блокировкой повторно проверяет
        клиента, действующий бонусный баланс, срок бонусов, лимит группы/магазина и уже
        списанную по заказу сумму. Локальный balance является только подсказкой интерфейса.
      properties:
        contract:
          type: string
          const: pos-offline-payment.v2
        payment_id:
          type: string
          format: uuid
          description: UUIDv7 платежа.
        order_id:
          type: string
          format: uuid
        payment_method_id:
          type: string
          format: uuid
        cash_shift_id:
          type: string
          format: uuid
        amount:
          type: string
          pattern: '^(0|[1-9][0-9]{0,11})(\.[0-9]{1,2})?$'
        reference:
          type: string
          maxLength: 255
        comment:
          type: string
          maxLength: 1000
    PosOfflineRefundV2Payload:
      type: object
      additionalProperties: false
      required: [contract, refund_id, order_id, original_payment_id, payment_method_id, amount]
      description: |
        Source-bound возврат exact бонусной оплаты POS. Сервер принимает V2 только если
        original_payment_id принадлежит этому заказу, имеет source=customer_bonus_balance,
        а payment_method_id соответствует исходному способу type=bonus. Баланс возвращается
        по связанной redemption-транзакции; касса и внешний reference запрещены.
      properties:
        contract:
          type: string
          const: pos-offline-refund.v2
        refund_id:
          type: string
          format: uuid
          description: Новый UUIDv7 возврата.
        order_id:
          type: string
          format: uuid
        original_payment_id:
          type: string
          format: uuid
          description: UUIDv7 exact исходной бонусной оплаты.
        payment_method_id:
          type: string
          format: uuid
        amount:
          type: string
          pattern: '^(0|[1-9][0-9]{0,11})(\.[0-9]{1,2})?$'
        comment:
          type: string
          maxLength: 1000
    PosOfflineAssignmentDecisionV1Payload:
      type: object
      additionalProperties: false
      required: [contract, assignment_id, order_id, action, expected_version]
      properties:
        contract:
          type: string
          const: pos-offline-assignment-decision.v1
        assignment_id:
          type: string
          format: uuid
          description: UUIDv7 назначения текущего сотрудника в exact магазине POS.
        order_id:
          type: string
          format: uuid
          description: UUIDv7 заказа, связанного с локально сохраненным назначением.
        action:
          type: string
          enum: [accept, decline]
        expected_version:
          type: integer
          minimum: 1
        reason:
          type: string
          minLength: 3
          maxLength: 512
          description: Обязательна только для decline и запрещена для accept.
    OfflinePushRequest:
      type: object
      required: [offline_lease_id, operations]
      properties:
        offline_lease_id:
          type: string
          format: uuid
        operations:
          type: array
          minItems: 1
          maxItems: 100
          items:
            type: object
            required: [id, idempotency_key, counter, type, created_at, payload]
            properties:
              id:
                type: string
                format: uuid
              idempotency_key:
                type: string
                format: uuid
              counter:
                type: integer
                minimum: 1
              type:
                type: string
                enum: [customer_create, sale, payment, refund, shift_open, shift_close, cash_in, cash_out, assignment_decision]
              created_at:
                type: string
                format: date-time
              expected_revisions:
                type: object
                additionalProperties:
                  type: string
                  pattern: '^[a-f0-9]{64}$'
              payload:
                type: object
                additionalProperties: true
                description: Для sale с ручной ценой и промокодом применяется PosOfflineSaleV4Payload; для bonus payment применяется PosOfflinePaymentV2Payload; для exact bonus refund применяется PosOfflineRefundV2Payload; для accept/decline назначения применяется PosOfflineAssignmentDecisionV1Payload.
    OfflinePushResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, operations, server_time]
          properties:
            contract:
              type: string
              const: pos-offline-push.v1
            operations:
              type: array
              items:
                type: object
                required: [id, status, replayed]
                properties:
                  id:
                    type: string
                    format: uuid
                  status:
                    type: string
                    enum: [queued, applied, conflict, rejected]
                  replayed:
                    type: boolean
                  received_at:
                    type: string
                    format: date-time
                  error_code:
                    type: string
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    OfflineStatusRequest:
      type: object
      required: [operation_ids]
      properties:
        operation_ids:
          type: array
          minItems: 1
          maxItems: 100
          uniqueItems: true
          items:
            type: string
            format: uuid
    OfflinePublicResult:
      type: [object, 'null']
      properties:
        code:
          type: string
          pattern: '^[a-z0-9_.-]{1,64}$'
        references:
          type: object
          additionalProperties:
            type: string
            format: uuid
      additionalProperties: false
    OfflineOperationStatus:
      type: object
      required: [id, status, terminal, acknowledged, result_revision, result, received_at, processed_at, acknowledged_at]
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          enum: [queued, applied, conflict, rejected, not_found]
        terminal:
          type: boolean
        acknowledged:
          type: boolean
        result_revision:
          type: [string, 'null']
          pattern: '^[a-f0-9]{64}$'
        result:
          $ref: '#/components/schemas/OfflinePublicResult'
        received_at:
          type: [string, 'null']
          format: date-time
        processed_at:
          type: [string, 'null']
          format: date-time
        acknowledged_at:
          type: [string, 'null']
          format: date-time
    OfflineStatusResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, operations, server_time]
          properties:
            contract:
              type: string
              const: pos-offline-status.v1
            operations:
              type: array
              items:
                $ref: '#/components/schemas/OfflineOperationStatus'
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    OfflineAckRequest:
      type: object
      required: [operations]
      properties:
        operations:
          type: array
          minItems: 1
          maxItems: 100
          items:
            type: object
            required: [id, result_revision]
            properties:
              id:
                type: string
                format: uuid
              result_revision:
                type: string
                pattern: '^[a-f0-9]{64}$'
    OfflineAckResult:
      type: object
      required: [id, status, replayed]
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          enum: [acknowledged, rejected]
        operation_status:
          type: string
          enum: [applied, conflict, rejected]
        result_revision:
          type: string
          pattern: '^[a-f0-9]{64}$'
        replayed:
          type: boolean
        acknowledged_at:
          type: string
          format: date-time
        error_code:
          type: string
          enum: [operation_not_found, operation_not_terminal, operation_result_changed]
    OfflineAckResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, operations, server_time]
          properties:
            contract:
              type: string
              const: pos-offline-ack.v1
            operations:
              type: array
              items:
                $ref: '#/components/schemas/OfflineAckResult'
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    AssignmentCommandRequest:
      type: object
      required: [expected_version, idempotency_key]
      properties:
        expected_version:
          type: integer
          minimum: 1
        idempotency_key:
          type: string
          format: uuid
    DeclineAssignmentRequest:
      allOf:
        - $ref: '#/components/schemas/AssignmentCommandRequest'
        - type: object
          required: [reason]
          properties:
            reason:
              type: string
              minLength: 1
              maxLength: 512
    Device:
      type: object
      required: [id, store_id, name, status, platform]
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        name:
          type: string
        status:
          type: string
          enum: [pending_activation, active, blocked, lost, archived]
        platform:
          type: string
          enum: [windows, macos]
    Employee:
      type: object
      required: [id, name, permissions]
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        permissions:
          type: array
          items:
            type: string
    ProfileDevice:
      type: object
      required: [id, name, platform]
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        platform:
          type: string
          enum: [windows, macos]
    Store:
      type: object
      required: [id, name, timezone, currency_code]
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        timezone:
          type: string
          example: Asia/Omsk
        currency_code:
          type: string
          pattern: '^[A-Z]{3}$'
          example: RUB
    Profile:
      type: object
      required: [employee, device, store, server_time]
      properties:
        employee:
          $ref: '#/components/schemas/Employee'
        device:
          $ref: '#/components/schemas/ProfileDevice'
        store:
          $ref: '#/components/schemas/Store'
        server_time:
          type: string
          format: date-time
    OrderBrief:
      type: object
      required: [id, number, status, type, source]
      properties:
        id:
          type: string
          format: uuid
        number:
          type: string
          nullable: true
        status:
          type: string
        type:
          type: string
          nullable: true
        source:
          type: string
        desired_at:
          type: string
          format: date-time
          nullable: true
    Assignment:
      type: object
      required: [id, version, role, status, assignment_method, allowed_actions, order, updated_at]
      properties:
        id:
          type: string
          format: uuid
        version:
          type: integer
          minimum: 1
        role:
          type: string
          enum: [manager, florist, courier, assistant]
        status:
          type: string
          enum: [pending_acceptance, active, declined, expired, ended, cancelled]
        assignment_method:
          type: string
          enum: [manual, auto, legacy_sync, legacy_backfill]
        acceptance_due_at:
          type: string
          format: date-time
          nullable: true
        accepted_at:
          type: string
          format: date-time
          nullable: true
        declined_at:
          type: string
          format: date-time
          nullable: true
        decline_reason:
          type: string
          nullable: true
        allowed_actions:
          type: array
          items:
            type: string
            enum: [accept, decline]
        order:
          $ref: '#/components/schemas/OrderBrief'
        updated_at:
          type: string
          format: date-time
    TaskNotification:
      type: object
      additionalProperties: false
      required: [id, task_id, order_id, event_type, title, body, task_title, context_type, status, priority, due_at, created_at, acknowledged_at]
      properties:
        id:
          type: string
          format: uuid
        task_id:
          type: string
          format: uuid
        order_id:
          type: [string, 'null']
          format: uuid
        event_type:
          type: string
          enum: [created, started, updated, completed, cancelled, overdue, reminder]
        title: { type: string, maxLength: 160 }
        body: { type: string, maxLength: 1000 }
        task_title: { type: string, maxLength: 255 }
        context_type:
          type: string
          enum: [general, personal, store, order, customer, product, stock]
        status:
          type: string
          enum: [pending, in_progress, completed, cancelled]
        priority:
          type: string
          enum: [low, normal, high, urgent]
        due_at: { type: [string, 'null'], format: date-time }
        created_at: { type: string, format: date-time }
        acknowledged_at:
          type: [string, 'null']
          format: date-time
          description: Первое подтверждение этого события exact POS-устройством и сотрудником.
    TaskNotificationCursor:
      type: object
      additionalProperties: false
      required: [created_at, id]
      properties:
        created_at: { type: string, format: date-time }
        id:
          type: string
          format: uuid
    TaskNotificationAcknowledgementRequest:
      type: object
      additionalProperties: false
      required: [contract, notification_ids]
      properties:
        contract:
          type: string
          const: pos-task-notification-acknowledgement.v1
        notification_ids:
          type: array
          minItems: 1
          maxItems: 100
          uniqueItems: true
          items:
            type: string
            format: uuid
    TaskNotificationAcknowledgement:
      type: object
      additionalProperties: false
      required: [id, acknowledged_at]
      properties:
        id:
          type: string
          format: uuid
        acknowledged_at:
          type: string
          format: date-time
    POSSubscriptionNotification:
      type: object
      additionalProperties: false
      required: [id, event_type, store_id, device_id, subscription_id, product_name, status, threshold_days, days_left, ends_at, title, body, created_at, acknowledged_at]
      properties:
        id:
          type: string
          format: uuid
        event_type:
          type: string
          enum: [warning_7, warning_3, warning_1]
        store_id:
          type: string
          format: uuid
        device_id:
          type: string
          format: uuid
        subscription_id:
          type: string
          format: uuid
        product_name: { type: string, maxLength: 120 }
        status:
          type: string
          enum: [active, trial]
        threshold_days:
          type: integer
          enum: [7, 3, 1]
        days_left:
          type: integer
          minimum: 0
          maximum: 7
        ends_at: { type: string, format: date-time }
        title: { type: string, maxLength: 160 }
        body: { type: string, maxLength: 500 }
        created_at: { type: string, format: date-time }
        acknowledged_at:
          type: [string, 'null']
          format: date-time
          description: Первое подтверждение этого события exact POS-устройством и сотрудником.
    POSSubscriptionNotificationAcknowledgementRequest:
      type: object
      additionalProperties: false
      required: [contract, notification_ids]
      properties:
        contract:
          type: string
          const: pos-subscription-notification-acknowledgement.v1
        notification_ids:
          type: array
          minItems: 1
          maxItems: 100
          uniqueItems: true
          items: { type: string, format: uuid }
    ActivateDeviceResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [device, device_token, token_type, expires_at, server_time]
          properties:
            device:
              $ref: '#/components/schemas/Device'
            device_token:
              type: string
              writeOnly: true
            token_type:
              type: string
              const: Bearer
            expires_at:
              type: string
              format: date-time
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    PosUpdateCheckResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data: { $ref: '#/components/schemas/PosUpdatePolicy' }
        request_id: { type: string, format: uuid }
    PinLoginResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [session_token, token_type, expires_at, profile]
          properties:
            session_token:
              type: string
              writeOnly: true
            token_type:
              type: string
              const: Bearer
            expires_at:
              type: string
              format: date-time
            profile:
              $ref: '#/components/schemas/Profile'
        request_id:
          type: string
          format: uuid
    ProfileResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/Profile'
        request_id:
          type: string
          format: uuid
    LogoutResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [logged_out, session_id]
          properties:
            logged_out:
              type: boolean
              const: true
            session_id:
              type: string
              format: uuid
        request_id:
          type: string
          format: uuid
    OfflineLease:
      type: object
      required:
        - id
        - contract
        - payload
        - signature
        - signature_algorithm
        - signature_key_version
        - public_key
        - public_key_fingerprint
        - issued_at
        - valid_until
        - counter_from
        - max_operation_counter
        - revoked
      properties:
        id:
          type: string
          format: uuid
        contract:
          type: string
          const: pos-offline-lease.v1
        payload:
          type: string
          description: Base64url без padding от точного UTF-8 JSON, по байтам которого проверяется signature.
        signature:
          type: string
          description: Base64url detached Ed25519 signature. Не является секретом.
        signature_algorithm:
          type: string
          const: Ed25519
        signature_key_version:
          type: string
        public_key:
          type: string
          description: Base64url Ed25519 public key; приватный ключ API никогда не возвращает.
        public_key_fingerprint:
          type: string
          pattern: '^[a-f0-9]{64}$'
        issued_at:
          type: string
          format: date-time
        valid_until:
          type: string
          format: date-time
        counter_from:
          type: integer
          minimum: 1
        max_operation_counter:
          type: integer
          minimum: 1
        revoked:
          type: boolean
    OfflineLeaseResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [lease]
          properties:
            lease:
              $ref: '#/components/schemas/OfflineLease'
        request_id:
          type: string
          format: uuid
    AssignmentListResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [items, count, server_time]
          properties:
            items:
              type: array
              items:
                $ref: '#/components/schemas/Assignment'
            count:
              type: integer
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    TaskNotificationFeedResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          additionalProperties: false
          required: [contract, items, count, has_more, cursor, server_time]
          properties:
            contract: { type: string, const: pos-task-notification-feed.v1 }
            items:
              type: array
              items: { $ref: '#/components/schemas/TaskNotification' }
            count: { type: integer, minimum: 0 }
            has_more: { type: boolean }
            cursor:
              oneOf:
                - $ref: '#/components/schemas/TaskNotificationCursor'
                - type: 'null'
            server_time: { type: string, format: date-time }
        request_id: { type: string, format: uuid }
    TaskNotificationAcknowledgementResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          additionalProperties: false
          required: [contract, items, count, server_time]
          properties:
            contract:
              type: string
              const: pos-task-notification-acknowledgement.v1
            items:
              type: array
              items:
                $ref: '#/components/schemas/TaskNotificationAcknowledgement'
            count: { type: integer, minimum: 0, maximum: 100 }
            server_time: { type: string, format: date-time }
        request_id: { type: string, format: uuid }
    POSSubscriptionNotificationFeedResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          additionalProperties: false
          required: [contract, items, count, unread_count, has_more, cursor, server_time]
          properties:
            contract: { type: string, const: pos-subscription-notification-feed.v1 }
            items:
              type: array
              items: { $ref: '#/components/schemas/POSSubscriptionNotification' }
            count: { type: integer, minimum: 0 }
            unread_count: { type: integer, minimum: 0 }
            has_more: { type: boolean }
            cursor:
              oneOf:
                - $ref: '#/components/schemas/TaskNotificationCursor'
                - type: 'null'
            server_time: { type: string, format: date-time }
        request_id: { type: string, format: uuid }
    POSSubscriptionNotificationAcknowledgementResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          additionalProperties: false
          required: [contract, items, count, server_time]
          properties:
            contract:
              type: string
              const: pos-subscription-notification-acknowledgement.v1
            items:
              type: array
              items: { $ref: '#/components/schemas/TaskNotificationAcknowledgement' }
            count: { type: integer, minimum: 0, maximum: 100 }
            server_time: { type: string, format: date-time }
        request_id: { type: string, format: uuid }
    AssignmentResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [assignment]
          properties:
            assignment:
              $ref: '#/components/schemas/Assignment'
        request_id:
          type: string
          format: uuid
    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
