openapi: 3.1.0
info:
  title: BloomCore API - Stock Webhooks
  version: 1.0.0
  description: |
    Подписанный webhook `stock.changed` для POS и внешнего складского учета. Все CRM
    `id` и `*_id` являются UUID; внутренние bigint ID не отправляются. Payload может
    содержать закупочную цену и причину движения. Проверяйте HMAC до JSON parsing,
    ограничивайте доступ и не записывайте полное тело события в открытые логи.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина.
paths: {}
webhooks:
  stockChanged:
    post:
      summary: Изменились остаток, движение или резерв товара
      description: |
        Обязательные `stock_balance` и `product` описывают актуальный snapshot.
        `stock_movement` и `stock_reservation` nullable и зависят от источника изменения.
        Получатель дедуплицирует событие по `event_id` и применяет баланс только при
        более новой `sync_version` в том же UUID tenant, магазина и товара.
      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/StockChangedWebhookEnvelope'
            example:
              event: stock.changed
              event_id: 019f58c4-0282-7550-adb5-c8dfbe14e0f4
              created_at: '2026-07-18T08:00:00+00:00'
              payload_schema_version: crm.webhook.v1
              tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
              store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
              retry_count: 0
              data:
                stock_balance:
                  id: 019f58c4-18d1-74fe-a087-f39dcc955e63
                  tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
                  store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
                  product_id: 019f58c2-038f-75ec-a49a-694503ec63e4
                  qty_available: '12.000'
                  qty_reserved: '3.000'
                  qty_total: '15.000'
                  sync_version: 9
                  sync_updated_at: '2026-07-18T07:59:58+00:00'
                  updated_at: '2026-07-18T07:59:58+00:00'
                stock_movement:
                  id: 019f58c4-298f-740a-a934-c73755fa02f5
                  tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
                  store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
                  related_store_id: null
                  product_id: 019f58c2-038f-75ec-a49a-694503ec63e4
                  inventory_batch_id: 019f58c4-342a-7c57-9667-4c0480452d16
                  supplier_id: 019f58c4-3e5f-79c2-a93d-392a4d191b0d
                  user_id: 019f58c4-46f8-7ed3-a118-b8c14ca3d90c
                  type: receipt
                  qty_delta: '12.000'
                  qty_before: '0.000'
                  qty_after: '12.000'
                  purchase_price: '140.00'
                  occurred_at: '2026-07-18T07:59:58+00:00'
                  reason: Приход от поставщика
                  reference_uuid: null
                  stock_document_id: 019f58c4-4ead-75f1-9da5-8a547882bf32
                  stock_document_item_id: 019f58c4-5764-7a5a-86b4-fe599a287674
                  stock_reservation_id: null
                  created_at: '2026-07-18T07:59:58+00:00'
                stock_reservation: null
                product:
                  id: 019f58c2-038f-75ec-a49a-694503ec63e4
                  tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
                  store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
                  folder_id: 019f58c1-f9cf-7264-ae3b-e00bdfeb1ad8
                  type: flower
                  name: Роза Explorer
                  sku: ROSE-EX
                  unit_id: null
                  is_stock_tracked: true
                  is_popular: true
                  min_stock_qty: '20.000'
                  allow_negative_stock: false
                  allow_fractional_quantity: true
                  default_price: '350.00'
                  default_cost: '140.00'
                  freshness_days: 7
                  is_visible_to_franchisor: true
                  status: active
                  sync_version: 4
                  sync_updated_at: '2026-07-18T07:59:58+00:00'
                  sync_deleted_at: null
                  created_at: '2026-07-01T08:00:00+00:00'
                  updated_at: '2026-07-18T07:59:58+00:00'
      responses:
        '200':
          description: Событие принято интеграцией.
components:
  parameters:
    webhookEvent:
      name: X-CRM-Webhook-Event
      in: header
      required: true
      schema: {type: string, const: stock.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}$'}
  schemas:
    StockChangedWebhookEnvelope:
      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: stock.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/StockChangedWebhookData'}
    StockChangedWebhookData:
      type: object
      additionalProperties: false
      required: [stock_balance, stock_movement, stock_reservation, product]
      properties:
        stock_balance: {$ref: '#/components/schemas/StockWebhookBalance'}
        stock_movement:
          oneOf:
            - {$ref: '#/components/schemas/StockWebhookMovement'}
            - {type: 'null'}
        stock_reservation:
          oneOf:
            - {$ref: '#/components/schemas/StockWebhookReservation'}
            - {type: 'null'}
        product: {$ref: '#/components/schemas/ProductWebhookProduct'}
    StockWebhookBalance:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, product_id, qty_available, qty_reserved, qty_total, sync_version, sync_updated_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        product_id:
          type: string
          format: uuid
        qty_available: {type: string, pattern: '^-?[0-9]+\.[0-9]{3}$'}
        qty_reserved: {type: string, pattern: '^-?[0-9]+\.[0-9]{3}$'}
        qty_total: {type: string, pattern: '^-?[0-9]+\.[0-9]{3}$'}
        sync_version: {type: integer, minimum: 0}
        sync_updated_at: {type: [string, 'null'], format: date-time}
        updated_at: {type: string, format: date-time}
    ProductWebhookProduct:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, folder_id, type, name, sku, unit_id, is_stock_tracked, is_popular, min_stock_qty, allow_negative_stock, allow_fractional_quantity, default_price, default_cost, freshness_days, is_visible_to_franchisor, status, sync_version, sync_updated_at, sync_deleted_at, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        folder_id:
          type: [string, 'null']
          format: uuid
        type: {type: string, enum: [flower, product, consumable, gift, certificate, service]}
        name: {type: string, minLength: 1}
        sku: {type: [string, 'null']}
        unit_id:
          type: [string, 'null']
          format: uuid
        is_stock_tracked: {type: boolean}
        is_popular: {type: boolean}
        min_stock_qty: {type: string, pattern: '^[0-9]+\.[0-9]{3}$'}
        allow_negative_stock: {type: boolean}
        allow_fractional_quantity: {type: boolean}
        default_price: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
        default_cost: {type: [string, 'null'], pattern: '^[0-9]+\.[0-9]{2}$'}
        freshness_days: {type: [integer, 'null'], minimum: 0}
        is_visible_to_franchisor: {type: boolean}
        status: {type: string, enum: [active, archived]}
        sync_version: {type: integer, minimum: 0}
        sync_updated_at: {type: [string, 'null'], format: date-time}
        sync_deleted_at: {type: [string, 'null'], format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    StockWebhookMovement:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, related_store_id, product_id, inventory_batch_id, supplier_id, user_id, type, qty_delta, qty_before, qty_after, purchase_price, occurred_at, reason, reference_uuid, stock_document_id, stock_document_item_id, stock_reservation_id, created_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        related_store_id:
          type: [string, 'null']
          format: uuid
        product_id:
          type: string
          format: uuid
        inventory_batch_id:
          type: [string, 'null']
          format: uuid
        supplier_id:
          type: [string, 'null']
          format: uuid
        user_id:
          type: [string, 'null']
          format: uuid
        type: {type: string, enum: [receipt, writeoff, transfer_out, transfer_in, inventory_adjustment]}
        qty_delta: {type: string, pattern: '^-?[0-9]+\.[0-9]{3}$'}
        qty_before: {type: string, pattern: '^-?[0-9]+\.[0-9]{3}$'}
        qty_after: {type: string, pattern: '^-?[0-9]+\.[0-9]{3}$'}
        purchase_price: {type: [string, 'null'], pattern: '^-?[0-9]+\.[0-9]{2}$'}
        occurred_at: {type: string, format: date-time}
        reason: {type: [string, 'null']}
        reference_uuid:
          type: [string, 'null']
          format: uuid
        stock_document_id:
          type: [string, 'null']
          format: uuid
        stock_document_item_id:
          type: [string, 'null']
          format: uuid
        stock_reservation_id:
          type: [string, 'null']
          format: uuid
        created_at: {type: string, format: date-time}
    StockWebhookReservation:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, product_id, inventory_batch_id, order_id, order_item_id, status, qty, reserved_at, released_at, consumed_at, reason]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        product_id:
          type: string
          format: uuid
        inventory_batch_id:
          type: [string, 'null']
          format: uuid
        order_id:
          type: [string, 'null']
          format: uuid
        order_item_id:
          type: [string, 'null']
          format: uuid
        status: {type: string, enum: [reserved, released, consumed]}
        qty: {type: string, pattern: '^-?[0-9]+\.[0-9]{3}$'}
        reserved_at: {type: [string, 'null'], format: date-time}
        released_at: {type: [string, 'null'], format: date-time}
        consumed_at: {type: [string, 'null'], format: date-time}
        reason: {type: [string, 'null']}
