{
  "openapi": "3.2.0",
  "info": {
    "title": "ArdorFishing — Seller Integration API",
    "version": "1.0.0",
    "description": "REST API для автоматического обновления цен, активности и остатков товаров продавца\nиз его учётной системы (push-модель). Альтернатива — загрузка YML-фида, у продавца\nодновременно может работать только одна модель.\n\n## Как начать\n1. В панели продавца откройте раздел **Интеграция**, выберите модель **REST API** и сохраните.\n2. В блоке **API-ключи** создайте ключ с нужными правами. Полный ключ показывается один раз — сохраните его.\n3. Проверьте ключ запросом `GET /ping`.\n\n## Аутентификация\nКлюч передаётся в заголовке `X-Api-Key` или `Authorization: Bearer <ключ>`.\nФормат ключа: `afk_<8 символов>_<40 символов>`. Ключ работает, только пока у продавца\nвключена модель REST API.\n\nAPI-ключи создаются в разделе [«Интеграция»](https://seller.ardorfishing.com/integration) панели продавца.\n\n| Право | Что разрешает |\n|---|---|\n| `products:write` | цены, зачёркнутые цены и активность товаров |\n| `stocks:write` | физические остатки на складах |\n\n## Что обновляется\nТолько **существующие** товары продавца, сопоставление по артикулу (SKU) без учёта регистра.\nНовые товары через API не создаются — их заводят в панели продавца или импортом Excel.\n\n## Модель остатков\n* `quantity` — физический остаток на складе продавца, **включая** единицы оплаченных заказов,\n  которые ещё не переданы перевозчику. Его можно перезаписывать снимком из учётной системы.\n* `reserved` — единицы заказов, ещё не переданных перевозчику. Ведётся площадкой, через API не меняется.\n* Доступно к продаже: `max(0, quantity − reserved)`.\n* При передаче отправления перевозчику площадка уменьшает и `quantity`, и `reserved` на количество в заказе.\n\n## Частичный успех\nПакет применяется настолько, насколько возможно: проблемы отдельных позиций возвращаются\nв `issues`, остальные позиции применяются. Структурно неверный запрос (типы, лимиты)\nотклоняется целиком с кодом 422.\n\n## Полная выгрузка и деактивация отсутствующих\nБез `session_id` каждый запрос — частичное обновление. Чтобы передать полный снимок каталога,\nоткройте сессию, отправьте все позиции пачками с её `session_id` и завершите сессию.\nЕсли у продавца включён флаг «Деактивировать всё, чего нет в выгрузке», при завершении\nактивные товары, не упомянутые ни в одной пачке сессии, снимаются с продажи.\nЗащита: ничего не деактивируется, если сессия пустая или из неё пропало больше 50 %\nактивных товаров. Снятые так товары возвращаются в продажу автоматически при следующем упоминании.\n\n## Лимиты\n* До 1000 позиций в одном запросе.\n* До 120 запросов в минуту на продавца (на все ключи вместе).\n* Сессия живёт 6 часов с момента открытия.\n\n## Язык сообщений\nЗаголовок `X-Locale: ru` или `X-Locale: en` (по умолчанию — русский).\n"
  },
  "servers": [
    {
      "url": "https://api.ardorfishing.com/seller-integration/v1",
      "description": "Боевой сервер"
    },
    {
      "url": "https://dev-api.ardorfishing.com/seller-integration/v1",
      "description": "Тестовый сервер"
    }
  ],
  "security": [
    {
      "ApiKeyHeader": []
    },
    {
      "BearerKey": []
    }
  ],
  "tags": [
    {
      "name": "Service",
      "description": "Проверка ключа и чтение текущего состояния"
    },
    {
      "name": "Updates",
      "description": "Обновление цен, активности и остатков"
    },
    {
      "name": "Sessions",
      "description": "Полная выгрузка каталога пачками"
    }
  ],
  "paths": {
    "/ping": {
      "get": {
        "tags": [
          "Service"
        ],
        "operationId": "ping",
        "summary": "Проверить ключ",
        "description": "Возвращает продавца, права ключа, склады и лимиты. Подходит любой действующий ключ.",
        "parameters": [
          {
            "$ref": "#/components/parameters/Locale"
          }
        ],
        "responses": {
          "200": {
            "description": "Ключ действителен",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PingResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/Maintenance"
          }
        }
      }
    },
    "/products": {
      "get": {
        "tags": [
          "Service"
        ],
        "operationId": "listProducts",
        "summary": "Текущее состояние товаров",
        "description": "Цены, активность и остатки по складам с резервами. Удобно для сверки с учётной системой.\nПодходит любой действующий ключ.\n",
        "parameters": [
          {
            "$ref": "#/components/parameters/Locale"
          },
          {
            "name": "sku[]",
            "in": "query",
            "description": "Фильтр по артикулам, до 1000 значений",
            "required": false,
            "style": "form",
            "explode": true,
            "schema": {
              "type": "array",
              "maxItems": 1000,
              "items": {
                "type": "string",
                "maxLength": 64
              }
            }
          },
          {
            "name": "page",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "per_page",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 1000,
              "default": 100
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Страница товаров",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProductsListResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "422": {
            "$ref": "#/components/responses/ValidationError"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/Maintenance"
          }
        }
      },
      "post": {
        "tags": [
          "Updates"
        ],
        "operationId": "updateProducts",
        "summary": "Обновить цены и активность",
        "description": "Требуется право `products:write`.\n\n* `price` — новая цена. Не передана — цена не меняется.\n* `old_price` — зачёркнутая цена. `null` убирает её, отсутствие поля оставляет как есть.\n  Если она не больше цены, зачёркнутая цена убирается с предупреждением `old_price_not_greater`, а цена применяется.\n* `is_active` — явное решение вашей системы: включить или снять товар с продажи.\n  Такое решение окончательное, деактивация по полной выгрузке его не переопределяет.\n\nПозиция только с `sku` допустима: в сессии она отмечает товар как присутствующий в выгрузке.\nЕсли артикул повторяется в одном запросе, применяется первое вхождение.\n",
        "parameters": [
          {
            "$ref": "#/components/parameters/Locale"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProductsBatchRequest"
              },
              "examples": {
                "prices": {
                  "summary": "Цены и активность",
                  "value": {
                    "items": [
                      {
                        "sku": "ABC-123",
                        "price": 1990,
                        "old_price": 2490
                      },
                      {
                        "sku": "ABC-124",
                        "price": 990,
                        "old_price": null
                      },
                      {
                        "sku": "ABC-125",
                        "is_active": false
                      }
                    ]
                  }
                },
                "inSession": {
                  "summary": "Пачка полной выгрузки",
                  "value": {
                    "session_id": 412,
                    "items": [
                      {
                        "sku": "ABC-123",
                        "price": 1990
                      }
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Пакет обработан (возможно, частично — смотрите `issues`)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BatchResponse"
                },
                "example": {
                  "run_id": 1051,
                  "session_id": null,
                  "stats": {
                    "received": 3,
                    "unknown": 1,
                    "invalid": 0,
                    "duplicates": 0,
                    "prices_updated": 1,
                    "stocks_updated": 0,
                    "activated": 0,
                    "deactivated": 1,
                    "reactivated": 0
                  },
                  "issues": [
                    {
                      "sku": "ABC-124",
                      "code": "sku_not_found",
                      "message": "Товар с таким артикулом не найден у продавца."
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "409": {
            "$ref": "#/components/responses/SessionNotOpen"
          },
          "422": {
            "$ref": "#/components/responses/ValidationError"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/Maintenance"
          }
        }
      }
    },
    "/stocks": {
      "post": {
        "tags": [
          "Updates"
        ],
        "operationId": "updateStocks",
        "summary": "Обновить остатки",
        "description": "Требуется право `stocks:write`.\n\n`quantity` — физический остаток на складе, **включая** единицы оплаченных заказов, ещё не\nпереданных перевозчику. Площадка держит такие единицы в резерве и продаёт `quantity − reserved`.\nЕсли переданный остаток меньше резерва, он всё равно применяется, а в `issues` приходит\nпредупреждение `quantity_below_reserved`: проверьте оплаченные заказы по этому товару.\n\n`warehouse` — код склада из `GET /ping`. Не передан — используется основной склад продавца.\nОдин артикул можно передать для разных складов в одном запросе.\n",
        "parameters": [
          {
            "$ref": "#/components/parameters/Locale"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StocksBatchRequest"
              },
              "example": {
                "items": [
                  {
                    "sku": "ABC-123",
                    "quantity": 12
                  },
                  {
                    "sku": "ABC-124",
                    "quantity": 0,
                    "warehouse": "MSK-1"
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Пакет обработан (возможно, частично — смотрите `issues`)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BatchResponse"
                },
                "example": {
                  "run_id": 1052,
                  "session_id": null,
                  "stats": {
                    "received": 2,
                    "unknown": 0,
                    "invalid": 0,
                    "duplicates": 0,
                    "prices_updated": 0,
                    "stocks_updated": 2,
                    "activated": 0,
                    "deactivated": 0,
                    "reactivated": 0
                  },
                  "issues": [
                    {
                      "sku": "ABC-123",
                      "code": "quantity_below_reserved",
                      "message": "Остаток 12 меньше зарезервированного под оплаченные заказы (14)."
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "409": {
            "$ref": "#/components/responses/SessionNotOpen"
          },
          "422": {
            "$ref": "#/components/responses/ValidationError"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/Maintenance"
          }
        }
      }
    },
    "/sessions": {
      "post": {
        "tags": [
          "Sessions"
        ],
        "operationId": "openSession",
        "summary": "Открыть сессию полной выгрузки",
        "description": "Требуется право `products:write` или `stocks:write`.\nСессия живёт 6 часов. У продавца одновременно открыта одна сессия:\nновая отменяет предыдущую незавершённую.\n",
        "parameters": [
          {
            "$ref": "#/components/parameters/Locale"
          }
        ],
        "responses": {
          "201": {
            "description": "Сессия открыта",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "session"
                  ],
                  "properties": {
                    "session": {
                      "$ref": "#/components/schemas/Session"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/Maintenance"
          }
        }
      }
    },
    "/sessions/{session}": {
      "get": {
        "tags": [
          "Sessions"
        ],
        "operationId": "showSession",
        "summary": "Состояние сессии",
        "description": "Счётчики и найденные проблемы (до 200 записей). Требуется право `products:write` или `stocks:write`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/Locale"
          },
          {
            "$ref": "#/components/parameters/SessionId"
          }
        ],
        "responses": {
          "200": {
            "description": "Сессия",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "session"
                  ],
                  "properties": {
                    "session": {
                      "$ref": "#/components/schemas/SessionWithIssues"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/SessionNotFound"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/Maintenance"
          }
        }
      }
    },
    "/sessions/{session}/complete": {
      "post": {
        "tags": [
          "Sessions"
        ],
        "operationId": "completeSession",
        "summary": "Завершить сессию",
        "description": "Требуется право `products:write` или `stocks:write`.\nЕсли у продавца включён флаг «Деактивировать всё, чего нет в выгрузке», активные товары,\nне упомянутые ни в одной пачке сессии (ни в `/products`, ни в `/stocks`), снимаются с продажи.\nРезультат — в поле `deactivation`.\n",
        "parameters": [
          {
            "$ref": "#/components/parameters/Locale"
          },
          {
            "$ref": "#/components/parameters/SessionId"
          }
        ],
        "responses": {
          "200": {
            "description": "Сессия завершена",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "session",
                    "deactivation"
                  ],
                  "properties": {
                    "session": {
                      "$ref": "#/components/schemas/SessionWithIssues"
                    },
                    "deactivation": {
                      "$ref": "#/components/schemas/DeactivationResult"
                    }
                  }
                },
                "example": {
                  "session": {
                    "id": 412,
                    "created_at": "2026-11-21T09:00:00.000000Z",
                    "source": "api",
                    "status": "completed",
                    "is_snapshot": true,
                    "stats": {
                      "received": 2380,
                      "unknown": 4,
                      "invalid": 0,
                      "duplicates": 0,
                      "prices_updated": 112,
                      "stocks_updated": 948,
                      "activated": 0,
                      "deactivated": 17,
                      "reactivated": 3
                    },
                    "issues": [],
                    "issues_count": 0,
                    "error": null,
                    "started_at": "2026-11-21T09:00:00.000000Z",
                    "finished_at": "2026-11-21T09:07:41.000000Z",
                    "expires_at": "2026-11-21T15:00:00.000000Z"
                  },
                  "deactivation": {
                    "deactivated": 17,
                    "skipped": null
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/SessionNotFound"
          },
          "409": {
            "$ref": "#/components/responses/SessionNotOpen"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/Maintenance"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKeyHeader": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Api-Key",
        "description": "Ключ из панели продавца: afk_xxxxxxxx_<40 символов>"
      },
      "BearerKey": {
        "type": "http",
        "scheme": "bearer",
        "description": "Тот же ключ в заголовке Authorization"
      }
    },
    "parameters": {
      "Locale": {
        "name": "X-Locale",
        "in": "header",
        "required": false,
        "description": "Язык сообщений об ошибках и проблемах",
        "schema": {
          "type": "string",
          "enum": [
            "ru",
            "en"
          ],
          "default": "ru"
        }
      },
      "SessionId": {
        "name": "session",
        "in": "path",
        "required": true,
        "description": "ID сессии из ответа `POST /sessions`",
        "schema": {
          "type": "integer",
          "minimum": 1
        }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Ключ не передан (`api_key_missing`), не найден (`api_key_invalid`),\nотозван (`api_key_revoked`) или истёк (`api_key_expired`).\n",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "API-ключ отозван.",
              "type": "api_key_revoked"
            }
          }
        }
      },
      "Forbidden": {
        "description": "У продавца не включена модель REST API (`integration_mode_not_api`)\nили у ключа нет нужного права (`api_key_scope_missing`).\n",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "У API-ключа нет нужного права: stocks:write.",
              "type": "api_key_scope_missing"
            }
          }
        }
      },
      "SessionNotFound": {
        "description": "Сессия не найдена или принадлежит другому продавцу",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "Сессия не найдена.",
              "type": "session_not_found"
            }
          }
        }
      },
      "SessionNotOpen": {
        "description": "Сессия уже завершена, отменена или истекла — откройте новую",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "Сессия уже завершена, отменена или истекла.",
              "type": "session_not_open"
            }
          }
        }
      },
      "ValidationError": {
        "description": "Запрос структурно неверен (типы полей, лимиты) и отклонён целиком",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ValidationError"
            },
            "example": {
              "message": "Поле items.0.price должно быть не меньше 0,01.",
              "errors": {
                "items.0.price": [
                  "Поле items.0.price должно быть не меньше 0,01."
                ]
              }
            }
          }
        }
      },
      "TooManyRequests": {
        "description": "Превышен лимит 120 запросов в минуту на продавца — подождите и повторите",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "Слишком много запросов, повторите позже.",
              "type": "too_many_requests"
            }
          }
        }
      },
      "Maintenance": {
        "description": "Технические работы. Повторите после паузы из заголовка `Retry-After` (секунды)",
        "headers": {
          "Retry-After": {
            "schema": {
              "type": "integer",
              "examples": [
                600
              ]
            }
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "error": {
                  "type": "string",
                  "examples": [
                    "maintenance"
                  ]
                }
              }
            }
          }
        }
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": [
          "error",
          "type"
        ],
        "properties": {
          "error": {
            "type": "string",
            "description": "Сообщение на языке из X-Locale"
          },
          "type": {
            "type": "string",
            "description": "Машиночитаемый код ошибки",
            "enum": [
              "api_key_missing",
              "api_key_invalid",
              "api_key_revoked",
              "api_key_expired",
              "integration_mode_not_api",
              "api_key_scope_missing",
              "too_many_requests",
              "session_not_found",
              "session_not_open"
            ]
          }
        }
      },
      "ValidationError": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string"
          },
          "errors": {
            "type": "object",
            "additionalProperties": {
              "type": "array",
              "items": {
                "type": "string"
              }
            }
          }
        }
      },
      "Sku": {
        "type": "string",
        "maxLength": 64,
        "description": "Артикул товара продавца. Сравнивается без учёта регистра, пробелы по краям отбрасываются",
        "examples": [
          "ABC-123"
        ]
      },
      "ProductsBatchRequest": {
        "type": "object",
        "required": [
          "items"
        ],
        "properties": {
          "session_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "ID открытой сессии. Не передан — разовое частичное обновление"
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/ProductItem"
            }
          }
        }
      },
      "ProductItem": {
        "type": "object",
        "required": [
          "sku"
        ],
        "properties": {
          "sku": {
            "$ref": "#/components/schemas/Sku"
          },
          "price": {
            "type": "number",
            "format": "double",
            "minimum": 0.01,
            "maximum": 99999999,
            "description": "Цена в рублях",
            "examples": [
              1990
            ]
          },
          "old_price": {
            "type": [
              "number",
              "null"
            ],
            "format": "double",
            "minimum": 0.01,
            "maximum": 99999999,
            "description": "Зачёркнутая цена в рублях. null — убрать",
            "examples": [
              2490
            ]
          },
          "is_active": {
            "type": "boolean",
            "description": "Явно включить или снять товар с продажи"
          }
        }
      },
      "StocksBatchRequest": {
        "type": "object",
        "required": [
          "items"
        ],
        "properties": {
          "session_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "ID открытой сессии. Не передан — разовое частичное обновление"
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/StockItem"
            }
          }
        }
      },
      "StockItem": {
        "type": "object",
        "required": [
          "sku",
          "quantity"
        ],
        "properties": {
          "sku": {
            "$ref": "#/components/schemas/Sku"
          },
          "quantity": {
            "type": "integer",
            "minimum": 0,
            "maximum": 1000000,
            "description": "Физический остаток на складе, включая единицы оплаченных, но не отгруженных заказов",
            "examples": [
              12
            ]
          },
          "warehouse": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 255,
            "description": "Код склада. Не передан — основной склад продавца",
            "examples": [
              "MSK-1"
            ]
          }
        }
      },
      "Stats": {
        "type": "object",
        "description": "Счётчики обработки",
        "properties": {
          "received": {
            "type": "integer",
            "description": "Получено позиций"
          },
          "unknown": {
            "type": "integer",
            "description": "Артикул не найден у продавца"
          },
          "invalid": {
            "type": "integer",
            "description": "Пустой или слишком длинный артикул, неизвестный склад"
          },
          "duplicates": {
            "type": "integer",
            "description": "Повтор артикула в запросе, учтено первое вхождение"
          },
          "prices_updated": {
            "type": "integer",
            "description": "Изменено цен"
          },
          "stocks_updated": {
            "type": "integer",
            "description": "Изменено остатков"
          },
          "activated": {
            "type": "integer",
            "description": "Включено по явному is_active=true"
          },
          "deactivated": {
            "type": "integer",
            "description": "Снято с продажи (по is_active=false или при завершении сессии)"
          },
          "reactivated": {
            "type": "integer",
            "description": "Возвращено в продажу после деактивации по выгрузке"
          }
        }
      },
      "Issue": {
        "type": "object",
        "required": [
          "sku",
          "code",
          "message"
        ],
        "properties": {
          "sku": {
            "type": [
              "string",
              "null"
            ]
          },
          "code": {
            "type": "string",
            "enum": [
              "sku_invalid",
              "sku_duplicated",
              "sku_not_found",
              "price_invalid",
              "old_price_not_greater",
              "warehouse_not_found",
              "quantity_below_reserved",
              "deactivate_guard"
            ],
            "description": "* `sku_invalid` — пустой или длиннее 64 символов, позиция пропущена\n* `sku_duplicated` — повтор в запросе, учтено первое вхождение\n* `sku_not_found` — у продавца нет товара с таким артикулом, позиция пропущена\n* `price_invalid` — цена не больше нуля, цена не изменена\n* `old_price_not_greater` — зачёркнутая цена не больше цены и убрана, цена применена\n* `warehouse_not_found` — склад не найден, остаток не изменён\n* `quantity_below_reserved` — остаток применён, но он меньше резерва под оплаченные заказы\n* `deactivate_guard` — деактивация при завершении сессии отменена защитой\n"
          },
          "message": {
            "type": "string"
          }
        }
      },
      "BatchResponse": {
        "type": "object",
        "required": [
          "run_id",
          "session_id",
          "stats",
          "issues"
        ],
        "properties": {
          "run_id": {
            "type": "integer",
            "description": "ID записи в журнале синхронизаций (для сессии — ID сессии)"
          },
          "session_id": {
            "type": [
              "integer",
              "null"
            ]
          },
          "stats": {
            "$ref": "#/components/schemas/Stats"
          },
          "issues": {
            "type": "array",
            "description": "Все проблемы этого запроса",
            "items": {
              "$ref": "#/components/schemas/Issue"
            }
          }
        }
      },
      "Session": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "source": {
            "type": "string",
            "enum": [
              "api"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "running",
              "completed",
              "expired",
              "cancelled"
            ],
            "description": "* `open` — принимает пачки\n* `running` — идёт завершение\n* `completed` — завершена\n* `expired` — не завершена за 6 часов, ничего не деактивировано\n* `cancelled` — отменена: открыта новая сессия или выключена модель REST API\n"
          },
          "is_snapshot": {
            "type": "boolean"
          },
          "stats": {
            "$ref": "#/components/schemas/Stats"
          },
          "issues_count": {
            "type": "integer"
          },
          "error": {
            "type": [
              "string",
              "null"
            ]
          },
          "started_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "finished_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "expires_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          }
        }
      },
      "SessionWithIssues": {
        "allOf": [
          {
            "$ref": "#/components/schemas/Session"
          },
          {
            "type": "object",
            "properties": {
              "issues": {
                "type": "array",
                "description": "Первые 200 проблем за всю сессию",
                "items": {
                  "$ref": "#/components/schemas/Issue"
                }
              }
            }
          }
        ]
      },
      "DeactivationResult": {
        "type": "object",
        "required": [
          "deactivated",
          "skipped"
        ],
        "properties": {
          "deactivated": {
            "type": "integer",
            "description": "Сколько товаров снято с продажи"
          },
          "skipped": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "disabled",
              "empty_snapshot",
              "guard",
              null
            ],
            "description": "Почему деактивация не выполнялась:\n* `disabled` — флаг «Деактивировать всё, чего нет в выгрузке» выключен\n* `empty_snapshot` — в сессии не нашлось ни одного вашего товара\n* `guard` — пропало больше 50 % активных товаров, выгрузка сочтена неполной\n* `null` — деактивация выполнена (возможно, деактивировать было нечего)\n"
          }
        }
      },
      "Warehouse": {
        "type": "object",
        "properties": {
          "code": {
            "type": "string",
            "examples": [
              "MSK-1"
            ]
          },
          "name": {
            "type": "string"
          },
          "is_active": {
            "type": "boolean"
          }
        }
      },
      "PingResponse": {
        "type": "object",
        "properties": {
          "seller": {
            "type": "object",
            "properties": {
              "id": {
                "type": "integer"
              },
              "name": {
                "type": "string"
              },
              "code": {
                "type": "string"
              }
            }
          },
          "key": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string"
              },
              "prefix": {
                "type": "string",
                "examples": [
                  "k3m9x2ab"
                ]
              },
              "scopes": {
                "type": "array",
                "items": {
                  "type": "string",
                  "enum": [
                    "products:write",
                    "stocks:write"
                  ]
                }
              },
              "expires_at": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time"
              }
            }
          },
          "deactivate_missing": {
            "type": "boolean",
            "description": "Включён ли флаг «Деактивировать всё, чего нет в выгрузке»"
          },
          "warehouses": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Warehouse"
            }
          },
          "limits": {
            "type": "object",
            "properties": {
              "max_batch_items": {
                "type": "integer",
                "examples": [
                  1000
                ]
              },
              "requests_per_minute": {
                "type": "integer",
                "examples": [
                  120
                ]
              },
              "session_ttl_hours": {
                "type": "integer",
                "examples": [
                  6
                ]
              }
            }
          }
        }
      },
      "ProductStock": {
        "type": "object",
        "properties": {
          "warehouse": {
            "type": [
              "string",
              "null"
            ],
            "examples": [
              "MSK-1"
            ]
          },
          "quantity": {
            "type": "integer",
            "description": "Физический остаток"
          },
          "reserved": {
            "type": "integer",
            "description": "Резерв под заказы, ещё не переданные перевозчику"
          },
          "available": {
            "type": "integer",
            "description": "Доступно к продаже: max(0, quantity − reserved)"
          }
        }
      },
      "ProductState": {
        "type": "object",
        "properties": {
          "sku": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "price": {
            "type": "number"
          },
          "old_price": {
            "type": [
              "number",
              "null"
            ]
          },
          "is_active": {
            "type": "boolean"
          },
          "deactivated_as_missing": {
            "type": "boolean",
            "description": "Снят с продажи, потому что отсутствовал в полной выгрузке"
          },
          "stocks": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProductStock"
            }
          }
        }
      },
      "ProductsListResponse": {
        "type": "object",
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProductState"
            }
          },
          "pagination": {
            "type": "object",
            "properties": {
              "total": {
                "type": "integer"
              },
              "per_page": {
                "type": "integer"
              },
              "current_page": {
                "type": "integer"
              },
              "last_page": {
                "type": "integer"
              }
            }
          }
        }
      }
    }
  }
}