openapi: 3.1.0
info:
  title: BloomCore API - Suppliers and Fraud
  version: 1.0.0
  description: |
    API v1 для работы с претензиями поставщиков, файлами претензий, историей
    рейтингов поставщиков и antifraud-событиями в tenant/store контексте
    текущего поддомена.

    Все методы требуют Bearer API-токен. Дополнительно каждый endpoint проверяет
    scope API-токена и внутреннее право пользователя токена в текущем магазине.
    В публичном API все поля `id` и `*_id` являются UUID-строками; внутренние
    bigint ID из БД не принимаются и не возвращаются. Использование API может
    необратимо изменить претензии поставщиков, файлы, рейтинги, antifraud-события
    и связанные webhook-уведомления, поэтому интеграции должны использовать
    минимальные scopes, allowed IPs и `Idempotency-Key` для изменяющих запросов.

    `supplierId` может ссылаться на общего поставщика компании (`store_id = null`)
    или поставщика текущего магазина. Поставщики, претензии, рейтинги и файлы
    другого магазина возвращают `404`. В antifraud API `order_id` принимается
    только из текущего магазина, `user_id` - только для активного сотрудника с
    активным доступом к текущему магазину, а `customer_id` остается tenant-wide.

    События поставщиков: `supplier.claim_created`, `supplier.rating_updated`,
    `supplier.return_created`. Событие `supplier.return_created` создается
    CRM-действием возврата поставщику по претензии и не имеет отдельного
    публичного REST endpoint-а в первом слое API.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина или tenant-контекста.
security:
  - bearerAuth: []
tags:
  - name: Suppliers
    description: Претензии, файлы претензий и рейтинг поставщиков.
  - name: FraudEvents
    description: Antifraud-события, подозрительные действия и ручная разметка.
paths:
  /suppliers/{supplierId}/claims:
    get:
      tags: [Suppliers]
      operationId: listSupplierClaims
      summary: Список претензий поставщика
      description: |
        Возвращает претензии выбранного поставщика в текущем tenant/store scope.
        Требует API scope `suppliers.view` и право `stock.view`.
      x-required-api-scope: suppliers.view
      x-required-crm-permission: stock.view
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/supplierClaimStatus'
        - $ref: '#/components/parameters/supplierClaimType'
        - $ref: '#/components/parameters/severity'
        - $ref: '#/components/parameters/search'
        - $ref: '#/components/parameters/perPage'
        - $ref: '#/components/parameters/page'
      responses:
        '200':
          description: Список претензий поставщика.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierClaimListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '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'
    post:
      tags: [Suppliers]
      operationId: createSupplierClaim
      summary: Создать претензию поставщику
      description: |
        Создает претензию поставщику через доменный сервис качества поставщиков.
        После успешного создания ставится webhook `supplier.claim_created`.
        Требует API scope `suppliers.claims.create` и право `stock.create`.
      x-required-api-scope: suppliers.claims.create
      x-required-crm-permission: stock.create
      x-produced-webhook-event: supplier.claim_created
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSupplierClaimRequest'
      responses:
        '201':
          description: Претензия создана.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierClaimResponse'
        '400':
          $ref: '#/components/responses/InvalidIdempotencyKey'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /suppliers/{supplierId}/claims/{claimId}/files:
    get:
      tags: [Suppliers]
      operationId: listSupplierClaimFiles
      summary: Список файлов претензии поставщика
      description: |
        Возвращает метаданные приватных файлов претензии поставщика в текущем
        tenant/store scope. Физический S3 path не раскрывается. Требует API
        scope `suppliers.claim_files.view` и право `stock.view`.
      x-required-api-scope: suppliers.claim_files.view
      x-required-crm-permission: stock.view
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/claimId'
        - $ref: '#/components/parameters/mimeType'
        - $ref: '#/components/parameters/search'
        - $ref: '#/components/parameters/perPage'
        - $ref: '#/components/parameters/page'
      responses:
        '200':
          description: Список файлов претензии.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierClaimFileListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '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'
    post:
      tags: [Suppliers]
      operationId: uploadSupplierClaimFile
      summary: Загрузить файл претензии поставщика
      description: |
        Загружает файл в приватный S3 и создает запись `supplier_claim_files`.
        Максимальный размер файла - 50 МБ. Требует API scope
        `suppliers.claim_files.manage` и право `stock.update`.
      x-required-api-scope: suppliers.claim_files.manage
      x-required-crm-permission: stock.update
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/claimId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/UploadSupplierClaimFileRequest'
      responses:
        '201':
          description: Файл загружен.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierClaimFileResponse'
        '400':
          $ref: '#/components/responses/InvalidIdempotencyKey'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /suppliers/{supplierId}/claims/{claimId}/files/{fileId}/download:
    get:
      tags: [Suppliers]
      operationId: downloadSupplierClaimFile
      summary: Получить временную ссылку на файл претензии
      description: |
        Возвращает временную ссылку на приватный S3-файл. Ссылка действует
        10 минут. Требует API scope `suppliers.claim_files.view` и право
        `stock.view`.
      x-required-api-scope: suppliers.claim_files.view
      x-required-crm-permission: stock.view
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/claimId'
        - $ref: '#/components/parameters/fileId'
      responses:
        '200':
          description: Временная ссылка на файл.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierClaimFileDownloadResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /suppliers/{supplierId}/claims/{claimId}/files/{fileId}:
    delete:
      tags: [Suppliers]
      operationId: deleteSupplierClaimFile
      summary: Удалить файл претензии поставщика
      description: |
        Soft-delete записи файла и удаление физического объекта из S3 выполняются
        в одной операции. Требует API scope `suppliers.claim_files.manage` и
        право `stock.update`.
      x-required-api-scope: suppliers.claim_files.manage
      x-required-crm-permission: stock.update
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/claimId'
        - $ref: '#/components/parameters/fileId'
      responses:
        '200':
          description: Файл удален.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierClaimFileDeleteResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /suppliers/{supplierId}/rating:
    get:
      tags: [Suppliers]
      operationId: getSupplierRatingHistory
      summary: История рейтинга поставщика
      description: |
        Возвращает краткую карточку поставщика, последнюю оценку и историю
        оценок. Требует API scope `suppliers.view` и право `stock.view`.
      x-required-api-scope: suppliers.view
      x-required-crm-permission: stock.view
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/perPage'
        - $ref: '#/components/parameters/page'
      responses:
        '200':
          description: История рейтингов поставщика.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierRatingHistoryResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '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'
  /suppliers/{supplierId}/ratings:
    post:
      tags: [Suppliers]
      operationId: createSupplierRating
      summary: Добавить оценку поставщика
      description: |
        Создает новую историческую оценку поставщика. После успешной записи
        ставится webhook `supplier.rating_updated`. Требует API scope
        `suppliers.ratings.create` и право `stock.update`.
      x-required-api-scope: suppliers.ratings.create
      x-required-crm-permission: stock.update
      x-produced-webhook-event: supplier.rating_updated
      parameters:
        - $ref: '#/components/parameters/supplierId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSupplierRatingRequest'
      responses:
        '201':
          description: Рейтинг поставщика записан.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupplierRatingResponse'
        '400':
          $ref: '#/components/responses/InvalidIdempotencyKey'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /fraud/events:
    get:
      tags: [FraudEvents]
      operationId: listFraudEvents
      summary: Список antifraud-событий
      description: |
        Возвращает antifraud-события текущего tenant/store scope. Требует API
        scope `fraud_events.view` и право `integrations.view`.
      x-required-api-scope: fraud_events.view
      x-required-crm-permission: integrations.view
      parameters:
        - $ref: '#/components/parameters/fraudEventStatus'
        - $ref: '#/components/parameters/severity'
        - $ref: '#/components/parameters/fraudEventSource'
        - $ref: '#/components/parameters/eventType'
        - $ref: '#/components/parameters/ipAddress'
        - $ref: '#/components/parameters/search'
        - $ref: '#/components/parameters/perPage'
        - $ref: '#/components/parameters/page'
      responses:
        '200':
          description: Список antifraud-событий.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FraudEventListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
    post:
      tags: [FraudEvents]
      operationId: createFraudEvent
      summary: Создать antifraud-событие
      description: |
        Фиксирует подозрительное событие через `FraudEventService::record`.
        Если `source` не передан, API задает `source = api`. После успешной
        записи ставится webhook `fraud.event_created`. Требует API scope
        `fraud_events.create` и право `integrations.manage`.
      x-required-api-scope: fraud_events.create
      x-required-crm-permission: integrations.manage
      x-produced-webhook-event: fraud.event_created
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateFraudEventRequest'
      responses:
        '201':
          description: Antifraud-событие создано.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FraudEventResponse'
        '400':
          $ref: '#/components/responses/InvalidIdempotencyKey'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /fraud/events/{eventId}:
    get:
      tags: [FraudEvents]
      operationId: getFraudEvent
      summary: Получить antifraud-событие
      description: |
        Возвращает одно antifraud-событие текущего tenant/store scope.
        Требует API scope `fraud_events.view` и право `integrations.view`.
      x-required-api-scope: fraud_events.view
      x-required-crm-permission: integrations.view
      parameters:
        - $ref: '#/components/parameters/eventId'
      responses:
        '200':
          description: Детальная карточка antifraud-события.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FraudEventResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
    patch:
      tags: [FraudEvents]
      operationId: updateFraudEvent
      summary: Изменить antifraud-событие
      description: |
        Обновляет статус, важность, score и диагностические поля antifraud-события.
        В первом API-слое отдельный webhook обновления не отправляется. Требует
        API scope `fraud_events.update` и право `integrations.manage`.
      x-required-api-scope: fraud_events.update
      x-required-crm-permission: integrations.manage
      parameters:
        - $ref: '#/components/parameters/eventId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateFraudEventRequest'
      responses:
        '200':
          description: Antifraud-событие обновлено.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FraudEventResponse'
        '400':
          $ref: '#/components/responses/InvalidIdempotencyKey'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
webhooks:
  supplierClaimCreated:
    post:
      summary: Создана претензия поставщику
      description: |
        CRM отправляет exact snapshot претензии и nullable поставщика. Получатель обязан
        проверить HMAC до JSON parsing, дедуплицировать событие по `event_id` и применять
        данные только внутри UUID tenant/store. Metadata очищается от secrets и numeric
        internal IDs и не является источником CRM relations.
      parameters:
        - name: X-CRM-Webhook-Event
          in: header
          required: true
          schema: {type: string, const: supplier.claim_created}
        - name: X-CRM-Webhook-Id
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Delivery
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Timestamp
          in: header
          required: true
          schema: {type: string, pattern: '^[0-9]{10}$'}
        - name: X-CRM-Webhook-Signature
          in: header
          required: true
          schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/SupplierClaimCreatedWebhookEnvelope'}
      responses:
        '200': {description: Событие принято интеграцией.}
  supplierRatingUpdated:
    post:
      summary: Обновлен рейтинг поставщика
      description: |
        CRM отправляет exact snapshot поставщика, новой исторической оценки и изменения
        рейтинга. Получатель обязан проверить HMAC до JSON parsing, дедуплицировать событие
        по `event_id`, применять данные только внутри UUID tenant/store и не записывать
        комментарий, критерии или контакты поставщика в открытые логи.
      parameters:
        - name: X-CRM-Webhook-Event
          in: header
          required: true
          schema: {type: string, const: supplier.rating_updated}
        - name: X-CRM-Webhook-Id
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Delivery
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Timestamp
          in: header
          required: true
          schema: {type: string, pattern: '^[0-9]{10}$'}
        - name: X-CRM-Webhook-Signature
          in: header
          required: true
          schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/SupplierRatingUpdatedWebhookEnvelope'}
      responses:
        '200': {description: Событие принято интеграцией.}
  supplierReturnCreated:
    post:
      summary: Создан возврат поставщику
      description: |
        CRM отправляет strict snapshots претензии, поставщика и черновика складского возврата.
        Получатель обязан проверить HMAC до JSON parsing, дедуплицировать событие по
        `event_id`, сверить UUID tenant/store/supplier и не логировать номера документов,
        товары, количества, цены или комментарии.
      parameters:
        - name: X-CRM-Webhook-Event
          in: header
          required: true
          schema: {type: string, const: supplier.return_created}
        - name: X-CRM-Webhook-Id
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Delivery
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Timestamp
          in: header
          required: true
          schema: {type: string, pattern: '^[0-9]{10}$'}
        - name: X-CRM-Webhook-Signature
          in: header
          required: true
          schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/SupplierReturnCreatedWebhookEnvelope'}
      responses:
        '200': {description: Событие принято интеграцией.}
  fraudEventCreated:
    post:
      summary: Создано antifraud-событие
      description: |
        CRM отправляет strict snapshot обнаруженной подозрительной активности. Получатель
        обязан проверить HMAC до JSON parsing, дедуплицировать событие по `event_id`,
        применять его только внутри UUID tenant/store и не логировать IP, user-agent,
        fingerprint, request ID, description, payload или context.
      parameters:
        - name: X-CRM-Webhook-Event
          in: header
          required: true
          schema: {type: string, const: fraud.event_created}
        - name: X-CRM-Webhook-Id
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Delivery
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Timestamp
          in: header
          required: true
          schema: {type: string, pattern: '^[0-9]{10}$'}
        - name: X-CRM-Webhook-Signature
          in: header
          required: true
          schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/FraudEventCreatedWebhookEnvelope'}
      responses:
        '200': {description: Событие принято интеграцией.}
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API token
  parameters:
    supplierId:
      name: supplierId
      in: path
      required: true
      description: UUID общего поставщика компании или поставщика текущего магазина. Поставщик другого магазина возвращает 404.
      schema:
        type: string
        format: uuid
    claimId:
      name: claimId
      in: path
      required: true
      description: UUID претензии поставщика текущего магазина. Претензия другого магазина возвращает 404.
      schema:
        type: string
        format: uuid
    fileId:
      name: fileId
      in: path
      required: true
      description: UUID файла претензии текущего магазина. Файл претензии другого магазина возвращает 404.
      schema:
        type: string
        format: uuid
    eventId:
      name: eventId
      in: path
      required: true
      description: UUID antifraud-события текущего магазина. Событие другого магазина возвращает 404.
      schema:
        type: string
        format: uuid
    idempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: |
        Ключ идемпотентности для POST/PATCH запросов. Допустимые символы:
        `A-Z`, `a-z`, `0-9`, `.`, `_`, `:`, `-`; длина от 8 до 128 символов.
        Успешный ответ хранится 24 часа.
      schema:
        type: string
        minLength: 8
        maxLength: 128
        pattern: '^[A-Za-z0-9._:-]{8,128}$'
    supplierClaimStatus:
      name: status
      in: query
      required: false
      schema:
        $ref: '#/components/schemas/SupplierClaimStatus'
    supplierClaimType:
      name: type
      in: query
      required: false
      schema:
        $ref: '#/components/schemas/SupplierClaimType'
    fraudEventStatus:
      name: status
      in: query
      required: false
      schema:
        $ref: '#/components/schemas/FraudEventStatus'
    fraudEventSource:
      name: source
      in: query
      required: false
      schema:
        $ref: '#/components/schemas/FraudEventSource'
    severity:
      name: severity
      in: query
      required: false
      schema:
        $ref: '#/components/schemas/Severity'
    eventType:
      name: event_type
      in: query
      required: false
      schema:
        type: string
        maxLength: 64
    ipAddress:
      name: ip_address
      in: query
      required: false
      schema:
        type: string
        maxLength: 45
    mimeType:
      name: mime_type
      in: query
      required: false
      schema:
        type: string
        maxLength: 255
    search:
      name: search
      in: query
      required: false
      schema:
        type: string
        maxLength: 255
    perPage:
      name: per_page
      in: query
      required: false
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 25
    page:
      name: page
      in: query
      required: false
      schema:
        type: integer
        minimum: 1
        maximum: 100000
        default: 1
  headers:
    IdempotencyReplayed:
      description: 'Возвращается со значением `true`, если ответ взят из кеша идемпотентности.'
      schema:
        type: string
        enum: ['true']
    RateLimitLimit:
      description: Максимальное число запросов API-токена в минуту.
      schema:
        type: integer
    RateLimitRemaining:
      description: Остаток запросов в текущем минутном окне.
      schema:
        type: integer
    RetryAfter:
      description: Через сколько секунд можно повторить запрос после 429.
      schema:
        type: integer
  responses:
    BadRequest:
      description: Некорректный tenant/store контекст или параметры запроса.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    InvalidIdempotencyKey:
      description: 'Некорректный `Idempotency-Key`.'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            invalidIdempotencyKey:
              value:
                success: false
                error:
                  code: invalid_idempotency_key
                  message: Некорректный Idempotency-Key.
                request_id: 018f0c1a-1f44-731e-b7ff-55a4b8fafe01
    Unauthenticated:
      description: Bearer API-токен отсутствует, отозван или пользователь токена неактивен.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: Недостаточно API scope, CRM-права, tenant/store scope или IP не входит в allowlist токена.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            scopeDenied:
              value:
                success: false
                error:
                  code: api_token_scope_denied
                  message: API-токен не имеет нужного scope.
                  details:
                    required_scope: suppliers.view
                request_id: 018f0c1a-1f44-731e-b7ff-55a4b8fafe02
    NotFound:
      description: Ресурс не найден в текущем tenant/store scope.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    IdempotencyConflict:
      description: '`Idempotency-Key` уже используется или был использован с другим телом запроса.'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ValidationError:
      description: Ошибка валидации входных данных.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ValidationErrorResponse'
    TooManyRequests:
      description: Превышен лимит запросов API-токена.
      headers:
        Retry-After:
          $ref: '#/components/headers/RetryAfter'
        X-RateLimit-Limit:
          $ref: '#/components/headers/RateLimitLimit'
        X-RateLimit-Remaining:
          $ref: '#/components/headers/RateLimitRemaining'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  schemas:
    SupplierClaimStatus:
      type: string
      enum: [open, in_progress, resolved, rejected]
    SupplierClaimResolutionResult:
      type: string
      enum:
        - compensation
        - partial_compensation
        - replacement
        - credit
        - supplier_rejected
        - no_compensation
        - internal_loss
        - other
    SupplierClaimType:
      type: string
      enum: [quality, shortage, price, documents, other]
    FraudEventSource:
      type: string
      enum: [system, api, pos, storefront, admin]
    FraudEventStatus:
      type: string
      enum: [open, reviewing, confirmed, false_positive, blocked]
    Severity:
      type: string
      enum: [low, medium, high, critical]
    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
    Supplier:
      type: object
      required: [id, tenant_id, store_id, name, phone, email, is_active]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        name:
          type: string
        phone:
          type: [string, 'null']
        email:
          type: [string, 'null']
          format: email
        is_active:
          type: boolean
    SupplierClaim:
      type: object
      required:
        - id
        - tenant_id
        - store_id
        - supplier_id
        - purchase_order_id
        - stock_document_id
        - stock_movement_id
        - created_by_user_id
        - number
        - status
        - type
        - severity
        - title
        - description
        - claim_amount
        - resolution_result
        - resolution_amount
        - resolved_at
        - resolved_by_user_id
        - resolution_comment
        - currency_code
        - external_id
        - metadata
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        supplier_id:
          type: string
          format: uuid
        purchase_order_id:
          type: [string, 'null']
          format: uuid
          description: UUID закупочной заявки текущего магазина и поставщика.
        stock_document_id:
          type: [string, 'null']
          format: uuid
        stock_movement_id:
          type: [string, 'null']
          format: uuid
        created_by_user_id:
          type: [string, 'null']
          format: uuid
        number:
          type: [string, 'null']
        status:
          $ref: '#/components/schemas/SupplierClaimStatus'
        type:
          $ref: '#/components/schemas/SupplierClaimType'
        severity:
          $ref: '#/components/schemas/Severity'
        title:
          type: string
        description:
          type: [string, 'null']
        claim_amount:
          type: [string, 'null']
          pattern: '^\d+(\.\d{2})?$'
        resolution_result:
          oneOf:
            - $ref: '#/components/schemas/SupplierClaimResolutionResult'
            - type: 'null'
        resolution_amount:
          type: [string, 'null']
          pattern: '^\d+(\.\d{2})?$'
        resolved_at:
          type: [string, 'null']
          format: date-time
        resolved_by_user_id:
          type: [string, 'null']
          format: uuid
        resolution_comment:
          type: [string, 'null']
        currency_code:
          type: string
          minLength: 3
          maxLength: 3
        external_id:
          type: [string, 'null']
          description: Внешний идентификатор поставщика/интеграции. Не является CRM UUID и не используется как внутренний primary key.
        metadata:
          type: [object, 'null']
          additionalProperties: true
        created_at:
          type: [string, 'null']
          format: date-time
        updated_at:
          type: [string, 'null']
          format: date-time
    SupplierClaimFile:
      type: object
      required:
        - id
        - tenant_id
        - store_id
        - supplier_claim_id
        - user_id
        - file_name
        - file_mime_type
        - file_size
        - description
        - metadata
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        supplier_claim_id:
          type: string
          format: uuid
        user_id:
          type: [string, 'null']
          format: uuid
        file_name:
          type: [string, 'null']
        file_mime_type:
          type: [string, 'null']
        file_size:
          type: [integer, 'null']
          minimum: 0
        description:
          type: [string, 'null']
        metadata:
          type: [object, 'null']
          additionalProperties: true
        created_at:
          type: [string, 'null']
          format: date-time
        updated_at:
          type: [string, 'null']
          format: date-time
    SupplierRating:
      type: object
      required:
        - id
        - tenant_id
        - store_id
        - supplier_id
        - created_by_user_id
        - rating
        - previous_rating
        - criteria
        - comment
        - rated_at
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        supplier_id:
          type: string
          format: uuid
        created_by_user_id:
          type: [string, 'null']
          format: uuid
        rating:
          type: integer
          minimum: 1
          maximum: 5
        previous_rating:
          type: [integer, 'null']
          minimum: 1
          maximum: 5
        criteria:
          type: [object, 'null']
          additionalProperties: true
        comment:
          type: [string, 'null']
        rated_at:
          type: [string, 'null']
          format: date-time
        created_at:
          type: [string, 'null']
          format: date-time
        updated_at:
          type: [string, 'null']
          format: date-time
    FraudEvent:
      type: object
      required:
        - id
        - tenant_id
        - store_id
        - order_id
        - customer_id
        - user_id
        - source
        - event_type
        - severity
        - status
        - score
        - title
        - description
        - ip_address
        - user_agent
        - request_id
        - fingerprint
        - payload
        - context
        - occurred_at
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        order_id:
          type: [string, 'null']
          format: uuid
          description: UUID заказа текущего магазина. Заказ другого магазина возвращает 422 validation_failed.
        customer_id:
          type: [string, 'null']
          format: uuid
          description: UUID клиента текущего tenant. Клиентская база tenant-wide и не ограничивается primary_store_id.
        user_id:
          type: [string, 'null']
          format: uuid
          description: UUID активного сотрудника tenant с активным доступом к текущему магазину. Сотрудник другого магазина возвращает 422 validation_failed.
        source:
          $ref: '#/components/schemas/FraudEventSource'
        event_type:
          type: string
          maxLength: 64
        severity:
          $ref: '#/components/schemas/Severity'
        status:
          $ref: '#/components/schemas/FraudEventStatus'
        score:
          type: [integer, 'null']
          minimum: 0
          maximum: 1000
        title:
          type: string
        description:
          type: [string, 'null']
        ip_address:
          type: [string, 'null']
          maxLength: 45
        user_agent:
          type: [string, 'null']
          maxLength: 512
        request_id:
          type: [string, 'null']
          maxLength: 128
          description: Внешний идентификатор исходного запроса или трассировки antifraud-события. Не является CRM UUID ответа API.
        fingerprint:
          type: [string, 'null']
          maxLength: 128
        payload:
          type: [object, 'null']
          additionalProperties: true
          description: "Diagnostic payload события. При сохранении и выдаче API CRM маскирует секретные ключи как `***` и внутренние числовые `id`/`*_id` как `[internal-id-hidden]`; не используйте это поле для передачи plain secrets."
        context:
          type: [object, 'null']
          additionalProperties: true
          description: "Diagnostic context события. При сохранении и выдаче API CRM маскирует секретные ключи как `***` и внутренние числовые `id`/`*_id` как `[internal-id-hidden]`; `request_id` остается внешней строкой трассировки."
        occurred_at:
          type: [string, 'null']
          format: date-time
        created_at:
          type: [string, 'null']
          format: date-time
        updated_at:
          type: [string, 'null']
          format: date-time
    CreateSupplierClaimRequest:
      type: object
      required: [type, severity, title]
      properties:
        number:
          type: [string, 'null']
          maxLength: 64
        status:
          $ref: '#/components/schemas/SupplierClaimStatus'
        type:
          $ref: '#/components/schemas/SupplierClaimType'
        severity:
          $ref: '#/components/schemas/Severity'
        title:
          type: string
          maxLength: 255
        description:
          type: [string, 'null']
          maxLength: 5000
        claim_amount:
          type: [number, 'null']
          minimum: 0
        resolution_result:
          oneOf:
            - $ref: '#/components/schemas/SupplierClaimResolutionResult'
            - type: 'null'
          description: Используется при создании претензии сразу в статусе resolved или rejected.
        resolution_amount:
          type: [number, 'null']
          minimum: 0
          description: Сумма компенсации, возврата или внутренней потери по закрытой претензии.
        resolved_at:
          type: [string, 'null']
          format: date-time
          description: Дата решения. Если претензия создается закрытой и поле не передано, CRM подставит текущую дату.
        resolution_comment:
          type: [string, 'null']
          maxLength: 5000
        purchase_order_id:
          type: [string, 'null']
          format: uuid
          description: UUID закупочной заявки текущего магазина и выбранного поставщика.
        stock_document_id:
          type: [string, 'null']
          format: uuid
        stock_movement_id:
          type: [string, 'null']
          format: uuid
        external_id:
          type: [string, 'null']
          maxLength: 255
          description: Внешний идентификатор претензии в системе интегратора. Не является CRM UUID и не используется как внутренний primary key.
        metadata:
          type: [object, 'null']
          additionalProperties: true
    UploadSupplierClaimFileRequest:
      type: object
      required: [file]
      properties:
        file:
          type: string
          format: binary
          description: Файл до 50 МБ. Хранится в приватном S3.
        description:
          type: [string, 'null']
          maxLength: 1000
        metadata:
          type: [object, 'null']
          additionalProperties: true
    CreateSupplierRatingRequest:
      type: object
      required: [rating]
      properties:
        rating:
          type: integer
          minimum: 1
          maximum: 5
        criteria:
          type: [object, 'null']
          additionalProperties: true
        comment:
          type: [string, 'null']
          maxLength: 2000
        rated_at:
          type: [string, 'null']
          format: date-time
    CreateFraudEventRequest:
      type: object
      required: [event_type, title]
      properties:
        order_id:
          type: [string, 'null']
          format: uuid
          description: UUID заказа текущего магазина. Заказ другого магазина возвращает 422 validation_failed.
        customer_id:
          type: [string, 'null']
          format: uuid
          description: UUID клиента текущего tenant. Клиентская база tenant-wide и не ограничивается primary_store_id.
        user_id:
          type: [string, 'null']
          format: uuid
          description: UUID активного сотрудника tenant с активным доступом к текущему магазину. Сотрудник другого магазина возвращает 422 validation_failed.
        source:
          $ref: '#/components/schemas/FraudEventSource'
        event_type:
          type: string
          maxLength: 64
          example: suspicious_order_velocity
        severity:
          $ref: '#/components/schemas/Severity'
        status:
          $ref: '#/components/schemas/FraudEventStatus'
        score:
          type: [integer, 'null']
          minimum: 0
          maximum: 1000
        title:
          type: string
          maxLength: 255
        description:
          type: [string, 'null']
          maxLength: 5000
        ip_address:
          type: [string, 'null']
          maxLength: 45
        user_agent:
          type: [string, 'null']
          maxLength: 512
        request_id:
          type: [string, 'null']
          maxLength: 128
          description: Внешний идентификатор исходного запроса или трассировки antifraud-события. Не является CRM UUID ответа API.
        fingerprint:
          type: [string, 'null']
          maxLength: 128
        payload:
          type: [object, 'null']
          additionalProperties: true
          description: "Diagnostic payload. CRM сохраняет это поле в sanitized виде: секретные ключи маскируются как `***`, внутренние числовые `id`/`*_id` как `[internal-id-hidden]`."
        context:
          type: [object, 'null']
          additionalProperties: true
          description: "Diagnostic context. CRM сохраняет это поле в sanitized виде; не передавайте plain secrets, токены и приватные ключи."
        occurred_at:
          type: [string, 'null']
          format: date-time
    UpdateFraudEventRequest:
      type: object
      minProperties: 1
      properties:
        order_id:
          type: [string, 'null']
          format: uuid
        customer_id:
          type: [string, 'null']
          format: uuid
        user_id:
          type: [string, 'null']
          format: uuid
        source:
          $ref: '#/components/schemas/FraudEventSource'
        event_type:
          type: [string, 'null']
          maxLength: 64
        severity:
          $ref: '#/components/schemas/Severity'
        status:
          $ref: '#/components/schemas/FraudEventStatus'
        score:
          type: [integer, 'null']
          minimum: 0
          maximum: 1000
        title:
          type: [string, 'null']
          maxLength: 255
        description:
          type: [string, 'null']
          maxLength: 5000
        ip_address:
          type: [string, 'null']
          maxLength: 45
        user_agent:
          type: [string, 'null']
          maxLength: 512
        request_id:
          type: [string, 'null']
          maxLength: 128
          description: Внешний идентификатор исходного запроса или трассировки antifraud-события. Не является CRM UUID ответа API.
        fingerprint:
          type: [string, 'null']
          maxLength: 128
        payload:
          type: [object, 'null']
          additionalProperties: true
          description: "Diagnostic payload. При обновлении применяется тот же storage sanitizer, что и при создании antifraud-события."
        context:
          type: [object, 'null']
          additionalProperties: true
          description: "Diagnostic context. При обновлении применяется тот же storage sanitizer, что и при создании antifraud-события."
        occurred_at:
          type: [string, 'null']
          format: date-time
    SupplierClaimListResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [items, meta]
          properties:
            items:
              type: array
              items:
                $ref: '#/components/schemas/SupplierClaim'
            meta:
              $ref: '#/components/schemas/PaginationMeta'
        request_id:
          type: string
          format: uuid
    SupplierClaimResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/SupplierClaim'
        request_id:
          type: string
          format: uuid
    SupplierClaimFileListResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [items, meta]
          properties:
            items:
              type: array
              items:
                $ref: '#/components/schemas/SupplierClaimFile'
            meta:
              $ref: '#/components/schemas/PaginationMeta'
        request_id:
          type: string
          format: uuid
    SupplierClaimFileResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/SupplierClaimFile'
        request_id:
          type: string
          format: uuid
    SupplierClaimFileDownloadResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [file, download_url, expires_at]
          properties:
            file:
              $ref: '#/components/schemas/SupplierClaimFile'
            download_url:
              type: string
              format: uri
            expires_at:
              type: string
              format: date-time
        request_id:
          type: string
          format: uuid
    SupplierClaimFileDeleteResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [deleted, file]
          properties:
            deleted:
              type: boolean
              const: true
            file:
              $ref: '#/components/schemas/SupplierClaimFile'
        request_id:
          type: string
          format: uuid
    SupplierRatingHistoryResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [supplier, latest, items, meta]
          properties:
            supplier:
              $ref: '#/components/schemas/Supplier'
            latest:
              anyOf:
                - $ref: '#/components/schemas/SupplierRating'
                - type: 'null'
            items:
              type: array
              items:
                $ref: '#/components/schemas/SupplierRating'
            meta:
              $ref: '#/components/schemas/PaginationMeta'
        request_id:
          type: string
          format: uuid
    SupplierRatingResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/SupplierRating'
        request_id:
          type: string
          format: uuid
    FraudEventListResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          type: object
          required: [items, meta]
          properties:
            items:
              type: array
              items:
                $ref: '#/components/schemas/FraudEvent'
            meta:
              $ref: '#/components/schemas/PaginationMeta'
        request_id:
          type: string
          format: uuid
    FraudEventResponse:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/FraudEvent'
        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
    ValidationErrorResponse:
      type: object
      required: [success, error, request_id]
      properties:
        success:
          type: boolean
          const: false
        error:
          type: object
          required: [code, message, details]
          properties:
            code:
              type: string
              const: validation_failed
            message:
              type: string
            details:
              type: object
              additionalProperties:
                type: array
                items:
                  type: string
        request_id:
          type: string
          format: uuid
    SupplierClaimCreatedWebhookEnvelope:
      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: supplier.claim_created}
        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, 'null']
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/SupplierClaimCreatedWebhookData'}
    SupplierClaimCreatedWebhookData:
      type: object
      additionalProperties: false
      required: [supplier_claim, supplier]
      properties:
        supplier_claim: {$ref: '#/components/schemas/SupplierClaimWebhookClaim'}
        supplier:
          oneOf:
            - {$ref: '#/components/schemas/SupplierClaimWebhookSupplier'}
            - {type: 'null'}
    SupplierClaimWebhookClaim:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, supplier_id, purchase_order_id, stock_document_id, stock_movement_id, created_by_user_id, number, status, type, severity, title, description, claim_amount, resolution_result, resolution_amount, resolved_at, resolved_by_user_id, resolution_comment, currency_code, external_id, metadata, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        supplier_id:
          type: [string, 'null']
          format: uuid
        purchase_order_id:
          type: [string, 'null']
          format: uuid
        stock_document_id:
          type: [string, 'null']
          format: uuid
        stock_movement_id:
          type: [string, 'null']
          format: uuid
        created_by_user_id:
          type: [string, 'null']
          format: uuid
        number: {type: string, minLength: 1}
        status: {type: string, enum: [open, in_progress, resolved, rejected]}
        type: {type: string, enum: [quality, shortage, price, documents, other]}
        severity: {type: string, enum: [low, medium, high, critical]}
        title: {type: string, minLength: 1}
        description: {type: [string, 'null']}
        claim_amount: {type: [string, 'null'], pattern: '^[0-9]+\.[0-9]{2}$'}
        resolution_result: {type: [string, 'null'], enum: [compensation, partial_compensation, replacement, credit, supplier_rejected, no_compensation, internal_loss, other, null]}
        resolution_amount: {type: [string, 'null'], pattern: '^[0-9]+\.[0-9]{2}$'}
        resolved_at: {type: [string, 'null'], format: date-time}
        resolved_by_user_id:
          type: [string, 'null']
          format: uuid
        resolution_comment: {type: [string, 'null']}
        currency_code: {type: string, pattern: '^[A-Z]{3}$'}
        external_id:
          type: [string, 'null']
          description: Не является CRM UUID; внешний идентификатор поставщика или интеграции.
        metadata:
          type: [object, 'null']
          additionalProperties: true
          description: Очищенный extension object; numeric internal IDs и secrets не передаются.
        created_at: {type: [string, 'null'], format: date-time}
        updated_at: {type: [string, 'null'], format: date-time}
    SupplierClaimWebhookSupplier:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, name, phone, email, is_active, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        name: {type: string, minLength: 1}
        phone: {type: [string, 'null']}
        email: {type: [string, 'null'], format: email}
        is_active: {type: boolean}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    SupplierRatingUpdatedWebhookEnvelope:
      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: supplier.rating_updated}
        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, 'null']
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/SupplierRatingUpdatedWebhookData'}
    SupplierRatingUpdatedWebhookData:
      type: object
      additionalProperties: false
      required: [supplier, supplier_rating, rating_change]
      properties:
        supplier: {$ref: '#/components/schemas/SupplierRatingWebhookSupplier'}
        supplier_rating: {$ref: '#/components/schemas/SupplierRatingWebhookRating'}
        rating_change: {$ref: '#/components/schemas/SupplierRatingWebhookChange'}
    SupplierRatingWebhookSupplier:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, name, phone, email, is_active, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        name: {type: string, minLength: 1}
        phone: {type: [string, 'null']}
        email: {type: [string, 'null'], format: email}
        is_active: {type: boolean}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    SupplierRatingWebhookRating:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, supplier_id, created_by_user_id, rating, previous_rating, criteria, comment, rated_at, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        supplier_id:
          type: string
          format: uuid
        created_by_user_id:
          type: [string, 'null']
          format: uuid
        rating: {type: integer, minimum: 1, maximum: 5}
        previous_rating: {type: [integer, 'null'], minimum: 1, maximum: 5}
        criteria:
          type: [object, 'null']
          additionalProperties: true
          description: Расширяемый объект критериев оценки; массивы-списки и scalar запрещены.
        comment:
          type: [string, 'null']
          description: Может содержать внутренний комментарий и не должен попадать в открытые логи.
        rated_at: {type: string, format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    SupplierRatingWebhookChange:
      type: object
      additionalProperties: false
      required: [from_rating, to_rating]
      properties:
        from_rating: {type: [integer, 'null'], minimum: 1, maximum: 5}
        to_rating: {type: integer, minimum: 1, maximum: 5}
    SupplierReturnCreatedWebhookEnvelope:
      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: supplier.return_created}
        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, 'null']
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/SupplierReturnCreatedWebhookData'}
    SupplierReturnCreatedWebhookData:
      type: object
      additionalProperties: false
      required: [supplier_claim, supplier, stock_document]
      properties:
        supplier_claim: {$ref: '#/components/schemas/SupplierClaimWebhookClaim'}
        supplier: {$ref: '#/components/schemas/SupplierClaimWebhookSupplier'}
        stock_document: {$ref: '#/components/schemas/SupplierReturnWebhookDocument'}
    SupplierReturnWebhookDocument:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, supplier_id, user_id, number, type, status, source, supplier_name, supplier_claim_id, supplier_claim_number, purchase_order_id, purchase_order_number, original_stock_document_id, original_stock_document_number, occurred_at, posted_at, comment, created_at, updated_at, items]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        supplier_id:
          type: string
          format: uuid
        user_id:
          type: [string, 'null']
          format: uuid
        number: {type: string, minLength: 1}
        type: {type: string, const: writeoff}
        status: {type: string, const: draft}
        source: {type: string, const: supplier_claim_return}
        supplier_name: {type: [string, 'null']}
        supplier_claim_id:
          type: string
          format: uuid
        supplier_claim_number: {type: string, minLength: 1}
        purchase_order_id:
          type: [string, 'null']
          format: uuid
        purchase_order_number: {type: [string, 'null']}
        original_stock_document_id:
          type: string
          format: uuid
        original_stock_document_number: {type: string, minLength: 1}
        occurred_at: {type: string, format: date-time}
        posted_at: {type: [string, 'null'], format: date-time}
        comment: {type: [string, 'null']}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
        items:
          type: array
          minItems: 1
          items: {$ref: '#/components/schemas/SupplierReturnWebhookItem'}
          description: Original stock document item UUID должен быть уникален внутри документа.
    SupplierReturnWebhookItem:
      type: object
      additionalProperties: false
      required: [id, product_id, inventory_batch_id, supplier_id, product_name, sku, qty, purchase_price, reason, comment, original_stock_document_item_id, original_stock_movement_id, max_return_qty_snapshot, available_qty_snapshot, already_returned_qty_snapshot]
      properties:
        id:
          type: string
          format: uuid
        product_id:
          type: string
          format: uuid
        inventory_batch_id:
          type: [string, 'null']
          format: uuid
        supplier_id:
          type: string
          format: uuid
        product_name: {type: [string, 'null']}
        sku: {type: [string, 'null']}
        qty:
          type: string
          pattern: '^[0-9]+\.[0-9]{3}$'
          description: Положительное количество, не превышающее max_return_qty_snapshot.
        purchase_price: {type: [string, 'null'], pattern: '^[0-9]+\.[0-9]{2}$'}
        reason: {type: [string, 'null']}
        comment: {type: [string, 'null']}
        original_stock_document_item_id:
          type: string
          format: uuid
        original_stock_movement_id:
          type: [string, 'null']
          format: uuid
        max_return_qty_snapshot: {type: string, pattern: '^[0-9]+\.[0-9]{3}$'}
        available_qty_snapshot: {type: string, pattern: '^[0-9]+\.[0-9]{3}$'}
        already_returned_qty_snapshot: {type: string, pattern: '^[0-9]+\.[0-9]{3}$'}
    FraudEventCreatedWebhookEnvelope:
      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: fraud.event_created}
        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, 'null']
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/FraudEventCreatedWebhookData'}
    FraudEventCreatedWebhookData:
      type: object
      additionalProperties: false
      required: [fraud_event]
      properties:
        fraud_event: {$ref: '#/components/schemas/FraudEventWebhookEvent'}
    FraudEventWebhookEvent:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, order_id, customer_id, user_id, source, event_type, severity, status, score, title, description, ip_address, user_agent, request_id, fingerprint, payload, context, occurred_at, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: [string, 'null']
          format: uuid
        order_id:
          type: [string, 'null']
          format: uuid
        customer_id:
          type: [string, 'null']
          format: uuid
        user_id:
          type: [string, 'null']
          format: uuid
        source: {type: string, enum: [system, api, pos, storefront, admin]}
        event_type: {type: string, minLength: 1}
        severity: {type: string, enum: [low, medium, high, critical]}
        status: {type: string, enum: [open, reviewing, confirmed, false_positive, blocked]}
        score: {type: integer, minimum: 0, maximum: 1000}
        title: {type: string, minLength: 1, maxLength: 255}
        description: {type: [string, 'null']}
        ip_address:
          type: [string, 'null']
          description: Валидный IPv4 либо IPv6; null, если адрес не известен.
        user_agent: {type: [string, 'null']}
        request_id:
          type: [string, 'null']
          description: Внешний correlation identifier. Не является CRM UUID.
        fingerprint: {type: [string, 'null']}
        payload:
          type: [object, 'null']
          additionalProperties: true
          description: Sanitize-объект detector payload; secrets и numeric internal IDs не передаются.
        context:
          type: [object, 'null']
          additionalProperties: true
          description: Sanitize-объект контекста; scalar и array-list запрещены.
        occurred_at: {type: string, format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
