openapi: 3.1.0
info:
  title: BloomCore API - Delivery Status History
  version: 1.2.0
  description: |
    Read-only API v1 для сверки append-only истории статусов доставки.
    Все `id` и `*_id` являются UUID; внутренние bigint ID не принимаются и не возвращаются.
    Endpoint ограничен tenant/store текущего поддомена и scope `deliveries.view`.
    API может раскрывать операционные данные; используйте минимальный scope, allowed IPs и отозыв токенов.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина.
security:
  - bearerAuth: []
tags:
  - name: DeliveryStatusHistory
    description: Подтвержденные переходы статуса доставки.
paths:
  /deliveries/{deliveryId}/status-history:
    get:
      tags: [DeliveryStatusHistory]
      summary: Получить историю статусов доставки
      description: |
        Возвращает события от новых к старым. Причина, адрес, телефон,
        курьер, цена и комментарий не возвращаются.
      x-required-api-scope: deliveries.view
      parameters:
        - $ref: '#/components/parameters/deliveryId'
        - $ref: '#/components/parameters/perPage'
        - $ref: '#/components/parameters/page'
      responses:
        '200':
          description: История доставки текущего tenant/store.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeliveryStatusHistoryResponse'
        '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'
webhooks:
  deliveryStatusChanged:
    post:
      tags: [DeliveryStatusHistory]
      summary: Изменен статус доставки
      description: |
        CRM отправляет подписанный immutable snapshot после commit бизнес-транзакции.
        `data.status_change.id` совпадает с UUID строки read API. Внутренняя причина,
        автор перехода и history metadata не передаются.
      parameters:
        - $ref: '#/components/parameters/webhookEvent'
        - $ref: '#/components/parameters/webhookEventId'
        - $ref: '#/components/parameters/webhookDeliveryId'
        - $ref: '#/components/parameters/webhookTimestamp'
        - $ref: '#/components/parameters/webhookSignature'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeliveryStatusWebhookEnvelope'
      responses:
        '200':
          description: Событие принято интеграцией.
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
  parameters:
    deliveryId:
      name: deliveryId
      in: path
      required: true
      schema:
        type: string
        format: uuid
        example: 019f5368-29d6-7ba2-b5b3-dbf6e40a9881
    perPage:
      name: per_page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 25
    page:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100000
        default: 1
    webhookEvent:
      name: X-CRM-Webhook-Event
      in: header
      required: true
      schema: {type: string, const: delivery.status_changed}
    webhookEventId:
      name: X-CRM-Webhook-Id
      in: header
      required: true
      schema: {type: string, format: uuid}
    webhookDeliveryId:
      name: X-CRM-Webhook-Delivery
      in: header
      required: true
      schema: {type: string, format: uuid}
    webhookTimestamp:
      name: X-CRM-Webhook-Timestamp
      in: header
      required: true
      schema: {type: string, pattern: '^[0-9]{10}$'}
    webhookSignature:
      name: X-CRM-Webhook-Signature
      in: header
      required: true
      schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
  headers:
    RateLimitLimit:
      schema: {type: integer}
    RateLimitRemaining:
      schema: {type: integer}
  schemas:
    DeliveryStatusHistoryResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success: {type: boolean, const: true}
        data:
          $ref: '#/components/schemas/DeliveryStatusHistoryData'
        request_id: {type: string, format: uuid}
    DeliveryStatusHistoryData:
      type: object
      required: [delivery_id, order_id, current_status, items, meta]
      properties:
        delivery_id:
          type: string
          format: uuid
          example: 019f5368-29d6-7ba2-b5b3-dbf6e40a9881
        order_id:
          type: string
          format: uuid
          example: 019f5368-4c81-74bc-aee2-538a8814e4bd
        current_status: {type: string}
        items:
          type: array
          items: {$ref: '#/components/schemas/DeliveryStatusEvent'}
        meta: {$ref: '#/components/schemas/PaginationMeta'}
    DeliveryStatusEvent:
      type: object
      required: [id, from_status, to_status, source, occurred_at]
      properties:
        id:
          type: string
          format: uuid
          example: 019f5369-0636-7a43-8d3b-b90cff8044ac
        from_status: {type: [string, 'null']}
        to_status: {type: string}
        source: {type: string, enum: [create, update, recalculate, failed, retry, cancel]}
        occurred_at: {type: string, format: date-time}
    DeliveryStatusWebhookEnvelope:
      type: object
      additionalProperties: false
      required: [event, event_id, created_at, payload_schema_version, tenant_id, store_id, retry_count, data]
      properties:
        event: {type: string, const: delivery.status_changed}
        event_id:
          type: string
          format: uuid
        created_at: {type: string, format: date-time}
        payload_schema_version: {type: string, const: crm.webhook.v1}
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data:
          $ref: '#/components/schemas/DeliveryStatusWebhookData'
    DeliveryStatusWebhookData:
      type: object
      additionalProperties: false
      required: [delivery, order, status_change]
      properties:
        delivery:
          $ref: '#/components/schemas/DeliveryWebhookDelivery'
        order:
          $ref: '#/components/schemas/DeliveryWebhookOrder'
        status_change:
          $ref: '#/components/schemas/DeliveryWebhookStatusChange'
    DeliveryWebhookDelivery:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, order_id, status]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        delivery_zone_id:
          type: [string, 'null']
          format: uuid
        delivery_interval_id:
          type: [string, 'null']
          format: uuid
        courier_id:
          type: [string, 'null']
          format: uuid
        status: {type: string}
        recipient_name: {type: [string, 'null']}
        recipient_phone: {type: [string, 'null']}
        city: {type: [string, 'null']}
        address: {type: [string, 'null']}
        entrance: {type: [string, 'null']}
        floor: {type: [string, 'null']}
        apartment: {type: [string, 'null']}
        scheduled_from: {type: [string, 'null'], format: date-time}
        scheduled_to: {type: [string, 'null'], format: date-time}
        delivery_price: {type: string}
        currency_code: {type: string}
        zone_check_status: {type: [string, 'null']}
        zone_check_message: {type: [string, 'null']}
        delivered_at: {type: [string, 'null'], format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    DeliveryWebhookOrder:
      type: object
      additionalProperties: false
      description: |
        Неизменяемый UUID-only snapshot заказа на момент перехода доставки.
        Контактные поля являются персональными данными и требуют защищенного хранения.
      required:
        - id
        - number
        - tenant_id
        - store_id
        - customer_id
        - recipient_customer_id
        - manager_id
        - florist_id
        - courier_id
        - source
        - type
        - status
        - payment_status
        - delivery_status
        - customer_name
        - customer_phone
        - customer_email
        - recipient_same_as_customer
        - recipient_name
        - recipient_phone
        - is_surprise
        - do_not_call_recipient
        - desired_at
        - subtotal
        - discount_total
        - delivery_price
        - total
        - paid_total
        - refunded_total
        - payment_due
        - completed_at
        - cancelled_at
        - created_at
        - updated_at
        - items
      properties:
        id:
          type: string
          format: uuid
        number: {type: string}
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        customer_id:
          type: [string, 'null']
          format: uuid
        recipient_customer_id:
          type: [string, 'null']
          format: uuid
        manager_id:
          type: [string, 'null']
          format: uuid
        florist_id:
          type: [string, 'null']
          format: uuid
        courier_id:
          type: [string, 'null']
          format: uuid
        source: {type: [string, 'null']}
        type: {type: [string, 'null']}
        status: {type: string}
        payment_status: {type: [string, 'null']}
        delivery_status: {type: [string, 'null']}
        customer_name: {type: [string, 'null']}
        customer_phone: {type: [string, 'null']}
        customer_email: {type: [string, 'null'], format: email}
        recipient_same_as_customer: {type: boolean}
        recipient_name: {type: [string, 'null']}
        recipient_phone: {type: [string, 'null']}
        is_surprise: {type: boolean}
        do_not_call_recipient: {type: boolean}
        desired_at: {type: [string, 'null'], format: date-time}
        subtotal: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        discount_total: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        delivery_price: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        total: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        paid_total: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        refunded_total: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        payment_due: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        completed_at: {type: [string, 'null'], format: date-time}
        cancelled_at: {type: [string, 'null'], format: date-time}
        created_at: {type: [string, 'null'], format: date-time}
        updated_at: {type: [string, 'null'], format: date-time}
        items:
          type: array
          items:
            $ref: '#/components/schemas/DeliveryWebhookOrderItem'
    DeliveryWebhookOrderItem:
      type: object
      additionalProperties: false
      required: [id, product_id, inventory_batch_id, type, name, qty, unit_price, discount_total, total, is_stock_tracked]
      properties:
        id:
          type: string
          format: uuid
        product_id:
          type: [string, 'null']
          format: uuid
        inventory_batch_id:
          type: [string, 'null']
          format: uuid
        type: {type: [string, 'null']}
        name: {type: string}
        qty: {type: string, pattern: '^-?[0-9]+\\.[0-9]{3}$'}
        unit_price: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        discount_total: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        total: {type: string, pattern: '^-?[0-9]+\\.[0-9]{2}$'}
        is_stock_tracked: {type: boolean}
    DeliveryWebhookStatusChange:
      type: object
      additionalProperties: false
      required: [id, from_status, to_status, source, occurred_at]
      properties:
        id:
          type: string
          format: uuid
          example: 019f5369-0636-7a43-8d3b-b90cff8044ac
        from_status: {type: [string, 'null']}
        to_status: {type: string}
        source: {type: string, enum: [create, update, recalculate, failed, retry, cancel]}
        occurred_at: {type: string, format: date-time}
    PaginationMeta:
      type: object
      required: [total, per_page, current_page, last_page]
      properties:
        total: {type: integer, minimum: 0}
        per_page: {type: integer, minimum: 1, maximum: 100}
        current_page: {type: integer, minimum: 1}
        last_page: {type: integer, minimum: 1}
    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}
        request_id: {type: string, format: uuid}
  responses:
    Unauthenticated:
      description: Bearer token отсутствует или недействителен.
      content: {application/json: {schema: {$ref: '#/components/schemas/ErrorResponse'}}}
    Forbidden:
      description: Нет scope `deliveries.view` или RBAC-права `delivery.view`.
      content: {application/json: {schema: {$ref: '#/components/schemas/ErrorResponse'}}}
    NotFound:
      description: UUID не найден в текущем tenant/store.
      content: {application/json: {schema: {$ref: '#/components/schemas/ErrorResponse'}}}
    ValidationError:
      description: Ошибка пагинации.
      content: {application/json: {schema: {$ref: '#/components/schemas/ErrorResponse'}}}
    TooManyRequests:
      description: Превышен rate limit API-токена.
      headers:
        Retry-After: {schema: {type: integer}}
        X-RateLimit-Limit: {$ref: '#/components/headers/RateLimitLimit'}
        X-RateLimit-Remaining: {$ref: '#/components/headers/RateLimitRemaining'}
      content: {application/json: {schema: {$ref: '#/components/schemas/ErrorResponse'}}}
