openapi: 3.1.0
info:
  title: API лабораторного портала
  version: "1.0"
  summary: Заказ анализов и получение результатов из МИС клиники.
  description: |
    JSON API портала лабораторий ТОО "Центр гематологии". Общие правила (подключение,
    ключи, статусы, вебхук, ограничения) – в [руководстве](./index.html); здесь –
    справочник по каждому запросу.

    Каждый запрос несет `Authorization: Bearer <ключ организации>` и
    `Accept: application/json`. Все данные видны только в пределах организации ключа:
    чужая заявка отвечает 404, как несуществующая.
  contact:
    name: Администратор портала ТОО "Центр гематологии"
    url: https://api.labz.kz
servers:
  - url: https://labz.kz/api/v1
    description: Боевой портал
  - url: https://sandbox.labz.kz/api/v1
    description: Песочница (заглушка вместо лабораторий)
security:
  - organizationKey: []
tags:
  - name: Справочники
    description: Услуги, пакеты и биоматериалы договора организации.
  - name: Заявки
    description: Создание заявки, чтение статусов и результатов, PDF.
  - name: Календарь
    description: Запись по времени для исследований с ограниченным числом мест.
  - name: Врачи
    description: Учетки врачей в веб-кабинете портала. Нужно право ключа `doctors:sync`.

paths:
  /services:
    get:
      tags: [Справочники]
      operationId: listServices
      summary: Услуги и пакеты договора
      description: |
        Сначала услуги, затем пакеты. Пакет отличает `is_package: true`: при заказе его
        код идет в `package_codes`, код услуги – в `service_codes`. Цены договорные.
        Справочник меняется – перечитывайте его регулярно (например, раз в сутки).
      responses:
        "200":
          description: Справочник
          content:
            application/json:
              schema:
                type: array
                items:
                  oneOf:
                    - $ref: "#/components/schemas/Service"
                    - $ref: "#/components/schemas/Package"
              examples:
                services:
                  $ref: "#/components/examples/ServiceList"
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "429": { $ref: "#/components/responses/TooManyRequests" }

  /biomaterials:
    get:
      tags: [Справочники]
      operationId: listBiomaterials
      summary: Биоматериалы
      description: Все активные биоматериалы. Биоматериалы разных лабораторий разные.
      parameters:
        - name: system
          in: query
          description: Только биоматериалы одной лаборатории.
          schema: { type: string, enum: [glab, histo] }
      responses:
        "200":
          description: Список
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Biomaterial" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/TooManyRequests" }

  /services/{id}/biomaterials:
    get:
      tags: [Справочники]
      operationId: listServiceBiomaterials
      summary: Биоматериалы услуги
      parameters:
        - name: id
          in: path
          required: true
          description: "`id` услуги из `GET /services`."
          schema: { type: integer }
      responses:
        "200":
          description: Список
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Biomaterial" }
        "404":
          description: Услуги нет или она не в договоре.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Message" }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /orders:
    post:
      tags: [Заявки]
      operationId: createOrder
      summary: Создать заявку
      description: |
        Портал создает заявку и сразу отправляет позиции в лаборатории (асинхронно:
        в ответе позиции обычно `pending`, через секунды – `sent`).

        Сохраните в МИС `id` и `code` заявки, `items[].id` и `items[].service.code`.

        **Повтор после таймаута.** Ключа идемпотентности нет: повторный запрос на того же
        пациента, услугу, биоматериал и время забора вернет 409 с номером уже созданной
        заявки – привяжитесь к ней.

        **Префикс штрихкода.** Если организации назначен `specimen_prefix`, каждый
        `items[].external_specimen_code` должен с него начинаться.

        **Клинические поля** – по `required_fields` услуги: `clinical_info` – в
        `items[].clinical_info` или общий `clinical_info`; `biomaterial_code` – в
        `items[]`; `sampled_at`, `birth_date`, `gender` – в свои поля; любой другой код –
        в `clinical_data`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreateOrder" }
            examples:
              full:
                summary: Две услуги, проба со штрихкодом, слот записи
                value:
                  patient:
                    iin: "900101300057"
                    last_name: Иванов
                    first_name: Иван
                    middle_name: Иванович
                    birth_date: "1990-01-01"
                    gender: male
                    phone: "+77011234567"
                  doctor:
                    iin: "850505400058"
                    last_name: Петрова
                    first_name: Анна
                    middle_name: Сергеевна
                  service_codes: [HC-0101, HC-0450]
                  urgency: routine
                  sampled_at: "2026-11-25T09:30:00+05:00"
                  clinical_data:
                    diagnosis: C92.0
                  items:
                    - service_code: HC-0101
                      biomaterial_code: BLOOD_EDTA
                      external_specimen_code: KL000123
                      clinical_info: Контроль терапии, 3-й курс
                    - service_code: HC-0450
                      biomaterial_code: BM_ASPIRATE
                      external_specimen_code: KL000124
                      clinical_info: Подозрение на рецидив
                      schedule: { date: "2026-11-27", window_id: 7 }
              minimal:
                summary: Одна услуга без дополнительных полей
                value:
                  patient: { iin: "900101300057", last_name: Иванов, first_name: Иван }
                  service_codes: [HC-0101]
      responses:
        "201":
          description: Заявка создана и отправлена.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
              examples:
                created:
                  $ref: "#/components/examples/OrderCreated"
        "409":
          description: |
            Дубль: у пациента уже есть незакрытая заявка на эту услугу с тем же временем
            забора (с точностью до минуты; разный биоматериал – не дубль). Новая заявка не
            создана – привяжитесь к `order_id` / `code`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DuplicateOrder" }
        "422":
          description: |
            Либо ошибки проверки полей (`message` + `errors`), либо `cannot_submit`:
            заявка создана черновиком, но не отправлена (недействительный ИИН, неизвестный
            пол пациента).
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ValidationError"
                  - $ref: "#/components/schemas/CannotSubmit"
              examples:
                validation:
                  summary: Ошибки полей
                  value:
                    message: Не указан биоматериал для услуги HC-0450 (and 1 more error)
                    errors:
                      items.1.biomaterial_code: [Не указан биоматериал для услуги HC-0450]
                      clinical_data.diagnosis: ["Не заполнено обязательное клиническое поле: Диагноз (МКБ-10)"]
                prefix:
                  summary: Штрихкод без префикса организации
                  value:
                    message: Штрихкод пробы AB000123 должен начинаться с префикса организации KL.
                    errors:
                      items.0.external_specimen_code: [Штрихкод пробы AB000123 должен начинаться с префикса организации KL.]
                cannotSubmit:
                  summary: Черновик не прошел проверку перед отправкой
                  value:
                    error: cannot_submit
                    message: "Невозможно отправить заказ: не указан пол пациента, и определить его по ИИН нельзя. Укажите пол в карточке пациента."
                    order_id: 124
                    code: 26-000124
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "429": { $ref: "#/components/responses/TooManyRequests" }

  /orders/{id}:
    get:
      tags: [Заявки]
      operationId: getOrder
      summary: Заявка, статусы и результаты
      description: |
        Решения о конкретном исследовании принимайте по `items[].status`: заявка
        `completed` может содержать отказанную позицию, а `submitted` – уже готовые.
        `revoked` – результат отозван, ранее полученное заключение недействительно.
      parameters:
        - $ref: "#/components/parameters/OrderId"
      responses:
        "200":
          description: Заявка
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
              examples:
                completed:
                  $ref: "#/components/examples/OrderCompleted"
        "404": { $ref: "#/components/responses/NotFound" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/TooManyRequests" }

  /orders/{id}/clinical-info:
    post:
      tags: [Заявки]
      operationId: replaceClinicalInfo
      summary: Заменить обоснование позиции
      description: |
        Пока лаборатория не приняла материал (позиция `pending`, `sent` или `error`,
        признак `clinical_editable`), обоснование можно заменить. Текст передается
        целиком. Доставка в лабораторию асинхронная: результат виден потом в
        `clinical_sync_error` / `clinical_synced_at`.
      parameters:
        - $ref: "#/components/parameters/OrderId"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [service_code, clinical_info]
              properties:
                service_code: { type: string, maxLength: 100, description: "Код услуги позиции." }
                clinical_info: { type: string, maxLength: 2000, description: "Новый текст целиком." }
            example:
              service_code: HC-0450
              clinical_info: "Подозрение на рецидив. МРД от 20.11: 0,8%"
      responses:
        "200":
          description: Принято
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ClinicalInfoResult" }
              example:
                order_id: 123
                items: [{ id: 9002, status: sent, delivery: push }]
        "404":
          description: Нет заявки (`message`) или в заявке нет такой услуги (`item_not_found`).
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/Message"
                  - $ref: "#/components/schemas/ApiError"
        "409":
          description: |
            `clinical_locked` – материал уже принят; `clinical_unsupported` – лаборатория
            не принимает правки уже переданной заявки.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApiError" }
              example:
                error: clinical_locked
                message: Заявка уже принята лабораторией, изменения запрещены.
                status: received
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /orders/{id}/referral:
    get:
      tags: [Заявки]
      operationId: getReferralPdf
      summary: Направление PDF
      description: |
        Бланк направления (как в кабинете врача): штрихкод заявки и штрихкоды проб
        `items[].id`. Если МИС не печатает свои штрихкоды, на пробирки клеят этот бланк.
      parameters:
        - $ref: "#/components/parameters/OrderId"
      responses:
        "200":
          description: PDF
          content:
            application/pdf:
              schema: { type: string, format: binary }
        "409":
          description: Заявка не отправлена (черновик).
        "404": { $ref: "#/components/responses/NotFound" }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /orders/items/{item}/lis-pdf:
    get:
      tags: [Заявки]
      operationId: getResultPdf
      summary: Бланк результата PDF
      description: |
        Бланк результата, выданного генетикой. Этот адрес портал сам подставляет в
        `items[].pdf_url` – строить его не нужно. У гистологии `pdf_url` – прямая ссылка
        на файл.
      parameters:
        - name: item
          in: path
          required: true
          description: "`items[].id`"
          schema: { type: integer }
      responses:
        "200":
          description: PDF
          content:
            application/pdf:
              schema: { type: string, format: binary }
        "403": { description: "Позиция другой организации." }
        "404": { description: "Бланка нет." }
        "502": { description: "Лаборатория не отдала файл – повторите позже." }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /calendar:
    get:
      tags: [Календарь]
      operationId: getCalendar
      summary: Дни с записью
      description: |
        `has_schedule: false` – у исследования нет записи по времени, слот в заявке не
        нужен. `true` – `days` от лаборатории.
      parameters:
        - $ref: "#/components/parameters/ServiceCode"
        - { name: from, in: query, required: true, schema: { type: string, format: date } }
        - { name: to, in: query, required: true, description: "Не раньше `from`., schema: { type: string, format: date }" }
      responses:
        "200":
          description: Дни
          content:
            application/json:
              schema:
                type: object
                required: [has_schedule, days]
                properties:
                  has_schedule: { type: boolean }
                  days:
                    type: array
                    items:
                      type: object
                      properties:
                        date: { type: string, format: date }
                        free_slots: { type: integer }
              example:
                has_schedule: true
                days: [{ date: "2026-11-27", free_slots: 3 }]
        "403": { description: "Услуги нет в договоре." }
        "404": { description: "Услуга не найдена." }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "502": { description: "Календарь лаборатории недоступен." }

  /calendar/slots:
    get:
      tags: [Календарь]
      operationId: getCalendarSlots
      summary: Окна записи на дату
      description: Выбранное окно передается в заявке как `items[].schedule = {date, window_id}`.
      parameters:
        - $ref: "#/components/parameters/ServiceCode"
        - { name: date, in: query, required: true, schema: { type: string, format: date } }
      responses:
        "200":
          description: Окна
          content:
            application/json:
              schema:
                type: object
                required: [has_schedule, windows]
                properties:
                  has_schedule: { type: boolean }
                  windows:
                    type: array
                    items:
                      type: object
                      description: Окно приема в формате лаборатории.
                      properties:
                        window_id: { type: integer }
                        free_slots: { type: integer }
                        capacity: { type: integer }
                      additionalProperties: true
              example:
                has_schedule: true
                windows: [{ window_id: 7, free_slots: 2, capacity: 5 }]
        "403": { description: "Услуги нет в договоре." }
        "404": { description: "Услуга не найдена." }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "502": { description: "Календарь лаборатории недоступен." }

  /sync/doctor:
    post:
      tags: [Врачи]
      operationId: upsertDoctor
      summary: Создать или обновить врача
      description: |
        Учетка врача в веб-кабинете портала, ключ – ИИН внутри организации. Для заявок
        через API не нужна: направившего врача передает поле `doctor` заявки.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [iin, last_name, first_name]
              properties:
                iin: { type: string, pattern: "^\\d{12}$" }
                last_name: { type: string, maxLength: 100 }
                first_name: { type: string, maxLength: 100 }
                middle_name: { type: [string, "null"], maxLength: 100 }
                email: { type: [string, "null"], format: email, maxLength: 255 }
                specialization: { type: [string, "null"], maxLength: 255 }
                password: { type: [string, "null"], minLength: 8, description: "Пароль входа в кабинет." }
                is_active: { type: [boolean, "null"], description: "`false` – отключить учетку." }
            example:
              iin: "850505400058"
              last_name: Петрова
              first_name: Анна
              password: s3cret-Pass
      responses:
        "200":
          description: Обновлен
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DoctorSyncResult" }
        "201":
          description: Создан
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DoctorSyncResult" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "401": { $ref: "#/components/responses/Unauthorized" }
    delete:
      tags: [Врачи]
      operationId: deactivateDoctor
      summary: Отключить врача
      description: Запись не удаляется, учетка отключается.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [iin]
              properties:
                iin: { type: string, pattern: "^\\d{12}$" }
      responses:
        "200":
          description: Отключен
          content:
            application/json:
              schema:
                type: object
                properties: { success: { type: boolean } }
        "404": { description: "Врач не найден." }
        "422": { description: "Неверный ИИН." }
        "403": { $ref: "#/components/responses/Forbidden" }
        "401": { $ref: "#/components/responses/Unauthorized" }

webhooks:
  orderResult:
    post:
      summary: Результат по заявке
      description: |
        Портал отправляет POST на `webhook_url` организации, когда заявка закрылась
        (`completed`, `revoked`, `rejected`) и когда любая позиция получила отзыв или
        отказ. Готовность отдельной позиции многопозиционной заявки и промежуточные
        статусы вебхук не вызывают.

        **Подпись:** `X-Portal-Signature` = hex(HMAC-SHA256(сырое тело, `webhook_secret`)).
        Проверяйте байты тела как пришли, не пересобранный JSON.

        **Повторы:** не 2xx – повтор через 30 и 60 с, всего до 3 попыток; таймаут 15 с.
        Событие может прийти дважды – обработка должна быть идемпотентной.

        **Рекомендация:** считайте вебхук сигналом и дочитывайте заявку через
        `GET /orders/{order_id}`. Решения – по `items[].status`, а не по `event`:
        при отказе одной позиции в заявке, где другие в работе, придет
        `event: order.completed` со `status: submitted`.
      security: []
      parameters:
        - name: X-Portal-Signature
          in: header
          required: true
          description: HMAC-SHA256 тела в hex.
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookPayload" }
            example:
              event: order.completed
              order_id: 123
              status: completed
              patient: { iin: "900101300057", fio: ИВАНОВ ИВАН ИВАНОВИЧ }
              items:
                - service_code: HC-0101
                  service_name: Общий анализ крови (ОАК)
                  external_system: null
                  status: completed
                  result_text: null
                  result_interpretation: null
                  pdf_url: https://labz.kz/api/v1/orders/items/9001/lis-pdf
                  result_values:
                    - { code: HGB, name: Гемоглобин, value: "98", unit: г/л, reference: 120-160, reference_min: 120, reference_max: 160, flag: L, is_abnormal: true }
                  resulted_at: "2026-11-26T11:02:00+05:00"
                  revoked_at: null
                  revoked_reason: null
                  revoked_by_name: null
              completed_at: "2026-11-26T11:02:05+05:00"
      responses:
        "200":
          description: Любой ответ 2xx – доставлено. Тело ответа портал не читает.

components:
  securitySchemes:
    organizationKey:
      type: http
      scheme: bearer
      description: API-ключ организации. Выдает администратор портала, показывается один раз.

  parameters:
    OrderId:
      name: id
      in: path
      required: true
      description: "`id` заявки из ответа 201 или 409."
      schema: { type: integer }
    ServiceCode:
      name: service_code
      in: query
      required: true
      description: Код услуги из справочника.
      schema: { type: string }

  responses:
    Unauthorized:
      description: |
        Нет ключа, ключ неизвестен или удален, организация отключена (`Unauthorized.`),
        истек срок ключа (`Token expired.`).
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Message" }
          examples:
            unauthorized: { value: { message: Unauthorized. } }
            expired: { value: { message: Token expired. } }
    Forbidden:
      description: Адрес не в белом списке ключа или у ключа нет нужного права.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Message" }
          examples:
            ip: { value: { message: IP address is not allowed for this token. } }
            ability: { value: { message: "This token has no 'doctors:sync' permission." } }
    TooManyRequests:
      description: Превышен лимит 600 запросов в минуту на ключ.
      headers:
        Retry-After: { description: "Через сколько секунд можно повторить., schema: { type: integer }" }
        X-RateLimit-Limit: { schema: { type: integer } }
        X-RateLimit-Remaining: { schema: { type: integer } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Message" }
          example: { message: Too Many Attempts. }
    NotFound:
      description: Нет такого объекта у организации ключа.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Message" }
    ValidationFailed:
      description: Ошибки проверки полей.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ValidationError" }

  schemas:
    Message:
      type: object
      required: [message]
      properties:
        message: { type: string }

    ApiError:
      type: object
      required: [error, message]
      properties:
        error: { type: string, description: "Машинный код ошибки." }
        message: { type: string }
        status: { type: string, description: "Статус позиции, если ошибка о позиции." }

    ValidationError:
      type: object
      required: [message, errors]
      properties:
        message: { type: string }
        errors:
          type: object
          description: Поле (через точку, `items.0.biomaterial_code`) -> список сообщений.
          additionalProperties:
            type: array
            items: { type: string }

    CannotSubmit:
      type: object
      required: [error, message, order_id, code]
      properties:
        error: { const: cannot_submit }
        message: { type: string }
        order_id: { type: integer, description: "Номер созданного черновика." }
        code: { type: [string, "null"] }

    DuplicateOrder:
      type: object
      required: [error, message, order_id, code, duplicates]
      properties:
        error: { const: duplicate_order }
        message: { type: string }
        order_id: { type: integer, description: "Существующая заявка – привяжитесь к ней." }
        code: { type: [string, "null"] }
        duplicates:
          type: array
          items:
            type: object
            properties:
              service_id: { type: integer }
              service_code: { type: [string, "null"] }
              service_name: { type: [string, "null"] }
              biomaterial_code: { type: [string, "null"] }
              biomaterial_name: { type: [string, "null"] }
              order_id: { type: integer }
              order_code: { type: [string, "null"] }
              order_status: { type: string }
              item_status: { type: string }
              sampled_at: { type: [string, "null"], description: "Формат `YYYY-MM-DD HH:MM:SS`." }
              created_at: { type: [string, "null"] }
              doctor_fio: { type: [string, "null"] }
              created_by_fio: { type: [string, "null"] }

    RequiredField:
      type: object
      description: Клиническое поле, которое лаборатория требует для исследования.
      properties:
        code: { type: string }
        label: { type: string }
        required: { type: boolean }

    Biomaterial:
      type: object
      additionalProperties: false
      required: [id, code, name, is_active, synced_at]
      properties:
        id: { type: integer }
        code: { type: string, description: "Идет в `items[].biomaterial_code`." }
        name: { type: string }
        system: { type: [string, "null"], description: "Лаборатория (`glab`, `histo`)." }
        is_active: { type: boolean }
        synced_at: { type: [string, "null"], format: date-time }

    Service:
      type: object
      additionalProperties: false
      required: [id, code, name, required_fields, has_schedule, price, urgency_options, biomaterials]
      properties:
        id: { type: integer }
        code: { type: string, description: "Код услуги портала – идет в `service_codes`." }
        lis_code: { type: [string, "null"], description: "Код в лаборатории." }
        name: { type: string }
        system: { type: [string, "null"], description: "В какую лабораторию уходит позиция." }
        required_fields:
          type: array
          items:
            oneOf:
              - $ref: "#/components/schemas/RequiredField"
              - { type: string }
        has_schedule: { type: boolean, description: "Есть запись по времени (см. Календарь)." }
        price: { type: [string, "null"], description: "Договорная цена планового исполнения, KZT, строкой (2500.00)." }
        price_urgent: { type: [string, "null"], description: "`null` – срочно по договору нельзя." }
        price_emergency: { type: [string, "null"], description: "`null` – экстренно по договору нельзя." }
        turnaround_days: { type: [integer, "null"] }
        turnaround_days_urgent: { type: [integer, "null"] }
        turnaround_days_emergency: { type: [integer, "null"] }
        urgency_options:
          type: array
          description: Допустимые значения `urgency` для этой позиции.
          items: { type: string, enum: [routine, urgent, emergency] }
        biomaterials:
          type: array
          items: { $ref: "#/components/schemas/Biomaterial" }
        synced_at: { type: [string, "null"], format: date-time }

    Package:
      type: object
      additionalProperties: false
      required: [id, code, name, is_package, required_fields, price, urgency_options, has_schedule, services, biomaterials]
      properties:
        id: { type: integer }
        code: { type: string, description: "Код пакета – идет в `package_codes`." }
        name: { type: string }
        is_package: { const: true }
        required_fields:
          type: array
          description: Объединение полей входящих услуг.
          items: { $ref: "#/components/schemas/RequiredField" }
        price: { type: [string, "null"] }
        price_urgent: { type: [string, "null"] }
        price_emergency: { type: [string, "null"] }
        turnaround_days: { type: [integer, "null"], description: "По самой долгой услуге." }
        turnaround_days_urgent: { type: [integer, "null"] }
        turnaround_days_emergency: { type: [integer, "null"] }
        urgency_options:
          type: array
          items: { type: string, enum: [routine, urgent, emergency] }
        has_schedule: { type: boolean }
        services:
          type: array
          description: Состав пакета.
          items:
            type: object
            properties:
              code: { type: string }
              lis_code: { type: [string, "null"] }
              name: { type: string }
        biomaterials:
          type: array
          maxItems: 0
          description: Всегда пусто – материал набирается по каждой услуге отдельно.
        synced_at: { type: [string, "null"], format: date-time }

    CreateOrder:
      type: object
      required: [patient]
      description: Нужен `service_codes` или `package_codes` (или оба).
      properties:
        patient:
          type: object
          required: [iin, last_name, first_name]
          description: Пациент ищется по ИИН внутри организации, новый заводится. Данные существующего не перезаписываются.
          properties:
            iin: { type: string, minLength: 12, maxLength: 12, description: "ИИН (проверяется контрольная цифра)." }
            last_name: { type: string, maxLength: 100 }
            first_name: { type: string, maxLength: 100 }
            middle_name: { type: [string, "null"], maxLength: 100 }
            birth_date: { type: [string, "null"], format: date, description: "Обязательна, если требует услуга." }
            gender: { type: [string, "null"], enum: [male, female, null], description: "Обязателен, если требует услуга; иначе берется из ИИН." }
            phone: { type: [string, "null"], maxLength: 20 }
        doctor:
          type: [object, "null"]
          description: Направивший врач. Учетка в портале ему не нужна – ФИО и ИИН уходят в лабораторию.
          required: [last_name]
          properties:
            iin: { type: [string, "null"], minLength: 12, maxLength: 12 }
            last_name: { type: string, maxLength: 100 }
            first_name: { type: [string, "null"], maxLength: 100 }
            middle_name: { type: [string, "null"], maxLength: 100 }
        service_codes:
          type: array
          minItems: 1
          description: Коды услуг; услуга активна и входит в договор.
          items: { type: string }
        package_codes:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string }
        urgency:
          type: [string, "null"]
          enum: [routine, urgent, emergency, null]
          description: Одна на заявку, разрешена договором для всех позиций. Пусто – плановая.
        sampled_at:
          type: [string, "null"]
          format: date-time
          description: Время забора, одно на заявку. Указывайте смещение (`+05:00`).
        clinical_info:
          type: [string, "null"]
          maxLength: 2000
          description: Общее обоснование. Лучше – `items[].clinical_info` на каждое исследование.
        clinical_data:
          type: [object, "null"]
          description: "Значения клинических полей `{\"код\": значение}` по `required_fields`."
          additionalProperties: true
        items:
          type: [array, "null"]
          description: Параметры позиций. Обязательны, если какой-то услуге нужен биоматериал.
          items:
            type: object
            required: [service_code]
            properties:
              service_code: { type: string, description: "Код услуги (или пакета – тогда `clinical_info` применяется ко всем услугам пакета)." }
              biomaterial_code: { type: [string, "null"], maxLength: 50 }
              external_specimen_code: { type: [string, "null"], maxLength: 64, description: "Штрихкод пробирки МИС, с префиксом организации." }
              clinical_info: { type: [string, "null"], maxLength: 2000, description: "Обоснование этого исследования." }
              schedule:
                type: [object, "null"]
                required: [date, window_id]
                properties:
                  date: { type: string, format: date }
                  window_id: { type: integer, description: "`window_id` из `GET /calendar/slots`." }

    ResultValue:
      type: object
      additionalProperties: false
      required: [code, name, value, unit, reference, reference_min, reference_max, flag, is_abnormal]
      properties:
        code: { type: [string, "null"], description: "Код показателя в лаборатории." }
        name: { type: [string, "null"] }
        value: { type: [string, "null"], description: "Число или текст (\"не обнаружено\")." }
        unit: { type: [string, "null"] }
        reference: { type: [string, "null"], description: "Референс текстом." }
        reference_min: { type: [number, "null"] }
        reference_max: { type: [number, "null"] }
        flag: { type: [string, "null"], description: "`H`, `L`, `HH`, `LL`, `A`, `N`." }
        is_abnormal: { type: boolean }

    ItemStatus:
      type: string
      description: |
        `pending` – в очереди; `sent` – передана в лабораторию; `received` – проба принята;
        `in_progress` – в работе; `completed` – результат готов; `rejected` – отказ
        лаборатории; `revoked` – результат отозван; `cancelled` – отменена; `error` –
        не удалось передать.
      enum: [pending, sent, received, in_progress, completed, rejected, revoked, cancelled, error]

    OrderStatus:
      type: string
      description: |
        `draft` – черновик; `submitted` – есть незакрытые позиции; `error` – есть позиция
        в ошибке; `completed` / `revoked` / `rejected` – все позиции закрыты (есть отзыв /
        есть отказ); `cancelled` – все отменены.
      enum: [draft, submitted, error, completed, revoked, rejected, cancelled]

    OrderItem:
      type: object
      additionalProperties: false
      required: [id, service, status, clinical_editable, result_values]
      properties:
        id: { type: integer, description: "Номер позиции = номер пробы на бланке направления." }
        service:
          type: object
          properties:
            id: { type: integer }
            name: { type: string }
            code: { type: string }
            required_fields: { type: array }
        order_package_id: { type: [integer, "null"], description: "Позиция из пакета." }
        external_system: { type: [string, "null"], description: "Лаборатория (`glab`, `histo`)." }
        lis_name: { type: [string, "null"] }
        external_order_id: { type: [string, "null"], description: "Номер в лаборатории." }
        clinical_info: { type: [string, "null"] }
        biomaterial_id: { type: [integer, "null"] }
        biomaterial_code: { type: [string, "null"] }
        biomaterial_name: { type: [string, "null"] }
        slot_date: { type: [string, "null"], format: date }
        slot_window_id: { type: [integer, "null"] }
        slot_label: { type: [string, "null"] }
        lgx_booking_id: { type: [string, integer, "null"], description: "Бронь подтверждена лабораторией." }
        status: { $ref: "#/components/schemas/ItemStatus" }
        clinical_editable: { type: boolean, description: "Обоснование еще можно заменить." }
        clinical_sync_error: { type: [string, "null"] }
        clinical_synced_at: { type: [string, "null"], format: date-time }
        result_text: { type: [string, "null"], description: "Заключение." }
        result_interpretation: { type: [string, "null"] }
        pdf_url: { type: [string, "null"], description: "Бланк результата." }
        our_pdf_url: { type: [string, "null"] }
        resulted_at: { type: [string, "null"], format: date-time }
        result_values:
          type: array
          items: { $ref: "#/components/schemas/ResultValue" }
        attempts: { type: [integer, "null"] }
        last_error: { type: [string, "null"] }
        reject_reason: { type: [string, "null"] }
        reject_comment: { type: [string, "null"] }
        revoked_at: { type: [string, "null"], format: date-time }
        revoked_reason: { type: [string, "null"] }
        revoked_by_name: { type: [string, "null"] }

    Order:
      type: object
      additionalProperties: false
      required: [id, code, status, patient, doctor, items]
      properties:
        id: { type: integer }
        code: { type: [string, "null"], description: "Номер заявки (`26-000123`), штрихкод направления." }
        status: { $ref: "#/components/schemas/OrderStatus" }
        urgency: { type: [string, "null"], enum: [routine, urgent, emergency, null] }
        service_name: { type: string, description: "Короткая подпись для списков." }
        clinical_info: { type: [string, "null"] }
        clinical_info_external: { type: boolean, description: "Заявка пришла из МИС." }
        required_data: { type: [object, array, "null"], description: "Присланные `clinical_data`." }
        sampled_at: { type: [string, "null"], format: date-time }
        created_at: { type: [string, "null"], format: date-time }
        patient:
          type: object
          properties:
            id: { type: [integer, "null"] }
            fio: { type: [string, "null"] }
            iin: { type: [string, "null"] }
            birth_date: { type: [string, "null"], format: date }
            age: { type: [integer, "null"] }
        doctor:
          type: object
          properties:
            id: { type: [integer, "null"] }
            fio: { type: string, description: "ФИО прописными; прочерк, если врач не передан." }
            iin: { type: [string, "null"] }
        items:
          type: array
          items: { $ref: "#/components/schemas/OrderItem" }
        packages:
          type: array
          description: Только в ответе 201 – снимок заказанных пакетов.
          items:
            type: object
            properties:
              id: { type: integer }
              service_package_id: { type: integer }
              code: { type: string }
              name: { type: string }
              price: { type: [string, "null"] }

    ClinicalInfoResult:
      type: object
      required: [order_id, items]
      properties:
        order_id: { type: integer }
        items:
          type: array
          items:
            type: object
            required: [id, status, delivery]
            properties:
              id: { type: integer }
              status: { $ref: "#/components/schemas/ItemStatus" }
              delivery:
                type: string
                enum: [unchanged, queued, push, resend, not_sent]
                description: |
                  `unchanged` – текст тот же; `queued` – уйдет с позицией; `push` – отправлен
                  в лабораторию; `resend` – позиция отправлена заново; `not_sent` – текст
                  сохранен, позиция не ушла (`message`).
              message: { type: string }

    DoctorSyncResult:
      type: object
      properties:
        success: { type: boolean }
        doctor_id: { type: integer }
        created: { type: boolean }

    WebhookPayload:
      type: object
      additionalProperties: false
      required: [event, order_id, status, patient, items, completed_at]
      properties:
        event:
          type: string
          enum: [order.completed, order.revoked, order.rejected]
          description: Из статуса заявки; решения принимайте по `items[].status`.
        order_id: { type: integer }
        status: { $ref: "#/components/schemas/OrderStatus" }
        patient:
          type: object
          additionalProperties: false
          properties:
            iin: { type: [string, "null"] }
            fio: { type: [string, "null"] }
        items:
          type: array
          items:
            type: object
            additionalProperties: false
            properties:
              service_code: { type: string }
              service_name: { type: string }
              external_system: { type: [string, "null"], description: "Сейчас всегда null – берите из GET заявки." }
              status: { $ref: "#/components/schemas/ItemStatus" }
              result_text: { type: [string, "null"] }
              result_interpretation: { type: [string, "null"] }
              pdf_url: { type: [string, "null"] }
              result_values:
                type: array
                items: { $ref: "#/components/schemas/ResultValue" }
              resulted_at: { type: [string, "null"], format: date-time }
              revoked_at: { type: [string, "null"], format: date-time }
              revoked_reason: { type: [string, "null"] }
              revoked_by_name: { type: [string, "null"] }
        completed_at: { type: string, format: date-time, description: "Время отправки вебхука." }

  examples:
    ServiceList:
      value:
        - id: 41
          code: HC-0101
          lis_code: CBC
          name: Общий анализ крови (ОАК)
          system: glab
          required_fields:
            - { code: biomaterial_code, label: Биоматериал, required: true }
            - { code: diagnosis, label: Диагноз (МКБ-10), required: true }
          has_schedule: false
          price: "2500.00"
          price_urgent: "4000.00"
          price_emergency: null
          turnaround_days: 1
          turnaround_days_urgent: 0
          turnaround_days_emergency: null
          urgency_options: [routine, urgent]
          biomaterials:
            - { id: 3, code: BLOOD_EDTA, name: Кровь с ЭДТА, system: glab, is_active: true, synced_at: "2026-11-20T03:00:00+05:00" }
          synced_at: "2026-11-20T03:00:00+05:00"
        - id: 5
          code: PKG-CLL
          name: Панель ХЛЛ
          is_package: true
          required_fields: [{ code: diagnosis, label: Диагноз (МКБ-10), required: true }]
          price: "85000.00"
          price_urgent: null
          price_emergency: null
          turnaround_days: 14
          turnaround_days_urgent: null
          turnaround_days_emergency: null
          urgency_options: [routine]
          has_schedule: false
          services:
            - { code: HC-0450, lis_code: FISH-CLL, name: FISH-панель ХЛЛ }
          biomaterials: []
          synced_at: "2026-11-01T10:00:00+05:00"
    OrderCreated:
      value:
        id: 123
        code: 26-000123
        status: submitted
        urgency: routine
        service_name: Общий анализ крови (ОАК)
        clinical_info: null
        clinical_info_external: true
        required_data: { diagnosis: C92.0 }
        sampled_at: "2026-11-25T09:30:00+05:00"
        created_at: "2026-11-25T09:31:02+05:00"
        patient: { id: 501, fio: ИВАНОВ ИВАН ИВАНОВИЧ, iin: "900101300057", birth_date: "1990-01-01", age: 36 }
        doctor: { id: null, fio: ПЕТРОВА АННА СЕРГЕЕВНА, iin: "850505400058" }
        items:
          - id: 9001
            service: { id: 41, name: Общий анализ крови (ОАК), code: HC-0101, required_fields: [] }
            order_package_id: null
            external_system: glab
            lis_name: Генетика
            external_order_id: null
            clinical_info: Контроль терапии, 3-й курс
            biomaterial_id: 3
            biomaterial_code: BLOOD_EDTA
            slot_date: null
            slot_window_id: null
            slot_label: null
            lgx_booking_id: null
            status: pending
            clinical_editable: true
            clinical_sync_error: null
            clinical_synced_at: null
            result_text: null
            result_interpretation: null
            pdf_url: null
            our_pdf_url: null
            resulted_at: null
            result_values: []
            attempts: 0
            last_error: null
            reject_reason: null
            reject_comment: null
            revoked_at: null
            revoked_reason: null
            revoked_by_name: null
        packages: []
    OrderCompleted:
      value:
        id: 123
        code: 26-000123
        status: completed
        urgency: routine
        service_name: Общий анализ крови (ОАК)
        clinical_info: null
        clinical_info_external: true
        required_data: { diagnosis: C92.0 }
        sampled_at: "2026-11-25T09:30:00+05:00"
        created_at: "2026-11-25T09:31:02+05:00"
        patient: { id: 501, fio: ИВАНОВ ИВАН ИВАНОВИЧ, iin: "900101300057", birth_date: "1990-01-01", age: 36 }
        doctor: { id: null, fio: ПЕТРОВА АННА СЕРГЕЕВНА, iin: "850505400058" }
        items:
          - id: 9001
            service: { id: 41, name: Общий анализ крови (ОАК), code: HC-0101, required_fields: [] }
            order_package_id: null
            external_system: glab
            lis_name: Генетика
            external_order_id: G-55120
            clinical_info: Контроль терапии, 3-й курс
            biomaterial_id: 3
            biomaterial_code: BLOOD_EDTA
            slot_date: null
            slot_window_id: null
            slot_label: null
            lgx_booking_id: null
            status: completed
            clinical_editable: false
            clinical_sync_error: null
            clinical_synced_at: null
            result_text: null
            result_interpretation: null
            pdf_url: https://labz.kz/api/v1/orders/items/9001/lis-pdf
            our_pdf_url: null
            resulted_at: "2026-11-26T11:02:00+05:00"
            result_values:
              - { code: HGB, name: Гемоглобин, value: "98", unit: г/л, reference: 120-160, reference_min: 120, reference_max: 160, flag: L, is_abnormal: true }
            attempts: 1
            last_error: null
            reject_reason: null
            reject_comment: null
            revoked_at: null
            revoked_reason: null
            revoked_by_name: null
