openapi: 3.1.0
info:
  title: Открытый API, версия 1
  version: '1.0'
  description: |
    API организации: 1С (любая конфигурация) или любая система загружает товары, цены и остатки
    и забирает заказы с площадок. Токен выдаёт владелец или администратор в кабинете, раздел «API и 1С».

    Каждый запрос — с заголовком `Authorization: Bearer <токен>`, данные — JSON в UTF-8.
    До 120 запросов в минуту на токен; превышение — 429 и заголовок `Retry-After`.

    Ошибки — одним видом: `{"error": {"code", "message", "fields"?}}`. `code` не меняется — по нему
    программа решает, что делать; `message` — текст для человека.
servers:
- url: /api/v1
security:
- token: []
paths:
  /ping:
    get:
      summary: Проверка подключения
      description: Токен принят — в ответе организация, от имени которой работают запросы.
      responses:
        '200':
          description: Подключено
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      organization:
                        type: object
                        properties:
                          name:
                            type: string
                      token:
                        type: object
                        properties:
                          name:
                            type: string
                          tail:
                            type: string
                      api_version:
                        type: string
                        example: v1
                      server_time:
                        type: string
                        format: date-time
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /products:
    get:
      summary: Товары — список по курсору
      description: |
        По возрастанию id. Следующая страница — `after_id` из `meta.next_after_id`; null — страниц больше нет.
        Остаток обычного товара — из учётной системы (`stock_source: erp`), цифрового — свободные ключи (`keys`).
      parameters:
      - name: after_id
        in: query
        schema:
          type: integer
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 100
      - name: erp_id
        in: query
        schema:
          type: string
      - name: sku
        in: query
        schema:
          type: string
      - name: updated_since
        in: query
        schema:
          type: string
          format: date-time
      responses:
        '200':
          description: Страница товаров
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Product'
                  meta:
                    type: object
                    properties:
                      next_after_id:
                        type:
                        - integer
                        - 'null'
        '401':
          $ref: '#/components/responses/Unauthenticated'
    put:
      summary: Товары — записать пакетом (до 500)
      description: |
        Товар находится по `erp_id`; нет такого — по `sku` (товар из кабинета переходит под учётную систему);
        нет и его — создаётся в пределах тарифа. Название, артикул и цена продажи — поля учётной
        системы; `is_digital` учитывается только при создании. Остатки — отдельно, `PUT /stocks` по складам. Итог — по каждой позиции в том же порядке:
        ошибка в одной позиции не отменяет остальные.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - items
              properties:
                items:
                  type: array
                  maxItems: 500
                  items:
                    type: object
                    required:
                    - erp_id
                    - title
                    properties:
                      erp_id:
                        type: string
                        maxLength: 100
                        example: 00-00001234
                      sku:
                        type: string
                        maxLength: 100
                        example: BOOK-MP-2
                      title:
                        type: string
                        maxLength: 255
                      price:
                        type: number
                        minimum: 0
                        example: 890
                      is_digital:
                        type: boolean
                        default: false
                        description: Только при создании
      responses:
        '200':
          $ref: '#/components/responses/BatchResult'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /products/{id}:
    get:
      summary: Один товар
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      responses:
        '200':
          description: Товар
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/Product'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      summary: Настройки товара, которые ведёт сервис
      description: |
        Только переданные поля. Выдача, ключи и инструкция — только у
        цифрового товара; страница получения — на тарифах с выдачей ключей. Ответ — товар целиком.
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                auto_fulfill:
                  type: boolean
                generates_codes:
                  type: boolean
                delivery_method:
                  type: string
                  enum:
                  - marketplace_key
                  - redemption_page
                redemption_includes_key:
                  type: boolean
                activation_url:
                  type:
                  - string
                  - 'null'
                activation_instructions:
                  type:
                  - string
                  - 'null'
                  maxLength: 2000
                archived:
                  type: boolean
      responses:
        '200':
          description: Товар
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /prices:
    put:
      summary: Цены продажи — пакетом (до 500)
      description: Позиция — `erp_id` или `sku` и `price`. «Нашу цену» для защиты цены ведёт сервис, здесь её нет.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - items
              properties:
                items:
                  type: array
                  maxItems: 500
                  items:
                    type: object
                    required:
                    - price
                    properties:
                      erp_id:
                        type: string
                      sku:
                        type: string
                      price:
                        type: number
                        minimum: 0
      responses:
        '200':
          $ref: '#/components/responses/BatchResult'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /stocks:
    put:
      summary: Остатки по складам — пакетом (до 500)
      description: |
        Позиция — `erp_id` или `sku`, код склада учётной системы `warehouse` и `stock`. Склад с новым кодом
        заводится сам (название — код, уточняется `PUT /warehouses`). Остаток товара — сумма по складам.
        В кабинете продавец выбирает, остаток какого склада отправлять на каждый склад FBS площадки.
        Только обычные товары: остаток цифрового — его свободные ключи (позиция вернёт `not_allowed`).

        **Кто ведёт остатки.** Принимается, только пока в настройках «Склады и остатки» хозяин остатков — «В 1С»
        (`stock_source = erp`). Если выбрано «В сервисе», весь запрос отвечает 409 с кодом
        `stocks_managed_in_service`; чтение (`GET /warehouses`, `GET /stock-movements`) работает всегда.

        **Что присылать.** Свободный остаток: сколько на складе минус то, что 1С уже зарезервировала и отгрузила
        сама. Сервис вычитает из него только резерв по заказам, которых 1С ещё не подтвердила
        (`POST /orders/ack` означает «заказ создан в 1С и учтён в её остатке»). Поэтому порядок в сеансе обмена
        такой: сначала забрать заказы (`GET /orders`), затем подтвердить загруженные (`POST /orders/ack`),
        и только потом отправить остатки.

        **Режим «Один склад на все магазины».** Принимается остаток только одного склада. Если у единственного
        склада кода ещё нет, он принимает первый присланный код; склад с другим кодом — ошибка позиции
        `single_warehouse` (остальные позиции применяются). Смените режим в кабинете или передавайте один склад.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - items
              properties:
                items:
                  type: array
                  maxItems: 500
                  items:
                    type: object
                    required:
                    - warehouse
                    - stock
                    properties:
                      erp_id:
                        type: string
                      sku:
                        type: string
                      warehouse:
                        type: string
                        maxLength: 100
                        example: '001'
                        description: Код склада в учётной системе
                      stock:
                        type: integer
                        minimum: 0
      responses:
        '200':
          $ref: '#/components/responses/BatchResult'
        '409':
          $ref: '#/components/responses/StocksManagedInService'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /stock-movements:
    get:
      summary: Журнал движений остатков (чтение)
      description: |
        Что и почему менялось на складах обычных товаров: ручная правка, файл, сверка, отгрузка, возврат,
        списание, обмен с 1С. По возрастанию `id`; `after_id` — последний `id` предыдущей страницы,
        `meta.next_after_id` — откуда продолжить (`null` — это конец). На странице до 500 записей.
        `delta` — на сколько изменился остаток «на складе» (может быть отрицательным), `quantity_after` — сколько
        стало. `reason`: `manual`, `file`, `reconcile`, `shipment`, `return_restock`, `writeoff`, `erp` и другие;
        список может пополняться. Работает при любом хозяине остатков. Склад можно удалить, а запись остаётся:
        тогда `warehouse.id` и `warehouse.code` — `null`, `warehouse.name` — название склада на момент движения.
      parameters:
      - name: after_id
        in: query
        schema:
          type: integer
          minimum: 0
      - name: product_id
        in: query
        description: Только движения этого товара
        schema:
          type: integer
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 500
          default: 500
      responses:
        '200':
          description: Движения
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id:
                          type: integer
                        product_id:
                          type: integer
                        erp_id:
                          type:
                          - string
                          - 'null'
                        sku:
                          type:
                          - string
                          - 'null'
                        warehouse:
                          type: object
                          properties:
                            id:
                              type:
                              - integer
                              - 'null'
                            code:
                              type:
                              - string
                              - 'null'
                            name:
                              type:
                              - string
                              - 'null'
                        delta:
                          type: integer
                        quantity_after:
                          type: integer
                        reason:
                          type: string
                        order_id:
                          type:
                          - integer
                          - 'null'
                        order_number:
                          type:
                          - string
                          - 'null'
                        comment:
                          type:
                          - string
                          - 'null'
                        created_at:
                          type: string
                          format: date-time
                  meta:
                    type: object
                    properties:
                      next_after_id:
                        type:
                        - integer
                        - 'null'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /warehouses:
    get:
      summary: Склады учётной системы
      description: Склады и к каким складам FBS площадок их привязал продавец в кабинете.
      responses:
        '200':
          description: Склады
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id:
                          type: integer
                        code:
                          type: string
                        name:
                          type: string
                        marketplace_warehouses:
                          type: array
                          items:
                            type: object
                            properties:
                              shop_id:
                                type: integer
                              shop:
                                type: string
                              external_id:
                                type: string
                              name:
                                type: string
    put:
      summary: Названия складов учётной системы — пакетом
      description: |
        Как и `PUT /stocks`, принимается только при хозяине остатков «В 1С»; иначе 409 `stocks_managed_in_service`.
        В режиме «Один склад на все магазины» код второго склада — ошибка позиции `single_warehouse`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - items
              properties:
                items:
                  type: array
                  maxItems: 500
                  items:
                    type: object
                    required:
                    - code
                    - name
                    properties:
                      code:
                        type: string
                        maxLength: 100
                      name:
                        type: string
                        maxLength: 255
      responses:
        '200':
          $ref: '#/components/responses/BatchResult'
        '409':
          $ref: '#/components/responses/StocksManagedInService'
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /shops:
    get:
      summary: Магазины — только чтение
      description: Ключи API площадок не отдаются никогда. `state` — ok, expiring, failed, unchecked, disabled.
      responses:
        '200':
          description: Магазины
  /listings:
    get:
      summary: Предложения магазинов — цены на площадке и «наша цена»
      parameters:
      - name: after_id
        in: query
        schema:
          type: integer
      - name: limit
        in: query
        schema:
          type: integer
          maximum: 200
          default: 100
      - name: shop_id
        in: query
        schema:
          type: integer
      - name: product_id
        in: query
        schema:
          type: integer
      responses:
        '200':
          description: Страница предложений; meta.next_after_id — курсор
  /our-prices:
    put:
      summary: «Наша цена» для защиты цены — пакетом (до 500)
      description: Позиция — `listing_id` или `shop_id` + `external_sku`, и `our_price` (null — снять защиту цены). Поле сервиса.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - items
              properties:
                items:
                  type: array
                  maxItems: 500
                  items:
                    type: object
                    required:
                    - our_price
                    properties:
                      listing_id:
                        type: integer
                      shop_id:
                        type: integer
                      external_sku:
                        type: string
                      our_price:
                        type:
                        - number
                        - 'null'
                        minimum: 0
      responses:
        '200':
          $ref: '#/components/responses/BatchResult'
  /products/{id}/keys:
    get:
      summary: Запас ключей товара — без самих ключей
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      responses:
        '200':
          description: free, issued, promised (обещано неоткрытым кодам покупки)
    post:
      summary: Загрузить ключи товара
      description: До 10 000 за раз. Ключ не меняется, кроме пробелов по краям; дубли и уже загруженные пропускаются. Ключи
        API не отдаёт никогда.
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - codes
              properties:
                codes:
                  type: array
                  maxItems: 10000
                  items:
                    type: string
                    maxLength: 255
      responses:
        '200':
          description: added — загружено, skipped — пропущено
  /products/{id}/materials:
    get:
      summary: Материалы товара для страницы получения
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      responses:
        '200':
          description: Материалы по порядку
    post:
      summary: Добавить материал — ссылку или файл
      description: JSON `{label, url}` — ссылка (только https); multipart `file` (+ `label`) — файл в пределах тарифа.
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                label:
                  type: string
                url:
                  type: string
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
                label:
                  type: string
      responses:
        '201':
          description: Материал
        '422':
          $ref: '#/components/responses/ValidationFailed'
  /materials/{id}:
    delete:
      summary: Удалить материал (и файл)
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      responses:
        '200':
          description: Удалён
  /orders:
    get:
      summary: Заказы — лента изменений по курсору
      description: |
        Заказы, изменившиеся после `since_version`, по возрастанию `sync_version`. Храните у себя
        `meta.next_since_version` и передавайте его в следующий раз; `has_more: true` — запросите ещё.
        Обрыв связи ничего не теряет: курсор сдвигаете вы. Ключи и коды покупки в ответ не попадают.
      parameters:
      - name: since_version
        in: query
        schema:
          type: integer
          default: 0
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 100
      - name: not_exported
        in: query
        schema:
          type: boolean
        description: Только ещё не загруженные в учётную систему или изменённые после загрузки
      - name: status
        in: query
        schema:
          type: string
          enum:
          - new
          - in_progress
          - done
          - cancelled
      responses:
        '200':
          description: Страница ленты
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Order'
                  meta:
                    type: object
                    properties:
                      next_since_version:
                        type: integer
                      has_more:
                        type: boolean
  /orders/{id}:
    get:
      summary: Один заказ
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
      responses:
        '200':
          description: Заказ
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/Order'
        '404':
          $ref: '#/components/responses/NotFound'
  /orders/ack:
    post:
      summary: Подтвердить загрузку заказов в учётную систему
      description: |
        `version` — тот `sync_version`, который вы загрузили; `erp_id` — номер документа у вас.
        Если заказ изменился позже, он останется в ленте с `erp.needs_export: true`.
        Подтверждение версию заказа не меняет.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - items
              properties:
                items:
                  type: array
                  maxItems: 500
                  items:
                    type: object
                    required:
                    - id
                    - version
                    properties:
                      id:
                        type: integer
                      version:
                        type: integer
                      erp_id:
                        type: string
                        maxLength: 100
                        example: РН-000123
      responses:
        '200':
          description: 'Итог по каждой позиции: acknowledged или error (invalid, not_found, invalid_version)'
        '422':
          $ref: '#/components/responses/ValidationFailed'
components:
  securitySchemes:
    token:
      type: http
      scheme: bearer
      description: Токен организации, начинается с `api_`.
  schemas:
    Order:
      type: object
      properties:
        id:
          type: integer
        sync_version:
          type: integer
        number:
          type: string
          description: Номер заказа на площадке
        external_id:
          type: string
        shop:
          type: object
          properties:
            id:
              type: integer
            name:
              type: string
            channel:
              type: string
              example: ozon
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        status:
          type: string
          enum:
          - new
          - in_progress
          - done
          - cancelled
        marketplace_status:
          type:
          - string
          - 'null'
        fulfillment:
          type:
          - string
          - 'null'
          enum:
          - pending
          - manual
          - sending
          - sent
          - sent_elsewhere
          - failed
          - null
        scheme:
          type:
          - string
          - 'null'
          enum:
          - fbs
          - rfbs
          - fbo
          - null
          description: 'Схема: fbs и rfbs — отгружает продавец (позиции обычных товаров в резерве склада до отгрузки), fbo — со склада площадки, наш остаток не трогает. null — площадка схему не сообщила.'
        ship_by:
          type:
          - string
          - 'null'
          format: date-time
          description: Срок сборки или отгрузки, который поставила площадка. У Wildberries в API его нет — null.
        warehouse:
          type:
          - object
          - 'null'
          description: Наш склад (склад 1С), с которого отгружается заказ, — по складу FBS магазина. null — у FBO, или склад площадки не сопоставлен.
          properties:
            code:
              type:
              - string
              - 'null'
            name:
              type: string
        shipped_at:
          type:
          - string
          - 'null'
          format: date-time
          description: Когда сервис увидел заказ отгруженным (площадка перевела его в доставку). С этого момента заказ не в резерве. Если остатки ведёт сервис, позиции списываются со склада (движение «Отгрузка заказа» в журнале) — только у заказа FBS/rFBS, который до отгрузки был у нас в резерве, и со сопоставленного склада. Заказ, который сервис впервые увидел уже отгруженным (история при подключении магазина, заказ, созданный и отгруженный между двумя загрузками), не списывается — `shipped_at` у него есть, движения нет. В режиме «В 1С» сервис не списывает никогда.
        buyer:
          type:
          - object
          - 'null'
          properties:
            name:
              type: string
            phone:
              type: string
            email:
              type: string
        total:
          type: string
          example: '900.00'
        items:
          type: array
          items:
            type: object
            properties:
              product_id:
                type:
                - integer
                - 'null'
              erp_id:
                type:
                - string
                - 'null'
              sku:
                type:
                - string
                - 'null'
              title:
                type: string
              quantity:
                type: integer
              price:
                type: string
                example: '450.00'
              return_decision:
                type:
                - string
                - 'null'
                enum: [pending, restock, write_off, null]
                description: |
                  Возврат обычного товара: `pending` — продавец ещё не решил, `restock` — «Годен» (вернулся на склад),
                  `write_off` — «Брак». `null` — возврата нет. Если остатки ведёт 1С, сервис склад не меняет — вернуть
                  остаток по `restock` должна 1С.
              return_decided_at:
                type:
                - string
                - 'null'
                format: date-time
        erp:
          type: object
          properties:
            id:
              type:
              - string
              - 'null'
            exported_version:
              type:
              - integer
              - 'null'
            exported_at:
              type:
              - string
              - 'null'
              format: date-time
            needs_export:
              type: boolean
    Product:
      type: object
      properties:
        id:
          type: integer
        erp_id:
          type:
          - string
          - 'null'
        sku:
          type:
          - string
          - 'null'
        title:
          type: string
        is_digital:
          type: boolean
        price:
          type:
          - string
          - 'null'
          example: '890.00'
          description: Цена продажи из учётной системы — строкой
        stock:
          type:
          - integer
          - 'null'
          description: Остаток — у обычного товара сумма «на складе» по всем складам (может быть отрицательной, если продано больше, чем было на складе), у цифрового — свободные ключи
        stock_source:
          type: string
          enum:
          - erp
          - keys
        stock_updated_at:
          type:
          - string
          - 'null'
          format: date-time
          description: Когда в последний раз изменилось число остатка (любое движение — обмен с 1С, правка, файл, отгрузка, возврат). Обмен с 1С, который прислал то же число, время не меняет — это не время последнего обмена
        stocks:
          type: array
          description: Остаток обычного товара по складам учётной системы
          items:
            type: object
            properties:
              warehouse:
                type: string
              stock:
                type: integer
                description: «На складе» по этому складу; может быть отрицательным (продано больше, чем было)
        delivery_method:
          type:
          - string
          - 'null'
          enum:
          - marketplace_key
          - redemption_page
          - null
        archived:
          type: boolean
        updated_at:
          type: string
          format: date-time
        listings:
          type: array
          items:
            type: object
            properties:
              shop_id:
                type: integer
              shop:
                type: string
              channel:
                type: string
                example: ozon
              external_sku:
                type:
                - string
                - 'null'
              price:
                type:
                - string
                - 'null'
              our_price:
                type:
                - string
                - 'null'
                description: «Наша цена» для защиты цены — поле сервиса
              market_price:
                type:
                - string
                - 'null'
    BatchItemResult:
      type: object
      properties:
        index:
          type: integer
          description: Номер позиции в запросе, с нуля
        erp_id:
          type:
          - string
          - 'null'
        sku:
          type:
          - string
          - 'null'
        id:
          type: integer
        result:
          type: string
          enum:
          - created
          - updated
          - unchanged
          - error
        error:
          type: object
          properties:
            code:
              type: string
              enum:
              - invalid
              - sku_taken
              - tariff_limit
              - not_found
              - not_allowed
            message:
              type: string
            fields:
              type: object
              additionalProperties:
                type: array
                items:
                  type: string
    Error:
      type: object
      required:
      - error
      properties:
        error:
          type: object
          required:
          - code
          - message
          properties:
            code:
              type: string
              example: validation_failed
            message:
              type: string
            fields:
              type: object
              additionalProperties:
                type: array
                items:
                  type: string
  responses:
    BatchResult:
      description: Итог по каждой позиции
      content:
        application/json:
          schema:
            type: object
            properties:
              data:
                type: array
                items:
                  $ref: '#/components/schemas/BatchItemResult'
              meta:
                type: object
                properties:
                  created:
                    type: integer
                  updated:
                    type: integer
                  unchanged:
                    type: integer
                  errors:
                    type: integer
    StocksManagedInService:
      description: Остатки ведутся в сервисе (`stock_source = service`), запись из 1С не принимается. Код `stocks_managed_in_service`
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    ValidationFailed:
      description: Запрос целиком неверен (нет items, больше 500 позиций)
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    NotFound:
      description: Нет такого (или он другой организации)
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthenticated:
      description: Нет токена или он отозван
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    TooManyRequests:
      description: Больше 120 запросов в минуту на токен
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
