openapi: 3.1.0
info:
  title: BloomCore Document Repository API
  version: 1.1.0
  description: |
    UUID-only API чтения общего хранилища документов.
    Контракт работает в контексте магазина из tenant-поддомена и требует
    API scope documents.view для метаданных либо documents.download для файла,
    соответствующие CRM-права и активную подписку API. Готовая текущая версия
    выдается только потоковым same-origin ответом. S3 URL, S3 locators,
    исходные имена, hashes, scanner diagnostics, ответственные сотрудники и
    внутренние bigint ID не публикуются.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: florio
security:
  - bearerAuth: []
paths:
  /documents:
    get:
      operationId: listDocuments
      summary: Получить активные документы текущего магазина
      description: |
        Возвращает только активные, не удаленные документы, явно назначенные
        магазину текущего поддомена. Company-wide токен не расширяет один
        запрос на другие магазины. Неизвестные query-параметры отклоняются.
      parameters:
        - $ref: '#/components/parameters/Search'
        - $ref: '#/components/parameters/Type'
        - $ref: '#/components/parameters/FolderId'
        - $ref: '#/components/parameters/IssuedFrom'
        - $ref: '#/components/parameters/IssuedTo'
        - $ref: '#/components/parameters/ExpiresFrom'
        - $ref: '#/components/parameters/ExpiresTo'
        - $ref: '#/components/parameters/UpdatedSince'
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/PerPage'
      responses:
        '200':
          description: Страница безопасных метаданных документов.
          headers:
            Cache-Control:
              schema:
                type: string
              example: max-age=0, no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentListEnvelope'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /documents/{documentId}:
    get:
      operationId: getDocument
      summary: Получить карточку активного документа
      description: |
        Возвращает карточку только при exact tenant/store binding.
        UUID документа другого магазина, tenant-а, архива или soft-delete
        получает нейтральный 404 без раскрытия существования записи.
      parameters:
        - name: documentId
          in: path
          required: true
          schema:
            type: string
            format: uuid
          example: 019fb400-8f1e-72c4-a601-4f0e6a993a31
      responses:
        '200':
          description: Безопасная карточка документа.
          headers:
            Cache-Control:
              schema:
                type: string
              example: max-age=0, no-store, private
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentDetailEnvelope'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /documents/{documentId}/download:
    get:
      operationId: downloadDocument
      summary: Скачать готовую текущую версию документа
      description: |
        Потоково отдает только authoritative current version со статусом ready.
        Требует API scope documents.download, а владелец токена должен иметь
        CRM-права documents.view и documents.download в exact магазине
        поддомена. Redirect и S3/presigned URL не используются. Имя вложения
        синтетическое и состоит только из публичных UUID и расширения,
        определенного по проверенному MIME type.
      parameters:
        - name: documentId
          in: path
          required: true
          schema:
            type: string
            format: uuid
          example: 019fb400-8f1e-72c4-a601-4f0e6a993a31
      responses:
        '200':
          description: Поток содержимого готовой текущей версии.
          headers:
            Cache-Control:
              schema:
                type: string
              example: max-age=0, no-store, private
            Content-Disposition:
              schema:
                type: string
              description: Attachment с синтетическим UUID-only именем.
            X-Content-Type-Options:
              schema:
                type: string
              example: nosniff
            Cross-Origin-Resource-Policy:
              schema:
                type: string
              example: same-origin
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '503':
          description: Authoritative private object временно недоступен.
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: Sanctum
  parameters:
    Search:
      name: search
      in: query
      schema:
        type: string
        maxLength: 255
      description: Поиск по нормализованному названию.
    Type:
      name: type
      in: query
      schema:
        $ref: '#/components/schemas/DocumentType'
    FolderId:
      name: folder_id
      in: query
      schema:
        type: string
        format: uuid
      example: 019fb400-91ab-762d-91db-9cd8ce221972
    IssuedFrom:
      name: issued_from
      in: query
      schema:
        type: string
        format: date
    IssuedTo:
      name: issued_to
      in: query
      schema:
        type: string
        format: date
    ExpiresFrom:
      name: expires_from
      in: query
      schema:
        type: string
        format: date
    ExpiresTo:
      name: expires_to
      in: query
      schema:
        type: string
        format: date
    UpdatedSince:
      name: updated_since
      in: query
      schema:
        type: string
        format: date-time
    Page:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100000
    PerPage:
      name: per_page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 25
  schemas:
    DocumentType:
      type: string
      enum:
        - contract
        - invoice
        - act
        - waybill
        - instruction
        - legal
        - other
    ExpiryState:
      type: object
      additionalProperties: false
      required:
        - state
        - days_remaining
      properties:
        state:
          type: string
          enum:
            - no_expiry
            - active
            - expires_today
            - expired
        days_remaining:
          type:
            - integer
            - 'null'
          description: Положительное значение до срока, 0 сегодня, отрицательное после срока.
    DocumentFolder:
      type: object
      additionalProperties: false
      required:
        - id
        - name
        - color
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
          maxLength: 255
        color:
          type: string
          pattern: '^#[A-F0-9]{6}$'
    CurrentDocumentFile:
      type: object
      additionalProperties: false
      required:
        - id
        - version_number
        - availability
        - mime_type
        - size_bytes
        - ready_at
      properties:
        id:
          type: string
          format: uuid
        version_number:
          type: integer
          minimum: 1
        availability:
          type: string
          enum:
            - ready
            - processing
            - unavailable
        mime_type:
          type:
            - string
            - 'null'
          maxLength: 255
        size_bytes:
          type:
            - integer
            - 'null'
          minimum: 0
        ready_at:
          type:
            - string
            - 'null'
          format: date-time
    DocumentSummary:
      type: object
      additionalProperties: false
      required:
        - id
        - store_id
        - type
        - title
        - issued_on
        - expires_on
        - expiry
        - folder
        - current_file
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        type:
          $ref: '#/components/schemas/DocumentType'
        title:
          type: string
          maxLength: 255
        issued_on:
          type:
            - string
            - 'null'
          format: date
        expires_on:
          type:
            - string
            - 'null'
          format: date
        expiry:
          $ref: '#/components/schemas/ExpiryState'
        folder:
          oneOf:
            - $ref: '#/components/schemas/DocumentFolder'
            - type: 'null'
        current_file:
          oneOf:
            - $ref: '#/components/schemas/CurrentDocumentFile'
            - type: 'null'
        created_at:
          type:
            - string
            - 'null'
          format: date-time
        updated_at:
          type:
            - string
            - 'null'
          format: date-time
    DocumentDetail:
      allOf:
        - $ref: '#/components/schemas/DocumentSummary'
        - type: object
          additionalProperties: false
          required:
            - description
          properties:
            description:
              type:
                - string
                - 'null'
              maxLength: 65535
    PaginationMeta:
      type: object
      additionalProperties: false
      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
    DocumentList:
      type: object
      additionalProperties: false
      required:
        - items
        - meta
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/DocumentSummary'
        meta:
          $ref: '#/components/schemas/PaginationMeta'
    DocumentListEnvelope:
      type: object
      additionalProperties: false
      required:
        - success
        - data
        - request_id
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/DocumentList'
        request_id:
          type: string
          format: uuid
    DocumentDetailEnvelope:
      type: object
      additionalProperties: false
      required:
        - success
        - data
        - request_id
      properties:
        success:
          type: boolean
          const: true
        data:
          $ref: '#/components/schemas/DocumentDetail'
        request_id:
          type: string
          format: uuid
    ErrorEnvelope:
      type: object
      additionalProperties: true
      required:
        - success
        - error
        - request_id
      properties:
        success:
          type: boolean
          const: false
        error:
          type: object
        request_id:
          type: string
          format: uuid
  responses:
    Unauthorized:
      description: Bearer API-токен отсутствует или недействителен.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    Forbidden:
      description: Нет требуемого documents.view/documents.download scope, CRM-права или подписки API.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    NotFound:
      description: Документ недоступен в текущем tenant/store scope.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    ValidationFailed:
      description: Фильтры не прошли closed-contract validation.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
