openapi: 3.1.0
info:
  title: BloomCore API - Customers
  version: 1.0.0
  description: |
    Поиск и создание клиентов в общей клиентской базе tenant-а. Запрос выполняется
    через поддомен конкретного магазина, а права владельца API-токена проверяются
    именно для этого магазина. Все CRM `id` и `*_id` являются UUID-строками.
    Ответы содержат персональные данные: не записывайте полные request/response body
    в общие логи, используйте минимальные scopes, allowed IP и ограниченный срок токена.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: florio
        description: Поддомен магазина, определяющий контекст прав и магазин регистрации.
security:
  - bearerAuth: []
paths:
  /customers/by-phone:
    get:
      operationId: findCustomersByPhone
      summary: Найти клиента по телефону
      description: |
        Выполняет точный tenant-wide поиск по нормализованному основному телефону,
        дополнительным phone-контактам и WhatsApp-контактам. Клиенты другого tenant-а
        никогда не возвращаются. Endpoint не раскрывает заказы, оплаты, адреса,
        задачи, комментарий, metadata или внутренние bigint ID.
      parameters:
        - name: phone
          in: query
          required: true
          description: Телефон; форматирование игнорируется, после нормализации требуется 7-15 цифр.
          schema:
            type: string
            minLength: 7
            maxLength: 64
          example: '+7 (999) 000-11-22'
      responses:
        '200':
          description: Результат точного поиска, включая признак неоднозначности.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CustomerLookupSuccess'
              example:
                success: true
                data:
                  items:
                    - id: 019f7f04-6e5d-7201-9356-54b557480e43
                      primary_store_id: 019f7f04-4c90-7ec0-b7cf-ab95efbe32f2
                      name: Анна Петрова
                      first_name: Анна
                      last_name: Петрова
                      phone: '+79990001122'
                      email: anna@example.test
                      birth_date: '1992-04-15'
                      gender: female
                      status: active
                      is_blacklisted: false
                      bonus_balance: '1250.00'
                      sync_version: 7
                      sync_updated_at: '2026-07-26T12:30:00Z'
                      created_at: '2026-05-02T10:00:00Z'
                      updated_at: '2026-07-26T12:30:00Z'
                  count: 1
                  ambiguous: false
                  truncated: false
                request_id: 019f7f05-4f10-71e8-82d2-726d738ed4dc
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /customers:
    post:
      operationId: createCustomer
      summary: Создать клиента
      description: |
        Создает активный профиль в tenant-е и назначает магазин текущего поддомена
        магазином регистрации. Требуются scope и CRM-право `customers.create`, а также
        `Idempotency-Key`. UUIDv7 генерируется сервером. Поля tenant, магазин, статус,
        blacklist, бонусный баланс и внутренние ID передавать нельзя.

        При совпадении нормализованного телефона или email возвращается
        `409 possible_duplicate` с безопасным списком canonical UUID. Принудительное
        создание отдельного профиля требует одновременно scope и CRM-право
        `customers.create_duplicate`, `force_duplicate=true` и причину длиной 5-512 символов.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateCustomerRequest'
            example:
              name: Анна Петрова
              phone: '+79990001122'
              email: anna@example.test
              birth_date: '1992-04-15'
              gender: female
              comment: Клиент зарегистрирован внешней витриной
      responses:
        '201':
          description: Клиент создан. Точный повтор возвращает тот же ответ с `Idempotency-Replayed: true`.
          headers:
            Idempotency-Replayed:
              description: `true`, если ответ безопасно воспроизведен из idempotency cache.
              schema: {type: string, enum: ['true']}
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CustomerProfileSuccess'
        '400':
          description: Отсутствует или некорректен `Idempotency-Key`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: Возможный дубль либо конфликт повторного Idempotency-Key.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/PossibleDuplicateError'
                  - $ref: '#/components/schemas/ErrorEnvelope'
        '422':
          $ref: '#/components/responses/ValidationFailed'
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: BloomCore API token
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        Уникальный ключ операции. Точный повтор с тем же payload воспроизводит ответ,
        а другой payload с тем же ключом возвращает 409.
      schema:
        type: string
        minLength: 8
        maxLength: 128
        pattern: '^[A-Za-z0-9._:-]+$'
      example: customer-create-site-2026-0001
  responses:
    Unauthorized:
      description: API-токен отсутствует, истек или отозван.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    Forbidden:
      description: Не совпал tenant/store, scope токена или CRM-право пользователя.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    ValidationFailed:
      description: Ошибка строгой валидации запроса.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
  schemas:
    CustomerProfile:
      type: object
      additionalProperties: false
      required:
        - id
        - primary_store_id
        - name
        - first_name
        - last_name
        - phone
        - email
        - birth_date
        - gender
        - status
        - is_blacklisted
        - bonus_balance
        - sync_version
        - sync_updated_at
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
        primary_store_id:
          type: [string, 'null']
          format: uuid
        name: {type: string, minLength: 1}
        first_name: {type: [string, 'null']}
        last_name: {type: [string, 'null']}
        phone: {type: [string, 'null']}
        email: {type: [string, 'null'], format: email}
        birth_date: {type: [string, 'null'], format: date}
        gender: {type: [string, 'null'], enum: [female, male, null]}
        status: {type: string, enum: [active, archived]}
        is_blacklisted: {type: boolean}
        bonus_balance: {type: string, pattern: '^-?[0-9]+\.[0-9]{2}$'}
        sync_version: {type: integer, minimum: 1}
        sync_updated_at: {type: string, format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    CustomerLookupData:
      type: object
      additionalProperties: false
      required: [items, count, ambiguous, truncated]
      properties:
        items:
          type: array
          maxItems: 20
          items: {$ref: '#/components/schemas/CustomerProfile'}
        count: {type: integer, minimum: 0}
        ambiguous: {type: boolean}
        truncated: {type: boolean}
    CreateCustomerRequest:
      type: object
      additionalProperties: false
      required: [name]
      anyOf:
        - required: [phone]
        - required: [email]
      properties:
        name: {type: string, minLength: 1, maxLength: 255}
        phone: {type: [string, 'null'], maxLength: 64}
        email: {type: [string, 'null'], format: email, maxLength: 255}
        birth_date: {type: [string, 'null'], format: date}
        gender: {type: [string, 'null'], enum: [female, male, unknown, null]}
        comment: {type: [string, 'null'], maxLength: 2000}
        force_duplicate: {type: boolean, default: false}
        duplicate_reason: {type: [string, 'null'], minLength: 5, maxLength: 512}
    DuplicateCandidate:
      type: object
      additionalProperties: false
      required: [id, primary_store_id, name, status, matched_by]
      properties:
        id:
          type: string
          format: uuid
        primary_store_id:
          type: [string, 'null']
          format: uuid
        name: {type: string}
        status: {type: string, enum: [active, archived]}
        matched_by:
          type: array
          uniqueItems: true
          items: {type: string, enum: [phone, email]}
    PossibleDuplicateDetails:
      type: object
      additionalProperties: false
      required: [candidate_count, matched_identity_types, candidates]
      properties:
        candidate_count: {type: integer, minimum: 1}
        matched_identity_types:
          type: array
          uniqueItems: true
          items: {type: string, enum: [phone, email]}
        candidates:
          type: array
          maxItems: 10
          items: {$ref: '#/components/schemas/DuplicateCandidate'}
    ErrorObject:
      type: object
      additionalProperties: true
      required: [code, message]
      properties:
        code: {type: string}
        message: {type: string}
        details: {type: object}
    ErrorEnvelope:
      type: object
      additionalProperties: false
      required: [success, error, request_id]
      properties:
        success: {type: boolean, const: false}
        error: {$ref: '#/components/schemas/ErrorObject'}
        request_id:
          type: string
          format: uuid
    PossibleDuplicateErrorObject:
      type: object
      additionalProperties: false
      required: [code, message, details]
      properties:
        code: {type: string, const: possible_duplicate}
        message: {type: string}
        details: {$ref: '#/components/schemas/PossibleDuplicateDetails'}
    PossibleDuplicateError:
      type: object
      additionalProperties: false
      required: [success, error, request_id]
      properties:
        success: {type: boolean, const: false}
        error: {$ref: '#/components/schemas/PossibleDuplicateErrorObject'}
        request_id:
          type: string
          format: uuid
    CustomerLookupSuccess:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: {type: boolean, const: true}
        data: {$ref: '#/components/schemas/CustomerLookupData'}
        request_id:
          type: string
          format: uuid
    CustomerProfileSuccess:
      type: object
      additionalProperties: false
      required: [success, data, request_id]
      properties:
        success: {type: boolean, const: true}
        data: {$ref: '#/components/schemas/CustomerProfile'}
        request_id:
          type: string
          format: uuid
