openapi: 3.1.0
info:
  title: BloomCore Mobile Client Notification API
  version: 1.2.0
  description: |
    Закрытый first-party API официального мобильного приложения BloomCore.
    Он не является публичным интеграционным API и не принимает API-токены,
    созданные владельцем магазина. Bearer-сессия привязана к сотруднику,
    компании и UUID конкретной установки приложения; перед каждым запросом
    сервер повторно проверяет активность сотрудника, session_version,
    подтверждение 2FA, если она включена,
    доступ к магазину и действующую подписку `mobile.access`.

    Штатный вход принимает пароль и текущий TOTP-код, если сотрудник включил
    2FA в CRM. Для сотрудника без 2FA поле two_factor_code можно опустить или
    передать null; сервер не требует настройки 2FA. Парольная сессия хранится
    с two_factor_verified_at = null, без фиктивного подтверждения. Включение
    и отключение 2FA отзывает старые сессии через session_version.
    Контракты mobile-session-*.v1 и формат ответов не меняются; ранее
    выпущенные клиенты с TOTP остаются совместимыми. Access secret живет
    ограниченное время, refresh secret ротируется при каждом использовании
    и имеет абсолютный срок действия. В БД сохраняются только SHA-256.
    Пароль, TOTP, access/refresh secret нельзя писать в логи, аналитику,
    crash reports, proxy access body или пользовательские audit metadata.

    Лента содержит только UUID бизнес-ресурсов и безопасную проекцию задач.
    Внутренние bigint ID, email, телефон, токен, хеш токена, CRM URL и
    реквизиты других сотрудников не возвращаются. Подтверждение прочтения
    независимо для каждой установки приложения и не изменяет общий
    `notifications.read_at`.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1/mobile
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина, выбранного в официальном приложении.
tags:
  - name: Authentication
    description: Парольный вход с TOTP для включенной 2FA, rotating refresh и отзыв exact installation session.
  - name: TaskNotifications
    description: Инкрементальная лента уведомлений о задачах текущего сотрудника.
paths:
  /auth/login:
    post:
      tags: [Authentication]
      summary: Создать first-party mobile session
      description: |
        Выполняет tenant-scoped проверку email и пароля, TOTP при включенной 2FA,
        active user, store access и подписки `mobile.access`. Повторное
        успешное подключение того же пользователя и UUID установки отзывает
        прежнюю active session. Recovery code этим endpoint не принимается.
        Для включенной 2FA отсутствующий код дает 401; некорректный формат
        переданного кода дает 422. Проверки rate limit и запрета повторного
        использования TOTP сохраняются. Поле two_factor_code не является
        безусловно обязательным в схеме, так как зависит от состояния аккаунта.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LoginRequest'
      responses:
        '201':
          description: Access и refresh secrets выданы один раз.
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SessionResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/RateLimited'
  /auth/refresh:
    post:
      tags: [Authentication]
      summary: Ротировать access и refresh secrets
      description: |
        Authorization Bearer содержит refresh secret, а не access secret.
        Сервер под row lock проверяет exact installation, tenant/store,
        абсолютный refresh expiry, active user, session_version, доступ и
        подписку. Успешный вызов атомарно инвалидирует оба прежних secrets.
      security:
        - mobileRefreshBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RefreshRequest'
      responses:
        '200':
          description: Новая пара secrets той же session UUID.
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SessionResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/RateLimited'
  /auth/logout:
    post:
      tags: [Authentication]
      summary: Отозвать текущую mobile session
      security:
        - mobileBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LogoutRequest'
      responses:
        '200':
          description: Exact session отозвана; оба secrets больше не действуют.
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LogoutResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /notifications:
    get:
      tags: [TaskNotifications]
      summary: Получить ленту уведомлений мобильного клиента
      description: |
        Без cursor возвращает последние записи в возрастающем порядке.
        Связанная пара `cursor_created_at + cursor_id` возвращает только
        последующие записи. Проекция ограничена текущими tenant, магазином,
        сотрудником, правом `tasks.view` и target `mobile`.
      security:
        - mobileBearer: []
      parameters:
        - name: cursor_created_at
          in: query
          required: false
          description: UTC/RFC3339 timestamp последнего полученного элемента.
          schema:
            type: string
            format: date-time
        - name: cursor_id
          in: query
          required: false
          description: UUID последнего полученного уведомления.
          schema:
            type: string
            format: uuid
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
      responses:
        '200':
          description: UUID-only лента и состояние exact mobile instance.
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotificationFeedResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
  /notifications/acknowledge:
    post:
      tags: [TaskNotifications]
      summary: Подтвердить прочтение уведомлений текущей установкой
      description: |
        Идемпотентно создает receipt для exact tenant, магазина, сотрудника,
        `client_type=mobile`, UUID установки и UUID уведомления. Чужие,
        неизвестные, malformed либо больше не входящие в безопасную проекцию
        UUID отсутствуют в `items` и не раскрываются отдельной ошибкой.
      security:
        - mobileBearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AcknowledgeRequest'
      responses:
        '200':
          description: Идемпотентный набор подтвержденных уведомлений.
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AcknowledgeResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
components:
  securitySchemes:
    mobileBearer:
      type: http
      scheme: bearer
      bearerFormat: BloomCore first-party mobile session
      description: |
        Секрет конкретной установки официального приложения. Публичные
        integration API-токены и POS-токены не подходят.
    mobileRefreshBearer:
      type: http
      scheme: bearer
      bearerFormat: BloomCore rotating mobile refresh secret
      description: |
        Одноразовый rotating refresh secret exact installation. После
        успешного refresh прежний secret немедленно становится недействительным.
  schemas:
    LoginRequest:
      type: object
      additionalProperties: false
      required:
        - contract
        - email
        - password
        - client_instance_uuid
        - platform
        - app_version
      properties:
        contract:
          type: string
          const: mobile-session-login.v1
        email:
          type: string
          format: email
          maxLength: 255
        password:
          type: string
          format: password
          maxLength: 1024
          writeOnly: true
        two_factor_code:
          type: [string, 'null']
          description: Текущий TOTP-код обязателен только при включенной 2FA; иначе поле можно опустить или передать null.
          pattern: '^\d{6}$'
          writeOnly: true
        client_instance_uuid:
          type: string
          format: uuid
        platform:
          type: string
          enum: [ios, android]
        app_version:
          type: string
          pattern: '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)'
          maxLength: 64
    RefreshRequest:
      type: object
      additionalProperties: false
      required: [contract, client_instance_uuid, platform, app_version]
      properties:
        contract:
          type: string
          const: mobile-session-refresh.v1
        client_instance_uuid:
          type: string
          format: uuid
        platform:
          type: string
          enum: [ios, android]
        app_version:
          type: string
          maxLength: 64
    LogoutRequest:
      type: object
      additionalProperties: false
      required: [contract]
      properties:
        contract:
          type: string
          const: mobile-session-logout.v1
    SessionResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          additionalProperties: false
          required:
            - contract
            - token_type
            - access_token
            - refresh_token
            - session_id
            - client_instance_uuid
            - tenant_id
            - store_id
            - user_id
            - expires_at
            - refresh_expires_at
            - server_time
          properties:
            contract:
              type: string
              enum: [mobile-session-login.v1, mobile-session-refresh.v1]
            token_type:
              type: string
              const: Bearer
            access_token:
              type: string
              pattern: '^[A-Za-z0-9_-]{64}$'
              writeOnly: true
            refresh_token:
              type: string
              pattern: '^[A-Za-z0-9_-]{64}$'
              writeOnly: true
            session_id:
              type: string
              format: uuid
            client_instance_uuid:
              type: string
              format: uuid
            tenant_id:
              type: string
              format: uuid
            store_id:
              type: string
              format: uuid
            user_id:
              type: string
              format: uuid
            expires_at:
              type: string
              format: date-time
            refresh_expires_at:
              type: string
              format: date-time
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    LogoutResponse:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          additionalProperties: false
          required: [contract, session_id, revoked_at, server_time]
          properties:
            contract:
              type: string
              const: mobile-session-logout.v1
            session_id:
              type: string
              format: uuid
            revoked_at:
              type: string
              format: date-time
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    NotificationFeedResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, items, count, unread_count, has_more, cursor, server_time]
          properties:
            contract:
              type: string
              const: mobile-task-notification-feed.v1
            items:
              type: array
              items:
                $ref: '#/components/schemas/TaskNotification'
            count:
              type: integer
              minimum: 0
            unread_count:
              type: integer
              minimum: 0
            has_more:
              type: boolean
            cursor:
              oneOf:
                - $ref: '#/components/schemas/Cursor'
                - type: 'null'
            server_time:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    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
        status:
          type: string
        priority:
          type: string
        due_at:
          oneOf:
            - type: string
              format: date-time
            - type: 'null'
        created_at:
          oneOf:
            - type: string
              format: date-time
            - type: 'null'
        acknowledged_at:
          oneOf:
            - type: string
              format: date-time
            - type: 'null'
    Cursor:
      type: object
      additionalProperties: false
      required: [created_at, id]
      properties:
        created_at:
          type: string
          format: date-time
        id:
          type: string
          format: uuid
    AcknowledgeRequest:
      type: object
      additionalProperties: false
      required: [contract, notification_ids]
      properties:
        contract:
          type: string
          const: mobile-task-notification-acknowledgement.v1
        notification_ids:
          type: array
          minItems: 1
          maxItems: 100
          uniqueItems: true
          items:
            type: string
            format: uuid
    AcknowledgeResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [contract, items, count, server_time]
          properties:
            contract:
              type: string
              const: mobile-task-notification-acknowledgement.v1
            items:
              type: array
              items:
                type: object
                additionalProperties: false
                required: [id, acknowledged_at]
                properties:
                  id:
                    type: string
                    format: uuid
                  acknowledged_at:
                    type: string
                    format: date-time
            count:
              type: integer
              minimum: 0
            server_time:
              type: string
              format: date-time
        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
  responses:
    Unauthenticated:
      description: Mobile session отсутствует, истекла или отозвана.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: Нет tenant/store/permission/subscription/2FA доступа.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ValidationError:
      description: Нарушен versioned request, cursor либо acknowledgement contract.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Conflict:
      description: TOTP-код уже использован для другой mobile login операции.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RateLimited:
      description: Превышен server-side лимит password, TOTP или refresh попыток.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
