openapi: 3.1.1
info:
  title: API личного кабинета Parser API
  version: 1.0.0
  description: |-
    По поручению клиента агент может проверить остаток запросов, подобрать тариф, рассчитать продление, выставить счёт и получить ссылку на оплату по СБП или PDF счёта. Расчёт стоимости доступен до выставления. Учтённая оплата и её применение видны в карточке счёта.

    Передавайте действующий ключ сервисов в заголовке `Authorization: Bearer <ключ>` по HTTPS на домен своего кабинета. Нужны e-mail в профиле и включённый доступ к API. Если проверка IP для API включена и список разрешённых адресов заполнен, в него должен входить исходящий IP интеграции. Ключ, e-mail и настройки доступа владелец меняет на сайте.

    Примеры Shell / cURL выполняются в вашей среде. Задайте LK_KEY через хранилище секретов. Возьмите SERVICE_ID, SUBSCRIPTION_ID и INVOICE_ID из ответов своего кабинета. Для расчёта и выставления подготовьте invoice.json по примеру тела и используйте один файл для обеих команд. Создайте INVOICE_KEY (UUID) до первого выставления и сохраните его для повтора. Для реквизитов подготовьте requisites.json с полями inn, bik и account.

    Даты без времени относятся к календарю ЛК (Europe/Moscow), даты со временем включают смещение. Деньги выражаются в рублях. Неописанные параметры URL, тело у операций без requestBody и ключ в URL отклоняются с 400. В JSON-запросах неизвестные поля отклоняются с 422. Ошибки возвращаются как application/json. Ответы с клиентскими данными и PDF передаются с Cache-Control: no-store. Привязка бренда происходит только на сайте. Если бренд ещё не привязан, API отвечает 401. Карточка счёта читает сохранённый статус. Для ожидающего счёта физлица она также возвращает действующие платёжные данные и запрашивает их при отсутствии или истечении платежа. Запрос PDF ожидающего счёта без номера может повторить его выпуск по правилам сайта.

    Idempotency-Key обязателен только для POST /invoices. В течение 24 часов после принятия команды повтор того же клиента с тем же UUID и полями тела (в любом порядке ключей объекта) возвращает тот же локальный счёт. После этого окна проверьте свои счета перед новой командой. При других данных с тем же UUID возвращается 409 idempotency_conflict, пока команда выполняется — 409 operation_in_progress с Retry-After. Отказ в доступе и ошибки данных до принятия команды не занимают UUID.
servers:
- url: https://lk.parser-api.com/api/client/v1
security:
- ClientKey: []
tags:
- name: Профиль
- name: Каталог и тарифы
- name: Подписки
- name: Счета
- name: Оплата и документы
paths:
  /profile:
    get:
      tags:
      - Профиль
      operationId: getProfile
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/profile"
      summary: Прочитать свой профиль
      description: Тип плательщика, привязанная организация, уведомления, автосчёт и доступные для чтения настройки IP и
        адресов. Полный ключ в ответ не входит.
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Profile'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/TooMany'
    patch:
      tags:
      - Профиль
      operationId: updateProfile
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request PATCH \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            --header 'Content-Type: application/json' \
            --data '{"days_notify":12}' \
            "https://lk.parser-api.com/api/client/v1/profile"
      summary: Изменить тип плательщика и настройки
      description: Передаются только изменяемые поля. Пропущенные настройки сохраняются. Проверяется итоговое сочетание
        значений. При переходе на fiz автосчёт выключается, параметры дня и срока сохраняются. Неизвестное или защищённое
        поле отклоняет весь запрос. При итоговом fiz значение auto_invoice всегда false. При изменении только notify_expiring
        и/или days_notify сохраняются правила настройки автосчёта первой оплатой. При первой привязке организации ЛК может
        включить автосчёт. Чтобы отключить его, передайте auto_invoice=false после привязки.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProfilePatch'
            examples:
              change_payer:
                value:
                  person_type: org
              change_notice:
                value:
                  days_notify: 10
                  notify_expiring: true
      responses:
        '200':
          description: Сохранённый профиль.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Profile'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '415':
          $ref: '#/components/responses/UnsupportedMedia'
        '422':
          $ref: '#/components/responses/Validation'
        '429':
          $ref: '#/components/responses/TooMany'
  /profile/requisites:
    put:
      tags:
      - Профиль
      operationId: setRequisites
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request PUT \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            --header 'Content-Type: application/json' \
            --data-binary @requisites.json \
            "https://lk.parser-api.com/api/client/v1/profile/requisites"
      summary: Привязать организацию или обновить реквизиты
      description: При успехе тип плательщика становится org. При частичном успехе возвращается сохранённая организация
        и bank_account_status=retry_required. Повтор с теми же реквизитами завершает привязку без дубля. Если привязать
        организацию не удалось из-за внешнего сбоя, возвращается 503. При первой привязке ЛК может включить автосчёт по
        правилам веб-профиля; итоговые настройки читаются через GET /profile.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RequisitesInput'
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RequisitesResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '415':
          $ref: '#/components/responses/UnsupportedMedia'
        '422':
          $ref: '#/components/responses/Validation'
        '429':
          $ref: '#/components/responses/TooMany'
        '503':
          $ref: '#/components/responses/Unavailable'
  /services:
    get:
      tags:
      - Каталог и тарифы
      operationId: listServices
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/services"
      summary: Получить сервисы, цены и условия теста
      description: Для каждого доступного сервиса purchase_tariffs содержит применимые платные тарифы клиента с источником
        цены. trial_limits показывает дневной и месячный лимиты предлагаемого тестового тарифа до активации, null означает
        отсутствие тестового тарифа. can_request_trial показывает, доступна ли активация этому клиенту сейчас. Данные
        берутся из тех же правил, что и фактическая выдача и выставление счёта.
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Service'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/TooMany'
  /tariffs/calculate:
    post:
      tags:
      - Каталог и тарифы
      operationId: calculateTariffs
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request POST \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            --header 'Content-Type: application/json' \
            --data "{\"service_id\":${SERVICE_ID:?},\"volume\":7500,\"day_volume\":250}" \
            "https://lk.parser-api.com/api/client/v1/tariffs/calculate"
      summary: Подобрать тариф под нагрузку
      description: Расчёт без записи. Варианты отсортированы по стоимости. Недоступный сервис даёт 404.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CalculatorInput'
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/TariffOption'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '415':
          $ref: '#/components/responses/UnsupportedMedia'
        '422':
          $ref: '#/components/responses/Validation'
        '429':
          $ref: '#/components/responses/TooMany'
  /services/{service_id}/trial:
    post:
      tags:
      - Подписки
      operationId: grantTrial
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request POST \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/services/${SERVICE_ID:?}/trial"
      summary: Активировать тестовый доступ
      description: Проверьте can_request_trial в GET /services и отправьте POST без тела. При успехе ответ содержит
        subscription_id, лимиты и дату окончания paid_till. Если ответ потерялся, проверьте подписки клиента.
        При 409 trial_unavailable используйте subscription_id из ошибки, если он указан.
      parameters:
      - $ref: '#/components/parameters/service_id'
      responses:
        '201':
          description: Тест предоставлен.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TrialResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: Тест недоступен. Если ранее выданный тест доступен этому клиенту, ответ содержит его subscription_id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TrialUnavailable'
              example:
                code: trial_unavailable
                message: Тест для этого сервиса недоступен
                request_id: example-request-id
                subscription_id: 42
        '429':
          $ref: '#/components/responses/TooMany'
        '500':
          description: Ошибка сервера. Проверьте состояние через GET /services и GET /subscriptions перед новой попыткой.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Problem'
              example:
                code: server_error
                message: Не удалось выполнить запрос
                request_id: example-request-id
  /subscriptions:
    get:
      tags:
      - Подписки
      operationId: listSubscriptions
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/subscriptions"
      summary: Получить подписки, сроки и расход
      description: Краткие строки отсортированы по paid_till, затем по id. Скрытые подписки и истёкшие подписки снятых с
        продажи сервисов исключены. Карточка по ID содержит тарифы и доступные действия.
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/SubscriptionSummary'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/TooMany'
  /subscriptions/{subscription_id}:
    get:
      tags:
      - Подписки
      operationId: getSubscription
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/subscriptions/${SUBSCRIPTION_ID:?}"
      summary: Посмотреть условия и действия подписки
      description: Те же правила видимости, что в списке. renewal_tariffs содержит действительные варианты ручного продления
        с источником цены, включая сохранённый тариф действующего скрытого из каталога сервиса. Карточка также содержит
        текущий тариф, количество пакетов, документацию и запланированные изменения объёма.
      parameters:
      - $ref: '#/components/parameters/subscription_id'
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Subscription'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooMany'
  /subscriptions/{subscription_id}/start-period:
    post:
      tags:
      - Подписки
      operationId: startPeriodNow
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request POST \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/subscriptions/${SUBSCRIPTION_ID:?}/start-period"
      summary: Начать новый оплаченный период сейчас
      description: Без тела, даты и UUID. Доступность совпадает с кнопкой в кабинете. При наличии полного оплаченного
        месяца впереди и допустимом графике смены условий требуется расход строго более 75% месячного лимита либо
        смена тарифа, числа пакетов или лимитов в ближайшем следующем периоде. Переход на другой тариф с теми же квотами допускает старт при нулевом расходе. Начатый сегодня период повторно запустить нельзя.
        Сервер проверяет условия под блокировкой. Остаток текущего периода сгорает. Если действие уже недоступно,
        возвращается 409 state_conflict. После потери ответа проверьте карточку подписки перед новой командой.
      parameters:
      - $ref: '#/components/parameters/subscription_id'
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PeriodStarted'
              example:
                subscription_id: 42
                started_on: '2026-11-22'
                paid_till: '2026-12-21'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: В текущем состоянии кабинета досрочный старт недоступен.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Problem'
              example:
                code: state_conflict
                message: Начать новый период досрочно уже нельзя — обновите страницу
                request_id: example-request-id
        '429':
          $ref: '#/components/responses/TooMany'
  /invoices/preview:
    post:
      tags:
      - Счета
      operationId: quoteInvoice
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request POST \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            --header 'Content-Type: application/json' \
            --data-binary @invoice.json \
            "https://lk.parser-api.com/api/client/v1/invoices/preview"
      summary: Рассчитать стоимость счёта
      description: Необязательный расчёт по тем же правилам, что для выставления. Возвращает состав, сумму и изменения лимитов
        и срока. Данные пересчитываются при выставлении.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InvoiceInput'
            examples:
              prolong:
                value:
                  type: prolong
                  month_count: 3
                  items:
                  - subscription_id: 42
                  - subscription_id: 56
              connect:
                value:
                  type: connect
                  month_count: 2
                  items:
                  - service_id: 3
                    tariff_id: 7
                    tariff_count: 1
              increase:
                value:
                  type: increase
                  items:
                  - subscription_id: 42
                    added_count: 1
              prolongWithChanges:
                value:
                  type: prolong
                  month_count: 1
                  items:
                  - subscription_id: 42
                    tariff_id: 7
                    tariff_count: 2
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Quote'
              example:
                items:
                - service_id: 3
                  service_name: Пример сервиса
                  subscription_id: 42
                  tariff_id: 7
                  tariff_name: Базовый
                  tariff_count: 2
                  price: '500.00'
                  amount: '1000.00'
                  old_day_limit: 100
                  new_day_limit: 200
                  old_month_limit: 1000
                  new_month_limit: 2000
                  old_paid_till: '2026-11-30'
                  new_paid_till: '2026-12-31'
                total: '1000.00'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '415':
          $ref: '#/components/responses/UnsupportedMedia'
        '422':
          $ref: '#/components/responses/InvoiceValidation'
        '429':
          $ref: '#/components/responses/TooMany'
  /invoices:
    post:
      tags:
      - Счета
      operationId: createInvoice
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request POST \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            --header "Idempotency-Key: ${INVOICE_KEY:?}" \
            --header 'Content-Type: application/json' \
            --data-binary @invoice.json \
            "https://lk.parser-api.com/api/client/v1/invoices"
      summary: Выставить счёт и получить способ оплаты
      description: Предварительный расчёт необязателен. Одна команда выставляет один счёт по одной или нескольким позициям.
        Тип плательщика фиксируется при создании. Для физлица ЛК сразу запрашивает ссылку СБП и возвращает payment; для
        организации или ИП — адрес invoice_pdf_url и состояние invoice_pdf_status. Если счёт сохранён, а банк временно не
        выдал ссылку, возвращаются 201, ID и payment=null; действующую ссылку можно получить в карточке этого счёта. Если номер ещё не получен,
        запросите PDF для того же счёта. При повторе команды возвращается 201 с тем же ID и актуальной карточкой без повторного выпуска или
        создания новой ссылки.
      parameters:
      - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InvoiceInput'
            examples:
              prolong:
                value:
                  type: prolong
                  month_count: 3
                  items:
                  - subscription_id: 42
                  - subscription_id: 56
              connect:
                value:
                  type: connect
                  month_count: 2
                  items:
                  - service_id: 3
                    tariff_id: 7
                    tariff_count: 1
              increase:
                value:
                  type: increase
                  items:
                  - subscription_id: 42
                    added_count: 1
              prolongWithChanges:
                value:
                  type: prolong
                  month_count: 1
                  items:
                  - subscription_id: 42
                    tariff_id: 7
                    tariff_count: 2
      responses:
        '201':
          description: Счёт сохранён. В ответе указан его постоянный ID, в том числе при задержке банка или бухгалтерии.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
              examples:
                organization:
                  value:
                    id: 81
                    number: № LK-81
                    type: prolong
                    status: pending
                    person_type: org
                    created_at: '2026-11-22T12:00:00+03:00'
                    paid_at: null
                    applied_at: null
                    month_count: 1
                    total: '1000.00'
                    auto_created: false
                    items:
                    - service_id: 3
                      service_name: Пример сервиса
                      subscription_id: 42
                      tariff_id: 7
                      tariff_name: Базовый
                      tariff_count: 2
                      price: '500.00'
                      amount: '1000.00'
                      old_day_limit: 100
                      new_day_limit: 200
                      old_month_limit: 1000
                      new_month_limit: 2000
                      old_paid_till: '2026-11-30'
                      new_paid_till: '2026-12-31'
                    invoice_pdf_status: pending
                    upd_status: unavailable
                    invoice_pdf_url: /api/client/v1/invoices/81/pdf
                    payment: null
                individual:
                  value:
                    id: 81
                    number: № LK-81
                    type: prolong
                    status: pending
                    person_type: fiz
                    created_at: '2026-11-22T12:00:00+03:00'
                    paid_at: null
                    applied_at: null
                    month_count: 1
                    total: '1000.00'
                    auto_created: false
                    items:
                    - service_id: 3
                      service_name: Пример сервиса
                      subscription_id: 42
                      tariff_id: 7
                      tariff_name: Базовый
                      tariff_count: 2
                      price: '500.00'
                      amount: '1000.00'
                      old_day_limit: 100
                      new_day_limit: 200
                      old_month_limit: 1000
                      new_month_limit: 2000
                      old_paid_till: '2026-11-30'
                      new_paid_till: '2026-12-31'
                    invoice_pdf_status: unavailable
                    upd_status: unavailable
                    invoice_pdf_url: null
                    payment:
                      id: 91
                      invoice_id: 81
                      amount: '1000.00'
                      expires_at: '2026-11-22T12:15:00+03:00'
                      sbp_url: https://example.org/sbp/demo
                      qr_payload: https://example.org/sbp/demo
          headers:
            Location:
              required: true
              description: Путь к созданному счёту.
              schema:
                type: string
                format: uri-reference
              example: /api/client/v1/invoices/81
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '415':
          $ref: '#/components/responses/UnsupportedMedia'
        '422':
          $ref: '#/components/responses/InvoiceValidation'
        '429':
          $ref: '#/components/responses/TooMany'
        '503':
          $ref: '#/components/responses/Unavailable'
    get:
      tags:
      - Счета
      operationId: listInvoices
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/invoices"
      summary: Получить последние счета клиента
      description: Сначала выбираются последние 100 собственных счетов на подключение, продление или увеличение объёма по
        created_at и id по убыванию. Бесплатные тесты не занимают места в этом списке. Поиск и фильтры применяются внутри
        этих 100 счетов. Выдача по 25 на странице. Страница за концом списка пуста. Даты создания включительны. Интервал
        с from позже to отклоняется. Ограничение относится только к списку. В строке выдаются номер, дата, сумма, статус,
        признак автосчёта и названия сервисов. Подробный состав доступен по ID.
      parameters:
      - $ref: '#/components/parameters/page'
      - name: search
        in: query
        schema:
          type: string
        description: Номер счёта, ID счёта или название сервиса.
      - name: status
        in: query
        schema:
          $ref: '#/components/schemas/InvoiceStatus'
        description: Состояние счёта.
      - name: from
        in: query
        schema:
          type: string
          format: date
        description: Дата начала.
      - name: to
        in: query
        schema:
          type: string
          format: date
        description: Дата окончания.
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvoicePage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/Validation'
        '429':
          $ref: '#/components/responses/TooMany'
  /invoices/{invoice_id}:
    get:
      tags:
      - Счета
      operationId: getInvoice
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --fail-with-body --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            "https://lk.parser-api.com/api/client/v1/invoices/${INVOICE_ID:?}"
      summary: Посмотреть счёт и статус оплаты
      description: Карточка доступна владельцу по ID, в том числе за пределами последних 100 счетов. status=pending означает
        ожидание оплаты, paid — ЛК учёл оплату, cancelled — счёт отменён. paid_at и applied_at отражают учёт оплаты и применение
        к подписке. Для ожидающего счёта физлица payment.sbp_url содержит ссылку СБП, если её предоставил банк.
        При повторном чтении ЛК возвращает действующий платёж. Если он отсутствует или истёк, GET запрашивает новый.
        Статус оплаты берётся из ЛК. Банк не опрашивается о зачислении. При недоступности банка или параллельном выпуске
        карточка остаётся доступной с payment=null. Для организаций, оплаченных и отменённых счетов payment=null. Плановая обработка отменяет ожидающие счета физлиц старше 30 дней.
      parameters:
      - $ref: '#/components/parameters/invoice_id'
      responses:
        '200':
          description: Успешный результат.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooMany'
  /invoices/{invoice_id}/pdf:
    get:
      tags:
      - Оплата и документы
      operationId: downloadInvoicePdf
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            --output response.bin --write-out 'HTTP %{http_code} %{content_type}\n' \
            "https://lk.parser-api.com/api/client/v1/invoices/${INVOICE_ID:?}/pdf"
      summary: Скачать PDF счёта
      description: Для собственного счёта организации. Для отменённого счёта или оплаченного счёта без бухгалтерского документа возвращается 404. Если у ожидающего счёта ещё нет номера, запрос PDF повторяет попытку
        выставления, как при скачивании на сайте. При отсутствии права или неприменимости возвращается 404. При временной ошибке получения уже выписанного
        документа — 503.
      parameters:
      - $ref: '#/components/parameters/invoice_id'
      responses:
        '200':
          description: Готовый файл PDF.
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '202':
          description: Документ ожидает выпуска. Следующий запрос возможен через указанное число секунд.
          headers:
            Retry-After:
              required: true
              description: Секунды до следующего запроса документа.
              schema: {type: integer, minimum: 1}
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentPending'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooMany'
        '503':
          $ref: '#/components/responses/Unavailable'
  /invoices/{invoice_id}/upd:
    get:
      tags:
      - Оплата и документы
      operationId: downloadUpd
      x-codeSamples:
      - lang: shell
        lib: curl
        source: |-
          curl --silent --show-error --request GET \
            --header "Authorization: Bearer ${LK_KEY:?}" \
            --output response.bin --write-out 'HTTP %{http_code} %{content_type}\n' \
            "https://lk.parser-api.com/api/client/v1/invoices/${INVOICE_ID:?}/upd"
      summary: Скачать УПД
      description: Только для собственного оплаченного счёта организации или ИП. Выпуска УПД может потребоваться ждать до
        пяти рабочих дней. Чтение не инициирует выпуск документа. При отсутствии права или неприменимости возвращается 404.
        При временной ошибке получения уже выписанного документа — 503.
      parameters:
      - $ref: '#/components/parameters/invoice_id'
      responses:
        '200':
          description: Готовый файл PDF.
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '202':
          description: Документ ожидает выпуска. Следующий запрос возможен через указанное число секунд.
          headers:
            Retry-After:
              required: true
              description: Секунды до следующего запроса документа.
              schema: {type: integer, minimum: 1}
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentPending'
              example:
                invoice_id: 81
                document: upd
                status: pending
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooMany'
        '503':
          $ref: '#/components/responses/Unavailable'
components:
  securitySchemes:
    ClientKey:
      type: http
      scheme: bearer
      description: 'Действующий ключ парсеров в Authorization: Bearer <ключ клиента>.'
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      schema:
        type: string
        format: uuid
      description: UUID команды, создаваемый клиентом до первой отправки. При потере ответа повторить с тем же UUID.
    service_id:
      name: service_id
      in: path
      required: true
      description: Идентификатор сервиса.
      schema:
        type: integer
        minimum: 1
    subscription_id:
      name: subscription_id
      in: path
      required: true
      description: Идентификатор подписки.
      schema:
        type: integer
        minimum: 1
    invoice_id:
      name: invoice_id
      in: path
      required: true
      description: Идентификатор счёта.
      schema:
        type: integer
        minimum: 1
    page:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        default: 1
      description: Нумерация с 1. Страница за концом списка возвращает пустой items.
  responses:
    BadRequest:
      description: Некорректный JSON, лишний параметр URL, ключ в URL, тело у метода без тела или отсутствующий/неверный
        Idempotency-Key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          example:
            code: invalid_request
            message: Некорректный JSON, лишний параметр URL, ключ в URL, тело у метода без тела или отсутствующий/неверный
              Idempotency-Key
            request_id: example-request-id
    Unauthorized:
      description: Ключ отсутствует или неверен, доступ к ЛК или API выключен, бренд не привязан либо домен не разрешён. Ответ одинаков.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          example:
            code: unauthorized
            message: Доступ не разрешён
            request_id: example-request-id
      headers:
        WWW-Authenticate:
          required: true
          schema:
            const: Bearer realm="lk"
    Forbidden:
      description: ip_not_allowed для запроса с недопустимого IP. email_required при отсутствии e-mail после проверки доступа.
        В этом случае сообщение точно совпадает с примером.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          examples:
            email_required:
              value:
                code: email_required
                message: Укажите e-mail в профиле личного кабинета
                request_id: example-request-id
            ip_not_allowed:
              value:
                code: ip_not_allowed
                message: Доступ с этого IP запрещён
                request_id: example-request-id
    NotFound:
      description: Объект отсутствует или недоступен этому клиенту. Ответ для чужого идентификатора одинаков.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          example:
            code: not_found
            message: Объект не найден
            request_id: example-request-id
    Conflict:
      description: Состояние ресурса препятствует операции. Ошибки idempotency_conflict и operation_in_progress применимы
        только к командам с обязательным Idempotency-Key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          examples:
            state_conflict:
              value:
                code: state_conflict
                message: Операция недоступна в текущем состоянии
                request_id: example-request-id
            idempotency_conflict:
              value:
                code: idempotency_conflict
                message: Этот идентификатор уже использован для другой команды
                request_id: example-request-id
            operation_in_progress:
              value:
                code: operation_in_progress
                message: Команда ещё выполняется
                request_id: example-request-id
      headers:
        Retry-After:
          description: Секунды до повтора при временном отказе. Для operation_in_progress и rate_limited заголовок обязателен.
          schema:
            type: integer
            minimum: 1
    Validation:
      description: Проверка данных не пройдена. Для полей запроса имена в fields задаются путями, например items.0.tariff_count.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          example:
            code: validation_error
            message: Проверка данных не пройдена
            request_id: example-request-id
    InvoiceValidation:
      description: Ошибка проверки состава. При расхождении пропущенных условий продления поле fields указывает позиции и
        параметры для явного выбора. В renewal_terms возвращаются условия на первый день продления для каждой такой подписки.
        При обычной ошибке ввода возвращается стандартный ответ validation_error.
      content:
        application/json:
          schema:
            oneOf:
            - $ref: '#/components/schemas/Problem'
            - type: object
              additionalProperties: false
              required: [code, message, request_id, fields, renewal_terms]
              properties:
                code: {const: validation_error}
                message: {type: string}
                request_id: {type: string}
                fields:
                  $ref: '#/components/schemas/Problem/properties/fields'
                renewal_terms:
                  type: array
                  minItems: 1
                  items:
                    type: object
                    additionalProperties: false
                    required: [subscription_id, period_start, tariff_id, tariff_count]
                    properties:
                      subscription_id: {type: integer, minimum: 1}
                      period_start: {type: string, format: date}
                      tariff_id: {type: integer, minimum: 1}
                      tariff_count: {type: integer, minimum: 1}
          examples:
            scheduledChanges:
              summary: После двух смен к началу продления будут действовать тариф 9 и три пакета.
              value:
                code: validation_error
                message: Уточните условия продления подписки 42
                request_id: example-request-id
                fields:
                  items.0.tariff_id: [Укажите тариф]
                  items.0.tariff_count: [Укажите число пакетов]
                renewal_terms:
                - {subscription_id: 42, period_start: '2027-01-01', tariff_id: 9, tariff_count: 3}
    TooMany:
      description: Превышена допустимая частота запросов.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          example:
            code: rate_limited
            message: Превышена допустимая частота запросов
            request_id: example-request-id
      headers:
        Retry-After:
          description: Секунды до повтора при временном отказе. Для operation_in_progress и rate_limited заголовок обязателен.
          schema:
            type: integer
            minimum: 1
    Unavailable:
      description: Временная ошибка зависимости. Для команды с обязательным Idempotency-Key сохраняйте исходный UUID. Для скачивания PDF повторите запрос к тому же документу.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          example:
            code: upstream_unavailable
            message: Внешняя система временно недоступна
            request_id: example-request-id
      headers:
        Retry-After:
          description: Секунды до повтора при временном отказе. Для operation_in_progress и rate_limited заголовок обязателен.
          schema:
            type: integer
            minimum: 1
    UnsupportedMedia:
      description: Для запроса с телом требуется application/json.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Problem'
          example:
            code: unsupported_media_type
            message: Для запроса с телом требуется application/json
            request_id: example-request-id
  schemas:
    Money:
      type: string
      pattern: ^(0|[1-9][0-9]*)\.[0-9]{2}$
      examples:
      - '1490.00'
      description: Рубли, строка с двумя цифрами после точки.
    PayerType:
      type: string
      enum:
      - fiz
      - org
      description: fiz — физлицо, org — организация или ИП.
    DocumentState:
      type: string
      enum:
      - unavailable
      - pending
      - ready
      description: unavailable — документ не положен, pending — ожидается выпуск, ready — документ выписан и доступен для
        запроса PDF.
    Problem:
      type: object
      properties:
        code:
          type: string
          description: Стабильный код для программы.
        message:
          type: string
        request_id:
          type: string
        fields:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
      required:
      - code
      - message
      - request_id
      additionalProperties: false
    TrialUnavailable:
      type: object
      required: [code, message, request_id]
      properties:
        code: {const: trial_unavailable}
        message: {type: string}
        request_id: {type: string}
        subscription_id: {type: integer, minimum: 1}
    Organization:
      type: object
      properties:
        inn:
          type: [string, 'null']
          description: ИНН из привязанной карточки. У ранее импортированной организации ИНН может отсутствовать.
        name:
          anyOf:
          - type: string
          - type: 'null'
      required:
      - inn
      - name
      additionalProperties: false
    RequisitesInput:
      type: object
      properties:
        inn:
          type: string
          pattern: ^(?:[0-9]{10}|[0-9]{12})$
        bik:
          type: string
          pattern: ^[0-9]{9}$
        account:
          type: string
          pattern: ^[0-9]{20}$
          description: Счёт проверяется по БИК. Все три значения передаются строками.
      required:
      - inn
      - bik
      - account
      additionalProperties: false
    Profile:
      type: object
      properties:
        person_type:
          $ref: '#/components/schemas/PayerType'
        notify_expiring:
          type: boolean
        days_notify:
          type: integer
          minimum: 1
          maximum: 30
        auto_invoice:
          type: boolean
        auto_invoice_day:
          type: integer
          minimum: 1
          maximum: 28
        auto_invoice_months:
          type: integer
          minimum: 1
          maximum: 12
        organization:
          anyOf:
          - $ref: '#/components/schemas/Organization'
          - type: 'null'
        emails:
          type: array
          items:
            type: string
            format: email
          minItems: 1
        allowed_ips:
          type: array
          items:
            type: string
        apply_ip_list_to_lk_api:
          type: boolean
          description: По умолчанию true. Изменяется на сайте.
      required:
      - person_type
      - notify_expiring
      - days_notify
      - auto_invoice
      - auto_invoice_day
      - auto_invoice_months
      - organization
      - emails
      - allowed_ips
      - apply_ip_list_to_lk_api
      additionalProperties: false
    ProfilePatch:
      type: object
      properties:
        person_type:
          $ref: '#/components/schemas/PayerType'
        notify_expiring:
          type: boolean
        days_notify:
          type: integer
          minimum: 1
          maximum: 30
        auto_invoice:
          type: boolean
        auto_invoice_day:
          type: integer
          minimum: 1
          maximum: 28
        auto_invoice_months:
          type: integer
          minimum: 1
          maximum: 12
      additionalProperties: false
      minProperties: 1
      description: Частичное изменение. Защищённые и неизвестные поля отклоняют запрос целиком. Для включённых уведомлений
        итоговое days_notify обязательно. Если автосчёт включён, проверяются итоговый день и срок. Переход на fiz выключает
        автосчёт.
    RequisitesResult:
      type: object
      properties:
        organization:
          $ref: '#/components/schemas/Organization'
        person_type:
          const: org
        bank_account_status:
          type: string
          enum:
          - saved
          - retry_required
        message:
          anyOf:
          - type: string
          - type: 'null'
      required:
      - organization
      - person_type
      - bank_account_status
      - message
      additionalProperties: false
    Link:
      type: object
      properties:
        title:
          type: string
        url:
          type: string
          format: uri
      required:
      - title
      - url
      additionalProperties: false
    ServiceDocs:
      type: object
      properties:
        title:
          type: string
        links:
          type: array
          items:
            $ref: '#/components/schemas/Link'
        example_template:
          anyOf:
          - type: string
          - type: 'null'
          description: Пример запроса к сервису с заполнителем {API_KEY}. Ключ клиента в ответ не включается.
      required:
      - title
      - links
      - example_template
      additionalProperties: false
    Tariff:
      type: object
      properties:
        id:
          type: integer
          minimum: 1
        name:
          type: string
        price:
          $ref: '#/components/schemas/Money'
        day_limit:
          type: integer
          minimum: 0
        month_limit:
          type: integer
          minimum: 0
        no_day_cap:
          type: boolean
          description: Дневной лимит тарифа больше или равен месячному. Весь месячный пакет можно использовать за один день.
        source:
          type: string
          enum:
          - common
          - service
          - personal
          - connected
          description: personal — тариф назначен этому клиенту; connected — предложение сохранено только благодаря его подписке;
            service — публичная цена сервиса; common — общая публичная цена. Один тариф выводится один раз. Персональное
            назначение имеет приоритет, обычный действующий публичный тариф сохраняет свой источник.
      required:
      - id
      - name
      - price
      - day_limit
      - month_limit
      - no_day_cap
      - source
      additionalProperties: false
    Service:
      type: object
      properties:
        id:
          type: integer
          minimum: 1
        name:
          type: string
        category:
          type: string
          description: Первая категория сервиса в меню ЛК. У доступного для подключения сервиса без карточки меню — «Другие сервисы».
        documentation:
          type: array
          items:
            $ref: '#/components/schemas/Link'
        subscription_id:
          anyOf:
          - type: integer
            minimum: 1
          - type: 'null'
          description: ID видимой подписки клиента либо null, в том числе если прежняя подписка скрыта.
        active:
          type: boolean
        trial_active:
          type: boolean
        can_request_trial:
          type: boolean
        can_connect:
          type: boolean
        purchase_tariffs:
          type: array
          items:
            $ref: '#/components/schemas/Tariff'
        trial_limits:
          anyOf:
          - type: object
            properties:
              day_limit:
                type: integer
                minimum: 0
              month_limit:
                type: integer
                minimum: 0
            required:
            - day_limit
            - month_limit
            additionalProperties: false
          - type: 'null'
      required:
      - id
      - name
      - category
      - documentation
      - subscription_id
      - active
      - trial_active
      - can_request_trial
      - can_connect
      - purchase_tariffs
      - trial_limits
      additionalProperties: false
    CalculatorInput:
      type: object
      properties:
        service_id:
          type: integer
          minimum: 1
        volume:
          type: integer
          minimum: 1
          maximum: 100000000
        day_volume:
          type: integer
          minimum: 1
          maximum: 100000000
        no_day_cap:
          type: boolean
      required:
      - service_id
      - volume
      additionalProperties: false
    TariffOption:
      type: object
      properties:
        tariff_id:
          type: integer
          minimum: 1
        name:
          type: string
        count:
          type: integer
          minimum: 1
        day_limit:
          type: integer
          minimum: 0
        month_limit:
          type: integer
          minimum: 0
        cost:
          $ref: '#/components/schemas/Money'
        source:
          type: string
          enum:
          - common
          - service
          - personal
          - connected
          description: personal — тариф назначен этому клиенту; connected — предложение сохранено только благодаря его подписке;
            service — публичная цена сервиса; common — общая публичная цена. Один тариф выводится один раз. Персональное
            назначение имеет приоритет, обычный действующий публичный тариф сохраняет свой источник.
      required:
      - tariff_id
      - name
      - count
      - day_limit
      - month_limit
      - cost
      - source
      additionalProperties: false
    SubscriptionChange:
      type: object
      properties:
        effective_on:
          type: string
          format: date
        tariff_id:
          anyOf:
          - type: integer
            minimum: 1
          - type: 'null'
          description: ID запланированного тарифа. При прямой установке лимитов без тарифа равен null.
        tariff_name:
          anyOf:
          - type: string
          - type: 'null'
        tariff_count:
          type: integer
          minimum: 0
        day_limit:
          type: integer
          minimum: 0
        month_limit:
          type: integer
          minimum: 0
      required:
      - effective_on
      - tariff_id
      - tariff_name
      - tariff_count
      - day_limit
      - month_limit
      additionalProperties: false
    EarlyStart:
      type: object
      properties:
        next_period_on:
          type: string
          format: date
        new_paid_till:
          type: string
          format: date
      required:
      - next_period_on
      - new_paid_till
      additionalProperties: false
    Subscription:
      type: object
      properties:
        id:
          type: integer
          minimum: 1
        service_id:
          type: integer
          minimum: 1
        service_name:
          type: string
        tariff_id:
          anyOf:
          - type: integer
            minimum: 1
          - type: 'null'
        tariff_name:
          anyOf:
          - type: string
          - type: 'null'
        tariff_count:
          type: integer
          minimum: 0
        trial:
          type: boolean
        paid_till:
          type: string
          format: date
        day_remaining:
          type: integer
          minimum: 0
          description: Неизрасходованная дневная квота. Для истёкшей подписки равна 0.
        month_remaining:
          type: [integer, 'null']
          minimum: 0
          description: Неизрасходованная месячная квота. null при отсутствии месячного ограничения, 0 для истёкшей подписки.
        day_used:
          type: integer
          minimum: 0
        month_used:
          type: integer
          minimum: 0
        day_limit:
          type: integer
          minimum: 0
        month_limit:
          type: integer
          minimum: 0
        status:
          type: string
          enum:
          - expired
          - month_limit_reached
          - day_limit_reached
          - expiring
          - active
        next_change:
          anyOf:
          - $ref: '#/components/schemas/SubscriptionChange'
          - type: 'null'
        early_start:
          anyOf:
          - $ref: '#/components/schemas/EarlyStart'
          - type: 'null'
          description: Объект возвращается, когда в кабинете доступна кнопка досрочного старта. Если кнопка недоступна, значение равно null.
        can_prolong:
          type: boolean
          description: Есть доступный тариф ручного продления.
        can_increase:
          type: boolean
          description: По правилам ЛК можно рассчитать докупку на текущем тарифе.
        renewal_tariffs:
          type: array
          items:
            $ref: '#/components/schemas/Tariff'
        documentation:
          anyOf:
          - $ref: '#/components/schemas/ServiceDocs'
          - type: 'null'
      required:
      - id
      - service_id
      - service_name
      - tariff_id
      - tariff_name
      - tariff_count
      - trial
      - paid_till
      - day_remaining
      - month_remaining
      - day_used
      - month_used
      - day_limit
      - month_limit
      - status
      - next_change
      - early_start
      - can_prolong
      - can_increase
      - renewal_tariffs
      - documentation
      additionalProperties: false
    ConnectLine:
      type: object
      properties:
        service_id:
          type: integer
          minimum: 1
        tariff_id:
          type: integer
          minimum: 1
        tariff_count:
          type: integer
          minimum: 1
          maximum: 1000
      required:
      - service_id
      - tariff_id
      - tariff_count
      additionalProperties: false
    ProlongLine:
      type: object
      properties:
        subscription_id:
          type: integer
          minimum: 1
        tariff_id:
          type: integer
          minimum: 1
        tariff_count:
          type: integer
          minimum: 1
          maximum: 1000
      required:
      - subscription_id
      additionalProperties: false
      description: Для каждого пропущенного поля ЛК сравнивает текущее платное условие со значением на первый день продления
        с учётом всей последовательности запланированных смен по эту дату включительно. При совпадении подставляет значение,
        если оно применимо. При расхождении возвращает 422 validation_error с путём поля и итоговыми условиями подписки в
        renewal_terms. При отсутствии платной базы требуется явный выбор тарифа и количества. Явно заданные параметры
        проверяются по обычным правилам продления. Сервер проверяет весь состав до создания счёта.
    IncreaseLine:
      type: object
      properties:
        subscription_id:
          type: integer
          minimum: 1
        added_count:
          type: integer
          minimum: 1
          maximum: 1000
      required:
      - subscription_id
      - added_count
      additionalProperties: false
    InvoiceInput:
      description: Один тип операции на счёт. Сервис или подписка указывается в составе один раз. Даты, суммы и лимиты рассчитывает
        ЛК. Сумма счёта ограничена 999999.99 рубля. Рассчитанные дневной и месячный лимиты каждой позиции должны быть в пределах 0–2147483647. Нарушение этих условий даёт 422 validation_error.
      oneOf:
      - type: object
        properties:
          type:
            type: string
            const: connect
          month_count:
            type: integer
            minimum: 1
            maximum: 12
          items:
            type: array
            items:
              $ref: '#/components/schemas/ConnectLine'
            minItems: 1
            maxItems: 50
        required:
        - type
        - month_count
        - items
        additionalProperties: false
      - type: object
        properties:
          type:
            type: string
            const: prolong
          month_count:
            type: integer
            minimum: 1
            maximum: 12
          items:
            type: array
            items:
              $ref: '#/components/schemas/ProlongLine'
            minItems: 1
            maxItems: 50
        required:
        - type
        - month_count
        - items
        additionalProperties: false
      - type: object
        properties:
          type:
            type: string
            const: increase
          items:
            type: array
            items:
              $ref: '#/components/schemas/IncreaseLine'
            minItems: 1
            maxItems: 50
        required:
        - type
        - items
        additionalProperties: false
    InvoiceLine:
      type: object
      properties:
        service_id:
          type: integer
          minimum: 1
        service_name:
          type: string
        subscription_id:
          anyOf:
          - type: integer
            minimum: 1
          - type: 'null'
        tariff_id:
          type: integer
          minimum: 1
        tariff_name:
          anyOf:
          - type: string
          - type: 'null'
        tariff_count:
          type: integer
          minimum: 0
        price:
          $ref: '#/components/schemas/Money'
        amount:
          $ref: '#/components/schemas/Money'
        old_day_limit:
          anyOf:
          - type: integer
            minimum: 0
          - type: 'null'
        new_day_limit:
          anyOf:
          - type: integer
            minimum: 0
            maximum: 2147483647
          - type: 'null'
        old_month_limit:
          anyOf:
          - type: integer
            minimum: 0
          - type: 'null'
        new_month_limit:
          anyOf:
          - type: integer
            minimum: 0
            maximum: 2147483647
          - type: 'null'
        old_paid_till:
          anyOf:
          - type: string
            format: date
          - type: 'null'
        new_paid_till:
          anyOf:
          - type: string
            format: date
          - type: 'null'
      required:
      - service_id
      - service_name
      - subscription_id
      - tariff_id
      - tariff_name
      - tariff_count
      - price
      - amount
      - old_day_limit
      - new_day_limit
      - old_month_limit
      - new_month_limit
      - old_paid_till
      - new_paid_till
      additionalProperties: false
    Quote:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/InvoiceLine'
        total:
          $ref: '#/components/schemas/Money'
      required:
      - items
      - total
      additionalProperties: false
    InvoiceStatus:
      type: string
      enum:
      - pending
      - paid
      - cancelled
    Invoice:
      type: object
      properties:
        id:
          type: integer
          minimum: 1
        number:
          type: string
          description: Отображаемый номер счёта. Поиск принимает также ID счёта и номер бухгалтерского счёта.
        type:
          type: string
          enum:
          - connect
          - prolong
          - increase
        status:
          $ref: '#/components/schemas/InvoiceStatus'
        person_type:
          $ref: '#/components/schemas/PayerType'
        created_at:
          type: string
          format: date-time
        paid_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
        applied_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
        month_count:
          type: [integer, 'null']
          description: Число месяцев при подключении и продлении. Для увеличения лимита равно null.
        total:
          $ref: '#/components/schemas/Money'
        auto_created:
          type: boolean
          description: true у автоматически выставленного счёта.
        items:
          type: array
          items:
            $ref: '#/components/schemas/InvoiceLine'
        invoice_pdf_status:
          $ref: '#/components/schemas/DocumentState'
        upd_status:
          $ref: '#/components/schemas/DocumentState'
        invoice_pdf_url:
          anyOf:
          - type: string
            format: uri-reference
            pattern: ^/api/client/v1/invoices/[1-9][0-9]*/pdf$
            description: Путь на текущем домене ЛК. Скачать с тем же Authorization, в том числе проверить готовность по
              ответу 202.
          - type: 'null'
        payment:
          anyOf:
          - $ref: '#/components/schemas/Payment'
          - type: 'null'
          description: Ещё действующий платёж ожидающего счёта физлица. null при ожидании ссылки, истечении, оплате, отмене
            или ином типе плательщика.
      required:
      - id
      - number
      - type
      - status
      - person_type
      - created_at
      - paid_at
      - applied_at
      - month_count
      - total
      - auto_created
      - items
      - invoice_pdf_status
      - upd_status
      - invoice_pdf_url
      - payment
      additionalProperties: false
      description: Счёт на подключение, продление или увеличение объёма. Бесплатный тест получен отдельной операцией.
      allOf:
      - if:
          properties:
            type: {const: increase}
        then:
          properties:
            month_count: {type: 'null'}
        else:
          properties:
            month_count: {type: integer, minimum: 1, maximum: 12}
      - if:
          properties:
            person_type:
              const: fiz
        then:
          properties:
            invoice_pdf_url:
              type: 'null'
            invoice_pdf_status:
              const: unavailable
            upd_status:
              const: unavailable
      - if:
          properties:
            person_type:
              const: org
        then:
          properties:
            payment:
              type: 'null'
      - if:
          properties:
            status:
              enum:
              - paid
              - cancelled
        then:
          properties:
            payment:
              type: 'null'
      - if:
          properties:
            status:
              const: cancelled
        then:
          properties:
            invoice_pdf_status:
              const: unavailable
            upd_status:
              const: unavailable
      - if:
          properties:
            invoice_pdf_status:
              enum:
              - pending
              - ready
        then:
          properties:
            invoice_pdf_url:
              type: string
              format: uri-reference
              pattern: ^/api/client/v1/invoices/[1-9][0-9]*/pdf$
              description: Путь на текущем домене ЛК. Скачать с тем же Authorization, в том числе проверить готовность по
                ответу 202.
      - if:
          properties:
            invoice_pdf_status:
              const: unavailable
        then:
          properties:
            invoice_pdf_url:
              type: 'null'
      - if:
          properties:
            person_type:
              const: org
            status:
              const: pending
        then:
          properties:
            invoice_pdf_status:
              enum:
              - pending
              - ready
      - if:
          properties:
            status:
              const: pending
        then:
          properties:
            upd_status:
              const: unavailable
      - if:
          properties:
            person_type: {const: org}
            status: {const: paid}
        then:
          properties:
            invoice_pdf_status: {enum: [ready, unavailable]}
            upd_status: {enum: [pending, ready]}
    Payment:
      type: object
      properties:
        id:
          type: integer
          minimum: 1
        invoice_id:
          type: integer
          minimum: 1
        amount:
          $ref: '#/components/schemas/Money'
        expires_at:
          type: string
          format: date-time
          description: Срок действия ссылки с часовым поясом. В этот момент ссылка перестаёт выдаваться в карточке счёта.
        qr_payload:
          anyOf:
          - type: string
            minLength: 1
          - type: 'null'
        sbp_url:
          anyOf:
          - type: string
            format: uri
            pattern: ^https://
          - type: 'null'
      required:
      - id
      - invoice_id
      - amount
      - expires_at
      - qr_payload
      - sbp_url
      additionalProperties: false
      anyOf:
      - properties:
          sbp_url:
            type: string
      - properties:
          qr_payload:
            type: string
    InvoicePage:
      description: Страница из выборки последних 100 счетов клиента. В ней максимум четыре непустые страницы.
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/InvoiceSummary'
          maxItems: 25
        page:
          type: integer
          minimum: 1
        per_page:
          const: 25
        next_page:
          anyOf:
          - type: integer
            minimum: 2
            maximum: 4
          - type: 'null'
      required:
      - items
      - page
      - per_page
      - next_page
      additionalProperties: false
      allOf:
      - if:
          properties:
            page:
              minimum: 4
        then:
          properties:
            next_page:
              type: 'null'
      - if:
          properties:
            page:
              minimum: 5
        then:
          properties:
            items:
              maxItems: 0
    TrialResult:
      type: object
      properties:
        subscription_id:
          type: integer
          minimum: 1
        service_id:
          type: integer
          minimum: 1
        paid_till:
          type: string
          format: date
        day_limit:
          type: integer
          minimum: 0
        month_limit:
          type: integer
          minimum: 0
        documentation:
          anyOf:
          - $ref: '#/components/schemas/ServiceDocs'
          - type: 'null'
      required:
      - subscription_id
      - service_id
      - paid_till
      - day_limit
      - month_limit
      - documentation
      additionalProperties: false
    PeriodStarted:
      type: object
      properties:
        subscription_id:
          type: integer
          minimum: 1
        started_on:
          type: string
          format: date
        paid_till:
          type: string
          format: date
      required:
      - subscription_id
      - started_on
      - paid_till
      additionalProperties: false
    DocumentPending:
      type: object
      properties:
        invoice_id:
          type: integer
          minimum: 1
        document:
          type: string
          enum:
          - invoice
          - upd
        status:
          const: pending
      required:
      - invoice_id
      - document
      - status
      additionalProperties: false
    SubscriptionSummary:
      type: object
      properties:
        id:
          type: integer
          minimum: 1
        service_id:
          type: integer
          minimum: 1
        service_name:
          type: string
        paid_till:
          type: string
          format: date
        status:
          type: string
          enum:
          - expired
          - month_limit_reached
          - day_limit_reached
          - expiring
          - active
        trial:
          type: boolean
        day_remaining:
          type: integer
          minimum: 0
          description: Неизрасходованная дневная квота. Для истёкшей подписки равна 0.
        month_remaining:
          type: [integer, 'null']
          minimum: 0
          description: Неизрасходованная месячная квота. null при отсутствии месячного ограничения, 0 для истёкшей подписки.
        day_used:
          type: integer
          minimum: 0
        day_limit:
          type: integer
          minimum: 0
        month_used:
          type: integer
          minimum: 0
        month_limit:
          type: integer
          minimum: 0
        can_prolong:
          type: boolean
          description: Есть доступный тариф ручного продления.
      required:
      - id
      - service_id
      - service_name
      - paid_till
      - status
      - trial
      - day_remaining
      - month_remaining
      - day_used
      - day_limit
      - month_used
      - month_limit
      - can_prolong
      additionalProperties: false
    InvoiceSummary:
      type: object
      properties:
        id:
          type: integer
          minimum: 1
        number:
          type: string
          description: Отображаемый номер счёта. Поиск принимает также ID счёта и номер бухгалтерского счёта.
        created_at:
          type: string
          format: date-time
        total:
          $ref: '#/components/schemas/Money'
        status:
          $ref: '#/components/schemas/InvoiceStatus'
        auto_created:
          type: boolean
          description: true у автоматически выставленного счёта.
        services:
          type: array
          items:
            type: string
          description: Названия сервисов по позициям счёта в порядке строк.
      required:
      - id
      - number
      - created_at
      - total
      - status
      - auto_created
      - services
      additionalProperties: false
