From 184c2222f1a24bc6f336ef56394889d74f41d093 Mon Sep 17 00:00:00 2001 From: Andrey Bezrukov Date: Fri, 13 Nov 2026 19:34:16 +0300 Subject: [PATCH] Sync with public swagger 1.4.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add fields and enums from swagger 1.1.0–1.4.0: *Kopeks money fields, budgetFrequency, statusReasons/topStatusReason, frequencyRules, kktuFields, new campaign/creative statuses, sandbox warnings, 409 conflict error. - Nullable campaign budget; legalInfo and legacy frequency fields deprecated. - Tolerate unknown enum values in responses (tests added). - SDK version = swagger version (1.4.0): openapi.json in repo, API_VERSION constant, CI check that package version matches openapi.json. - User-Agent: avito-ads-sdk-/; a custom User-Agent is now extended with the SDK label instead of replacing it. - CHANGELOG (with Breaking section) and README updated. --- .github/workflows/ci.yml | 21 + CHANGELOG.md | 57 +- README.md | 110 +- avito_ads/__init__.py | 23 +- avito_ads/_async/resources.py | 34 +- avito_ads/_async/token_provider.py | 5 +- avito_ads/_async/transport.py | 5 +- avito_ads/_core/operations.py | 35 +- avito_ads/_core/transport.py | 3 + avito_ads/_sync/resources.py | 34 +- avito_ads/_sync/token_provider.py | 5 +- avito_ads/_sync/transport.py | 5 +- avito_ads/_version.py | 37 + avito_ads/auth/storage.py | 9 +- avito_ads/configuration.py | 16 +- avito_ads/enums.py | 86 + avito_ads/exceptions.py | 10 + avito_ads/filters.py | 12 + avito_ads/models/__init__.py | 18 +- avito_ads/models/account.py | 14 +- avito_ads/models/base.py | 24 + avito_ads/models/campaign.py | 49 +- avito_ads/models/contract.py | 10 + avito_ads/models/created.py | 17 +- avito_ads/models/creative.py | 66 +- avito_ads/models/group.py | 190 +- avito_ads/models/statistics.py | 72 +- openapi.json | 6652 ++++++++++++++++++++++++++++ pyproject.toml | 6 +- tests/unit/test_swagger_1_4_0.py | 339 ++ tests/unit/test_user_agent.py | 67 + tests/unit/test_version.py | 16 + 32 files changed, 7971 insertions(+), 76 deletions(-) create mode 100644 avito_ads/_version.py create mode 100644 openapi.json create mode 100644 tests/unit/test_swagger_1_4_0.py create mode 100644 tests/unit/test_user_agent.py create mode 100644 tests/unit/test_version.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e6ffbab..15e199a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,27 @@ jobs: run: | python -m pip install --upgrade pip pip install -e ".[dev]" + - name: Version matches swagger + # Версия пакета == info.version из openapi.json == avito_ads.API_VERSION == __version__. + run: | + python - <<'EOF' + import json + import sys + from importlib.metadata import version + + import avito_ads + + versions = { + "package metadata": version("avito-ads"), + "avito_ads.__version__": avito_ads.__version__, + "avito_ads.API_VERSION": avito_ads.API_VERSION, + "openapi.json info.version": json.load(open("openapi.json", encoding="utf-8"))["info"]["version"], + } + for name, value in versions.items(): + print(f"{name}: {value}") + if len(set(versions.values())) != 1: + sys.exit("Версии расходятся") + EOF - name: Ruff run: ruff check . - name: Pytest diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c99abf..f8776d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,62 @@ Формат основан на [Keep a Changelog](https://keepachangelog.com/ru/1.0.0/), проект придерживается [семантического версионирования](https://semver.org/lang/ru/). -## [1.0.0] +## [1.4.0] — 2026-11-13 + +Синхронизация с публичным swagger 1.4.0. С этой версии **версия SDK = версия публичного API (swagger)**. + +### Breaking +- Пользовательский User-Agent теперь дополняется меткой SDK, а не заменяет её: + `with_user_agent("my-app/1.0")` даёт `my-app/1.0 avito-ads-sdk-python3/1.4.0`. Метка по + умолчанию сменилась с `avito-ads-python/0.1.0` на `avito-ads-sdk-python3/<версия>`. +- `account.create_sandbox_account`: `legal_type` (`"ul"`/`"ip"`) обязателен по swagger — без него + или с неизвестным значением бросается `ValidationError` до запроса. +- Изменения swagger, ломающие клиентов API: значение `weekly` у `budgetFrequency` группы удалено; + входные `frequencyCount`/`frequencyPeriod` при создании группы заменены на `frequencyRules` + (метода создания группы в SDK нет, в ответе группы старые поля сохранены). + +### Added +- Константы `avito_ads.API_VERSION` (`"1.4.0"`), `avito_ads.__version__`, `avito_ads.DEFAULT_USER_AGENT`; + `Configuration.effective_user_agent`. `openapi.json` (swagger 1.4.0) в корне репозитория, проверка в CI: + версия пакета == `info.version` == `API_VERSION`. +- `ConflictError` (HTTP 409, наследник `ApiError`) — конфликт версий группы в `groups.change_budget` и + `groups.change_price`. +- Денежные поля в копейках: `Balance.balance_kopeks`, `bonus_balance_kopeks`; `StatsData.spend_kopeks`, + `spend_bonus_kopeks`; `Campaign.budget_kopeks`; `Group.budget_kopeks`, `price_kopeks`. +- Кампания: `budget_frequency` (`daily`/`entirePeriod`/`mixed`), `performance_additional_agreement_id`. +- `status_reasons` (список кодов, `[]` без причин) и `top_status_reason` (`""` без причины) у кампании, + группы и креатива. +- Статусы кампании `will_launch_soon`, `partially_active`, `will_stop_soon`, `pausing`, `unpausing`; + статусы креатива `will_launch_soon`, `pausing`, `unpausing`. +- Группа: `frequency_rules` (`FrequencyRule.count`/`period`), `budget_frequency`, `actions`, + `activity_schedule`, `audience_type`, `format`, `pace`, `period_start_at`, `period_end_at`, + `period_timezone`, `price_control`, `schedule_type`, `start_asap`, `user_id`, `targeting_*_ids` (8 полей). +- Креатив: `kktu_fields` (`KKTUFieldValue.key`/`value`), `landing_id`, `origin_url`, `preview_url`, `user_id`. +- Договор: `is_agent_acting_for_publisher`, `is_creative_reporter`. +- Sandbox: `CreatedAccount.warnings`; ответ `207` (аккаунт создан частично) — успех. +- Перечисления `CampaignBudgetFrequency`, `BudgetFrequency`, `FrequencyPeriod`, `GroupFormat`, + `AudienceType`, `Paces`, `GroupPriceControl`, `ScheduleType`. +- Типы статистики `CampaignStatistic`, `GroupStatistic`, `CreativeStatistic` (наследники `EntityStatistic`). + +### Changed +- Явная политика неизвестных значений: статусы, `budget_frequency`, коды причин и прочие значения + перечислений в ответах возвращаются строками как есть; enum проверяются только на входе. +- `statistics.groups()`/`creatives()` возвращают `GroupStatistic`/`CreativeStatistic`, + `CampaignStatisticResult.campaign` — `CampaignStatistic`. +- `Campaign.budget`/`budget_kopeks` по swagger nullable: тип `Optional[int]` прежний, теперь задокументировано, + что `None` у mixed-кампании (бюджета нет) не равен `0` у пустой кампании. +- `create_sandbox_account`: `actual_address` может быть `None` (API возьмёт юридический адрес). +- Исправлена ошибка mypy в `auth/storage.py` (импорт `Protocol` напрямую из `typing`). + +### Deprecated +- `Creative.legal_info` — используйте `kktu_fields` (swagger 1.2.0). +- `Group.frequency_count`/`frequency_period` — используйте `frequency_rules`. +- `EntityStatistic.payment_model`/`campaign_type` (только у `CampaignStatistic`) и + `EntityStatistic.group_id` (только у `CreativeStatistic`). + +Устаревшие поля не удалены: при чтении выдаётся `DeprecationWarning`. + +## [0.1.0] ### Added - Python SDK для API Авито Реклама в **двух режимах работы**: синхронном diff --git a/README.md b/README.md index a3bd955..5952b23 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,20 @@ Python SDK для API **Авито Реклама** (Avito Ads API). Библиотека закрывает все основные методы API: аккаунт и баланс, дочерние аккаунты и переводы средств, рекламодателей, договоры, кампании, группы объявлений, креативы, статистику и управление пользователями. Поддерживаются **два режима работы — синхронный и асинхронный** — с одинаковым набором методов. Транспорт построен на [httpx](https://www.python-httpx.org/), авторизация — OAuth2 `client_credentials` с автоматическим обновлением и кэшированием токена, а также повторными попытками при ошибках `429` и `5xx`. +## Версия SDK и API + +Версия SDK = версия публичного API (swagger), под которую он собран. Текущая — **1.4.0**: + +```python +import avito_ads + +print(avito_ads.__version__) # "1.4.0" — версия пакета +print(avito_ads.API_VERSION) # "1.4.0" — версия swagger (info.version в openapi.json) +``` + +Спецификация лежит в корне репозитория (`openapi.json`); CI проверяет, что версия пакета, +`API_VERSION` и `info.version` совпадают. + ## Возможности - Поддержка **Python 3.8+**. @@ -108,7 +122,7 @@ config = ( .with_max_retries(4) # макс. число повторов при 429/5xx .with_retry_base_delay(1000) # базовая задержка повтора, мс .with_token_leeway(60) # запас на досрочное обновление токена, сек - .with_user_agent("my-app/1.0") # значение заголовка User-Agent + .with_user_agent("my-app/1.0") # свой User-Agent; метка SDK дописывается ) ``` @@ -123,6 +137,21 @@ config = config.with_http_client(httpx.Client(http2=True)) config = config.with_async_client(httpx.AsyncClient(http2=True)) ``` +### User-Agent + +По умолчанию SDK отправляет `User-Agent: avito-ads-sdk-python3/<версия>` — и в запросах к API, и в +запросе токена. По этой метке Авито видит, что запрос пришёл из Python SDK. + +Свой `User-Agent` не заменяет метку, а дополняется ею через пробел: + +```python +config = config.with_user_agent("my-app/1.0") +print(config.effective_user_agent) # my-app/1.0 avito-ads-sdk-python3/1.4.0 +``` + +Если в вашем значении метка `avito-ads-sdk-python3/` уже есть (без учёта регистра), второй раз она +не дописывается. + ### Окружения | Окружение | Базовый адрес API | @@ -248,6 +277,68 @@ client.groups.change_budget(group_id=555, budget=100000) client.groups.change_price(group_id=555, price=25) ``` +#### Причины статуса + +У кампании, группы и креатива есть `status_reasons` — все коды причин текущего статуса (`[]`, если +причин нет) и `top_status_reason` — главная причина (`""`, если не определена). API может добавлять +новые коды, поэтому обрабатывайте неизвестные значения: + +```python +from avito_ads import CampaignStatus + +for campaign in client.campaigns.iterate(): + if campaign.status == CampaignStatus.PAUSED and campaign.top_status_reason: + print(campaign.id, "на паузе:", campaign.top_status_reason, campaign.status_reasons) +``` + +Статусы, `budget_frequency` и другие значения перечислений модели возвращают **строкой как есть**: +новое значение, появившееся в API, не вызывает ошибку. Перечисления из `avito_ads.enums` нужны для +сравнения и для проверки входных значений. + +#### Бюджет кампании (может отсутствовать) + +`Campaign.budget` и `budget_kopeks` — сумма бюджетов групп, `Optional[int]`. Если в кампании есть +группы и с дневным бюджетом, и с бюджетом на весь период (`budget_frequency == "mixed"`), бюджета +нет и поле равно `None`; у пустой кампании — `0`. Не подменяйте `None` нулём: + +```python +from avito_ads import CampaignBudgetFrequency + +if campaign.budget_kopeks is None: + print("Бюджет не суммируется:", campaign.budget_frequency) # mixed +else: + print("Бюджет:", campaign.budget_kopeks / 100, "₽") +``` + +Денежные поля в копейках есть также у баланса (`balance_kopeks`, `bonus_balance_kopeks`), +статистики (`spend_kopeks`, `spend_bonus_kopeks`) и группы (`budget_kopeks`, `price_kopeks`). + +#### Частотные ограничения группы + +```python +for group in client.groups.iterate(): + for rule in group.frequency_rules: # FrequencyRule: count показов за period + print(group.id, rule.count, rule.period) # period: no_limit / day / week / month +``` + +`Group.frequency_count`/`frequency_period` оставлены для совместимости (соответствуют первому +правилу) и помечены устаревшими: при чтении выдаётся `DeprecationWarning`. Так же помечен +`Creative.legal_info` — используйте `Creative.kktu_fields`. + +#### Конфликт при изменении группы (409) + +Если группу изменили параллельно, `change_budget`/`change_price` бросают `ConflictError` +(наследник `ApiError`). Перечитайте группу и повторите изменение: + +```python +from avito_ads.exceptions import ConflictError + +try: + client.groups.change_budget(group_id=555, budget=100000) +except ConflictError: + ... # перечитать группу и повторить +``` + ### Статистика Период не может превышать 100 дней; даты — в формате `YYYY-MM-DD`. Эти ограничения проверяются на стороне клиента. @@ -313,7 +404,7 @@ from avito_ads.enums import CampaignStatus f = ( CampaignsFilter() - .statuses([CampaignStatus.ACTIVE.value]) + .statuses([CampaignStatus.ACTIVE.value, CampaignStatus.WILL_STOP_SOON.value]) .contract_ids([10, 20]) .created_at(DateRange("2025-01-01", "2025-01-31")) ) @@ -321,6 +412,9 @@ f = ( campaigns = client.campaigns.list(f) ``` +Значения `statuses` передаются в API без проверки на клиенте — доступны все статусы swagger 1.4.0, +включая `will_launch_soon`, `partially_active`, `will_stop_soon`, `pausing`, `unpausing`. + Пустой фильтр корректно сериализуется в JSON-объект `{}`, как того требует API. ## Обработка ошибок @@ -333,6 +427,7 @@ campaigns = client.campaigns.list(f) | 401 | `AuthenticationError` | | 403 | `AccessDeniedError` | | 404 | `NotFoundError` | +| 409 | `ConflictError` (конфликт версий группы в `change_budget`/`change_price`) | | 429 | `RateLimitError` (атрибут `retry_after`) | | 5xx | `ServerError` | | сеть/таймаут | `NetworkError` | @@ -435,6 +530,8 @@ async def balance(client: AsyncClient = Depends(avito)): Создание тестового аккаунта доступно только в песочнице: ```python +from avito_ads.enums import LegalType + config = Configuration.create(client_id, client_secret, account_id).sandbox() with Client(config) as client: @@ -444,11 +541,18 @@ with Client(config) as client: long_name="Полное наименование", ogrn="1177746123456", legal_address="г. Москва, ул. Примерная, д. 1", - actual_address="г. Москва, ул. Примерная, д. 1", + actual_address=None, # None — возьмётся юридический адрес contact={"name": "Иван Иванов", "phone": "+79001234567"}, + legal_type=LegalType.UL, # обязателен: "ul" или "ip" ) + print(created.account_id) + for warning in created.warnings: # ответ 207: аккаунт создан, но не всё подготовлено + print("Предупреждение:", warning) ``` +Ответ `207` считается успехом: аккаунт создан, а что не подготовилось — в `created.warnings` +(пустой список — аккаунт подготовлен полностью). + ## Разработка и тестирование ```bash diff --git a/avito_ads/__init__.py b/avito_ads/__init__.py index 263a14b..a4a335f 100644 --- a/avito_ads/__init__.py +++ b/avito_ads/__init__.py @@ -30,6 +30,7 @@ async def main() -> None: from ._async import AsyncClient from ._sync import Client +from ._version import API_VERSION, DEFAULT_USER_AGENT, __version__ from .auth import ( AsyncTokenStorage, InMemoryAsyncTokenStorage, @@ -39,6 +40,9 @@ async def main() -> None: from .configuration import Configuration from .contract_builder import ContractBuilder from .enums import ( + AudienceType, + BudgetFrequency, + CampaignBudgetFrequency, CampaignPaymentModel, CampaignStatus, CampaignType, @@ -47,9 +51,14 @@ async def main() -> None: ContractSubject, ContractType, CreativesStatus, + FrequencyPeriod, + GroupFormat, + GroupPriceControl, GroupsStatus, LegalRole, LegalType, + Paces, + ScheduleType, UserRole, ) from .exceptions import ( @@ -59,6 +68,7 @@ async def main() -> None: AvitoAdsError, BadRequestError, ConfigurationError, + ConflictError, NetworkError, NotFoundError, RateLimitError, @@ -75,10 +85,10 @@ async def main() -> None: ) from .pagination import ListRequest, PaginatedResult -__version__ = "0.1.0" - __all__ = [ "__version__", + "API_VERSION", + "DEFAULT_USER_AGENT", # clients "Client", "AsyncClient", @@ -102,6 +112,14 @@ async def main() -> None: "CampaignStatus", "GroupsStatus", "CreativesStatus", + "CampaignBudgetFrequency", + "BudgetFrequency", + "FrequencyPeriod", + "GroupFormat", + "AudienceType", + "Paces", + "GroupPriceControl", + "ScheduleType", # exceptions "AvitoAdsError", "ConfigurationError", @@ -111,6 +129,7 @@ async def main() -> None: "AuthenticationError", "AccessDeniedError", "NotFoundError", + "ConflictError", "RateLimitError", "ServerError", "NetworkError", diff --git a/avito_ads/_async/resources.py b/avito_ads/_async/resources.py index c7ec83e..bdf65f5 100644 --- a/avito_ads/_async/resources.py +++ b/avito_ads/_async/resources.py @@ -11,7 +11,7 @@ from .._core import operations as ops from .._core.operations import FilterType from ..contract_builder import ContractBuilder -from ..enums import UserRole +from ..enums import LegalType, UserRole from ..models import ( Account, Advertiser, @@ -25,8 +25,9 @@ CreatedChildAccount, CreatedContract, Creative, - EntityStatistic, + CreativeStatistic, Group, + GroupStatistic, User, ) from ..pagination import DEFAULT_LIMIT, PaginatedResult, iterate_pages_async @@ -59,12 +60,21 @@ async def create_sandbox_account( long_name: str, ogrn: str, legal_address: str, - actual_address: str, + actual_address: Optional[str], contact: Dict[str, Any], kpp: Optional[str] = None, - legal_type: Optional[str] = None, + legal_type: Union[str, LegalType, None] = None, ) -> CreatedAccount: - """Создаёт тестовый аккаунт (только в песочнице, ``POST /v1/account/{accountID}``).""" + """Создаёт тестовый аккаунт (только в песочнице, ``POST /v1/account/{accountID}``). + + ``legal_type`` (``"ul"``/``"ip"``, :class:`~avito_ads.enums.LegalType`) + обязателен: без него бросается ``ValidationError`` до запроса. Значение по + умолчанию ``None`` оставлено только ради порядка аргументов. + ``actual_address`` можно передать ``None`` — API возьмёт ``legal_address``. + + Ответы ``200`` и ``207`` (аккаунт создан, но часть sandbox-данных не + подготовилась) — успех; предупреждения — в ``CreatedAccount.warnings``. + """ return await self._http.execute( ops.create_sandbox_account( self._account_id, @@ -234,11 +244,17 @@ async def loader(req: Any) -> PaginatedResult[Group]: return iterate_pages_async(loader, request) async def change_budget(self, group_id: int, budget: int) -> None: - """Изменить бюджет группы (значение >= 1).""" + """Изменить бюджет группы (значение >= 1). + + :raises ConflictError: 409 — группу изменили параллельно; перечитайте её и повторите. + """ await self._http.execute(ops.change_group_budget(self._account_id, group_id, budget)) async def change_price(self, group_id: int, price: int) -> None: - """Изменить ставку группы (значение >= 1).""" + """Изменить ставку группы (значение >= 1). + + :raises ConflictError: 409 — группу изменили параллельно; перечитайте её и повторите. + """ await self._http.execute(ops.change_group_price(self._account_id, group_id, price)) @@ -277,7 +293,7 @@ async def campaign( async def groups( self, campaign_id: int, date_from: str, date_to: str, group_ids: List[int] - ) -> List[EntityStatistic]: + ) -> List[GroupStatistic]: """Статистика по группам кампании.""" return await self._http.execute( ops.group_statistics(self._account_id, campaign_id, date_from, date_to, group_ids) @@ -285,7 +301,7 @@ async def groups( async def creatives( self, campaign_id: int, date_from: str, date_to: str, creative_ids: List[int] - ) -> List[EntityStatistic]: + ) -> List[CreativeStatistic]: """Статистика по креативам кампании.""" return await self._http.execute( ops.creative_statistics( diff --git a/avito_ads/_async/token_provider.py b/avito_ads/_async/token_provider.py index c9eae50..017e961 100644 --- a/avito_ads/_async/token_provider.py +++ b/avito_ads/_async/token_provider.py @@ -8,6 +8,7 @@ import httpx +from .._version import build_user_agent from ..auth.credentials import Credentials from ..auth.storage import AsyncTokenStorage from ..auth.token import AccessToken @@ -25,7 +26,7 @@ def __init__( storage: AsyncTokenStorage, leeway: int = 60, timeout: float = 30.0, - user_agent: str = "avito-ads-python/0.1.0", + user_agent: Optional[str] = None, logger: Optional[logging.Logger] = None, ) -> None: self._client = client @@ -34,7 +35,7 @@ def __init__( self._storage = storage self._leeway = leeway self._timeout = timeout - self._user_agent = user_agent + self._user_agent = build_user_agent(user_agent) self._logger = logger self._cache_key = credentials.cache_key() diff --git a/avito_ads/_async/transport.py b/avito_ads/_async/transport.py index dd494bc..3da3eed 100644 --- a/avito_ads/_async/transport.py +++ b/avito_ads/_async/transport.py @@ -15,6 +15,7 @@ from .._core import transport as core from .._core.operations import Operation from .._core.response import ApiResponse +from .._version import build_user_agent from ..exceptions import NetworkError from .token_provider import AsyncTokenProvider @@ -36,7 +37,7 @@ def __init__( max_retries: int = 4, retry_base_delay_ms: int = 1000, timeout: float = 30.0, - user_agent: str = "avito-ads-python/0.1.0", + user_agent: Optional[str] = None, logger: Optional[logging.Logger] = None, sleep: Callable[[float], Awaitable[None]] = _default_sleep, ) -> None: @@ -46,7 +47,7 @@ def __init__( self._max_retries = max_retries self._retry_base_delay_ms = retry_base_delay_ms self._timeout = timeout - self._user_agent = user_agent + self._user_agent = build_user_agent(user_agent) self._logger = logger self._sleep = sleep diff --git a/avito_ads/_core/operations.py b/avito_ads/_core/operations.py index 70d2680..03f3fdd 100644 --- a/avito_ads/_core/operations.py +++ b/avito_ads/_core/operations.py @@ -10,10 +10,10 @@ from dataclasses import dataclass from datetime import datetime -from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union +from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, Union from ..contract_builder import ContractBuilder -from ..enums import UserRole +from ..enums import LegalType, UserRole from ..exceptions import ConfigurationError, ValidationError from ..filters import BaseFilter from ..models import ( @@ -29,14 +29,17 @@ CreatedChildAccount, CreatedContract, Creative, + CreativeStatistic, EntityStatistic, Group, + GroupStatistic, User, ) from ..pagination import DEFAULT_LIMIT, ListRequest, PaginatedResult from .response import ApiResponse T = TypeVar("T") +S = TypeVar("S", bound=EntityStatistic) FilterType = Union[Dict[str, Any], BaseFilter, None] @@ -108,10 +111,10 @@ def parse(response: ApiResponse) -> "PaginatedResult[T]": return Operation("POST", account_path(account_id, suffix), request.to_dict(), parse) -def _entities(rows: object) -> List[EntityStatistic]: +def _entities(rows: object, model: Type[S]) -> List[S]: if not isinstance(rows, list): return [] - return [EntityStatistic.from_dict(row) for row in rows if isinstance(row, dict)] + return [model.from_dict(row) for row in rows if isinstance(row, dict)] # --- Account ---------------------------------------------------------------- @@ -139,28 +142,32 @@ def create_sandbox_account( long_name: str, ogrn: str, legal_address: str, - actual_address: str, + actual_address: Optional[str], contact: Dict[str, Any], kpp: Optional[str] = None, - legal_type: Optional[str] = None, + legal_type: Union[str, LegalType, None] = None, ) -> "Operation[CreatedAccount]": if not contact: raise ConfigurationError( "Для создания аккаунта необходимо передать контактное лицо (contact)." ) + if legal_type is None: + raise ValidationError( + "Для создания аккаунта необходимо передать тип юрлица (legal_type: 'ul' или 'ip')." + ) body: Dict[str, Any] = { "inn": inn, "shortName": short_name, "longName": long_name, "ogrn": ogrn, "legalAddress": legal_address, - "actualAddress": actual_address, + "legalType": LegalType.assert_valid(legal_type), "contact": contact, } + if actual_address is not None: + body["actualAddress"] = actual_address if kpp is not None: body["kpp"] = kpp - if legal_type is not None: - body["legalType"] = legal_type return Operation( "POST", account_path(account_id), body, lambda r: CreatedAccount.from_dict(r.data) ) @@ -282,6 +289,7 @@ def list_creatives( def change_group_budget(account_id: int, group_id: int, budget: int) -> "Operation[None]": + """Изменение бюджета группы; при конфликте версий API отвечает 409 (``ConflictError``).""" if budget < 1: raise ValidationError(f"Бюджет должен быть не менее 1, передано {budget}.") return Operation( @@ -293,6 +301,7 @@ def change_group_budget(account_id: int, group_id: int, budget: int) -> "Operati def change_group_price(account_id: int, group_id: int, price: int) -> "Operation[None]": + """Изменение ставки группы; при конфликте версий API отвечает 409 (``ConflictError``).""" if price < 1: raise ValidationError(f"Ставка должна быть не менее 1, передано {price}.") return Operation( @@ -337,25 +346,25 @@ def campaign_statistics( def group_statistics( account_id: int, campaign_id: int, date_from: str, date_to: str, group_ids: List[int] -) -> "Operation[List[EntityStatistic]]": +) -> "Operation[List[GroupStatistic]]": _assert_period(date_from, date_to) return Operation( "POST", account_path(account_id, f"campaigns/{campaign_id}/groups/stats"), {"dateFrom": date_from, "dateTo": date_to, "groupIDs": list(group_ids)}, - lambda r: _entities(r.data.get("groups", [])), + lambda r: _entities(r.data.get("groups", []), GroupStatistic), ) def creative_statistics( account_id: int, campaign_id: int, date_from: str, date_to: str, creative_ids: List[int] -) -> "Operation[List[EntityStatistic]]": +) -> "Operation[List[CreativeStatistic]]": _assert_period(date_from, date_to) return Operation( "POST", account_path(account_id, f"campaigns/{campaign_id}/creatives/stats"), {"dateFrom": date_from, "dateTo": date_to, "creativeIDs": list(creative_ids)}, - lambda r: _entities(r.data.get("creatives", [])), + lambda r: _entities(r.data.get("creatives", []), CreativeStatistic), ) diff --git a/avito_ads/_core/transport.py b/avito_ads/_core/transport.py index e7caf9e..0cc3631 100644 --- a/avito_ads/_core/transport.py +++ b/avito_ads/_core/transport.py @@ -15,6 +15,7 @@ ApiError, AuthenticationError, BadRequestError, + ConflictError, NotFoundError, RateLimitError, ServerError, @@ -110,6 +111,8 @@ def error_from_response( return AccessDeniedError(message, status_code, error_code, request, response) if status_code == 404: return NotFoundError(message, status_code, error_code, request, response) + if status_code == 409: + return ConflictError(message, status_code, error_code, request, response) if status_code == 429: return RateLimitError( message, diff --git a/avito_ads/_sync/resources.py b/avito_ads/_sync/resources.py index 31745c0..11d937c 100644 --- a/avito_ads/_sync/resources.py +++ b/avito_ads/_sync/resources.py @@ -11,7 +11,7 @@ from .._core import operations as ops from .._core.operations import FilterType from ..contract_builder import ContractBuilder -from ..enums import UserRole +from ..enums import LegalType, UserRole from ..models import ( Account, Advertiser, @@ -25,8 +25,9 @@ CreatedChildAccount, CreatedContract, Creative, - EntityStatistic, + CreativeStatistic, Group, + GroupStatistic, User, ) from ..pagination import DEFAULT_LIMIT, PaginatedResult, iterate_pages @@ -59,12 +60,21 @@ def create_sandbox_account( long_name: str, ogrn: str, legal_address: str, - actual_address: str, + actual_address: Optional[str], contact: Dict[str, Any], kpp: Optional[str] = None, - legal_type: Optional[str] = None, + legal_type: Union[str, LegalType, None] = None, ) -> CreatedAccount: - """Создаёт тестовый аккаунт (только в песочнице, ``POST /v1/account/{accountID}``).""" + """Создаёт тестовый аккаунт (только в песочнице, ``POST /v1/account/{accountID}``). + + ``legal_type`` (``"ul"``/``"ip"``, :class:`~avito_ads.enums.LegalType`) + обязателен: без него бросается ``ValidationError`` до запроса. Значение по + умолчанию ``None`` оставлено только ради порядка аргументов. + ``actual_address`` можно передать ``None`` — API возьмёт ``legal_address``. + + Ответы ``200`` и ``207`` (аккаунт создан, но часть sandbox-данных не + подготовилась) — успех; предупреждения — в ``CreatedAccount.warnings``. + """ return self._http.execute( ops.create_sandbox_account( self._account_id, @@ -216,11 +226,17 @@ def iterate(self, filter: FilterType = None, limit: int = DEFAULT_LIMIT) -> Iter ) def change_budget(self, group_id: int, budget: int) -> None: - """Изменить бюджет группы (значение >= 1).""" + """Изменить бюджет группы (значение >= 1). + + :raises ConflictError: 409 — группу изменили параллельно; перечитайте её и повторите. + """ self._http.execute(ops.change_group_budget(self._account_id, group_id, budget)) def change_price(self, group_id: int, price: int) -> None: - """Изменить ставку группы (значение >= 1).""" + """Изменить ставку группы (значение >= 1). + + :raises ConflictError: 409 — группу изменили параллельно; перечитайте её и повторите. + """ self._http.execute(ops.change_group_price(self._account_id, group_id, price)) @@ -255,7 +271,7 @@ def campaign( def groups( self, campaign_id: int, date_from: str, date_to: str, group_ids: List[int] - ) -> List[EntityStatistic]: + ) -> List[GroupStatistic]: """Статистика по группам кампании.""" return self._http.execute( ops.group_statistics(self._account_id, campaign_id, date_from, date_to, group_ids) @@ -263,7 +279,7 @@ def groups( def creatives( self, campaign_id: int, date_from: str, date_to: str, creative_ids: List[int] - ) -> List[EntityStatistic]: + ) -> List[CreativeStatistic]: """Статистика по креативам кампании.""" return self._http.execute( ops.creative_statistics(self._account_id, campaign_id, date_from, date_to, creative_ids) diff --git a/avito_ads/_sync/token_provider.py b/avito_ads/_sync/token_provider.py index c40ac02..27e69ea 100644 --- a/avito_ads/_sync/token_provider.py +++ b/avito_ads/_sync/token_provider.py @@ -8,6 +8,7 @@ import httpx +from .._version import build_user_agent from ..auth.credentials import Credentials from ..auth.storage import TokenStorage from ..auth.token import AccessToken @@ -25,7 +26,7 @@ def __init__( storage: TokenStorage, leeway: int = 60, timeout: float = 30.0, - user_agent: str = "avito-ads-python/0.1.0", + user_agent: Optional[str] = None, logger: Optional[logging.Logger] = None, ) -> None: self._client = client @@ -34,7 +35,7 @@ def __init__( self._storage = storage self._leeway = leeway self._timeout = timeout - self._user_agent = user_agent + self._user_agent = build_user_agent(user_agent) self._logger = logger self._cache_key = credentials.cache_key() diff --git a/avito_ads/_sync/transport.py b/avito_ads/_sync/transport.py index 9921660..2e4dfb5 100644 --- a/avito_ads/_sync/transport.py +++ b/avito_ads/_sync/transport.py @@ -16,6 +16,7 @@ from .._core import transport as core from .._core.operations import Operation from .._core.response import ApiResponse +from .._version import build_user_agent from ..exceptions import NetworkError from .token_provider import SyncTokenProvider @@ -33,7 +34,7 @@ def __init__( max_retries: int = 4, retry_base_delay_ms: int = 1000, timeout: float = 30.0, - user_agent: str = "avito-ads-python/0.1.0", + user_agent: Optional[str] = None, logger: Optional[logging.Logger] = None, sleep: Callable[[float], None] = time.sleep, ) -> None: @@ -43,7 +44,7 @@ def __init__( self._max_retries = max_retries self._retry_base_delay_ms = retry_base_delay_ms self._timeout = timeout - self._user_agent = user_agent + self._user_agent = build_user_agent(user_agent) self._logger = logger self._sleep = sleep diff --git a/avito_ads/_version.py b/avito_ads/_version.py new file mode 100644 index 0000000..0e74f3e --- /dev/null +++ b/avito_ads/_version.py @@ -0,0 +1,37 @@ +"""Версия SDK, версия публичного API и сборка заголовка ``User-Agent``. + +Единственный источник версии пакета: ``pyproject.toml`` читает ``__version__`` +отсюда (``[tool.setuptools.dynamic]``), из неё же собирается ``User-Agent``. +Версия SDK совпадает с версией публичного API (swagger), под которую он собран. +""" + +from __future__ import annotations + +from typing import Optional + +__version__ = "1.4.0" + +#: Версия публичного API Авито Реклама (``info.version`` в swagger), под которую собран SDK. +API_VERSION = "1.4.0" + +#: Метка SDK в ``User-Agent``; по ней сервер определяет, что запрос пришёл из Python SDK. +USER_AGENT_PRODUCT = "avito-ads-sdk-python3" + +#: ``User-Agent`` по умолчанию: ``avito-ads-sdk-python3/<версия>``. +DEFAULT_USER_AGENT = f"{USER_AGENT_PRODUCT}/{__version__}" + + +def build_user_agent(user_agent: Optional[str] = None) -> str: + """Собирает итоговое значение заголовка ``User-Agent``. + + Пользовательский ``User-Agent`` не заменяет метку SDK, а дополняется ею через + пробел: ``my-app/1.0 avito-ads-sdk-python3/1.4.0``. Если метка + ``avito-ads-sdk-python3/`` уже есть (без учёта регистра), второй раз она не + дописывается. Пустое значение даёт ``User-Agent`` по умолчанию. + """ + custom = (user_agent or "").strip() + if not custom: + return DEFAULT_USER_AGENT + if f"{USER_AGENT_PRODUCT}/" in custom.lower(): + return custom + return f"{custom} {DEFAULT_USER_AGENT}" diff --git a/avito_ads/auth/storage.py b/avito_ads/auth/storage.py index 139e5ee..1c682a5 100644 --- a/avito_ads/auth/storage.py +++ b/avito_ads/auth/storage.py @@ -7,12 +7,9 @@ from __future__ import annotations -from typing import Dict, Optional - -try: # pragma: no cover - зависит от версии Python - from typing import Protocol, runtime_checkable -except ImportError: # pragma: no cover - from typing_extensions import Protocol, runtime_checkable +# ``Protocol`` и ``runtime_checkable`` есть в ``typing`` начиная с Python 3.8 — +# минимальной поддерживаемой версии, поэтому запасной импорт не нужен. +from typing import Dict, Optional, Protocol, runtime_checkable from .token import AccessToken diff --git a/avito_ads/configuration.py b/avito_ads/configuration.py index a4fa58f..313b5d9 100644 --- a/avito_ads/configuration.py +++ b/avito_ads/configuration.py @@ -14,6 +14,7 @@ import httpx +from ._version import DEFAULT_USER_AGENT, build_user_agent from .auth.credentials import Credentials from .auth.storage import AsyncTokenStorage, TokenStorage from .exceptions import ConfigurationError @@ -38,7 +39,7 @@ class Configuration: max_retries: int = 4 retry_base_delay_ms: int = 1000 token_leeway: int = 60 - user_agent: str = "avito-ads-python/0.1.0" + user_agent: str = DEFAULT_USER_AGENT logger: Optional[logging.Logger] = None token_storage: Optional[TokenStorage] = None async_token_storage: Optional[AsyncTokenStorage] = None @@ -88,7 +89,13 @@ def with_token_leeway(self, token_leeway: int) -> "Configuration": return replace(self, token_leeway=token_leeway) def with_user_agent(self, user_agent: str) -> "Configuration": - """Значение заголовка ``User-Agent``.""" + """Свой ``User-Agent`` приложения. + + Метка SDK не заменяется, а дописывается через пробел: + ``my-app/1.0`` превращается в ``my-app/1.0 avito-ads-sdk-python3/1.4.0`` + (см. :attr:`effective_user_agent`). Если метка уже есть, второй раз она + не добавляется. + """ return replace(self, user_agent=user_agent) def with_logger(self, logger: logging.Logger) -> "Configuration": @@ -117,6 +124,11 @@ def with_async_client(self, client: httpx.AsyncClient) -> "Configuration": def credentials(self) -> Credentials: return Credentials(self.client_id, self.client_secret) + @property + def effective_user_agent(self) -> str: + """Итоговый заголовок ``User-Agent``: пользовательский + метка SDK.""" + return build_user_agent(self.user_agent) + @property def base_uri(self) -> str: """Базовый адрес API с учётом окружения.""" diff --git a/avito_ads/enums.py b/avito_ads/enums.py index 699cdd1..5f5e4ef 100644 --- a/avito_ads/enums.py +++ b/avito_ads/enums.py @@ -3,6 +3,13 @@ Используются строковые enum (наследники ``str, Enum``), поэтому значения можно передавать как сам элемент перечисления, так и эквивалентную строку. Метод :func:`BaseEnum.assert_valid` проверяет, что переданное значение допустимо. + +Политика неизвестных значений: перечисления проверяют только **входные** +значения (роли пользователей, поля договора, тип юрлица). Поля ответов API +(статусы, ``budgetFrequency``, ``statusReasons`` и т. п.) модели возвращают +строкой как есть и не приводят к enum, поэтому новое значение, добавленное в +API, не вызывает ошибку. Сравнивайте их со значениями enum: +``campaign.status == CampaignStatus.ACTIVE``. """ from __future__ import annotations @@ -123,7 +130,12 @@ class CampaignStatus(BaseEnum): MODERATION_FAILED = "moderation_failed" PARTIAL_MODERATION = "partial_moderation" ACTIVE = "active" + WILL_LAUNCH_SOON = "will_launch_soon" + PARTIALLY_ACTIVE = "partially_active" + WILL_STOP_SOON = "will_stop_soon" + PAUSING = "pausing" PAUSED = "paused" + UNPAUSING = "unpausing" STOPPED = "stopped" FINISHED = "finished" ARCHIVED = "archived" @@ -154,8 +166,82 @@ class CreativesStatus(BaseEnum): IN_MODERATION = "in_moderation" MODERATION_FAILED = "moderation_failed" ERIR_REGISTRATION = "erir_registration" + WILL_LAUNCH_SOON = "will_launch_soon" ACTIVE = "active" + PAUSING = "pausing" PAUSED = "paused" + UNPAUSING = "unpausing" STOPPED = "stopped" FINISHED = "finished" ARCHIVED = "archived" + + +class CampaignBudgetFrequency(BaseEnum): + """Тип агрегата бюджета кампании (``Campaign.budgetFrequency``). + + ``mixed`` — в кампании есть группы и с дневным бюджетом, и с бюджетом на весь + период; тогда ``budget``/``budgetKopeks`` у кампании отсутствуют. + """ + + DAILY = "daily" + ENTIRE_PERIOD = "entirePeriod" + MIXED = "mixed" + + +class BudgetFrequency(BaseEnum): + """Частота расходования бюджета группы (``Group.budgetFrequency``).""" + + DAILY = "daily" + ENTIRE_PERIOD = "entirePeriod" + + +class FrequencyPeriod(BaseEnum): + """Период частотного ограничения (``FrequencyRule.period``).""" + + NO_LIMIT = "no_limit" + DAY = "day" + WEEK = "week" + MONTH = "month" + + +class GroupFormat(BaseEnum): + """Формат группы объявлений.""" + + MEDIA_ROOT = "mediaRoot" + MEDIA_SELLER_PROFILE = "mediaSellerProfile" + MEDIA_PREMIUM = "mediaPremium" + MEDIA = "media" + NATIVE = "native" + HTML_PREMIUM = "htmlPremium" + HTML = "html" + VIDEO = "video" + + +class AudienceType(BaseEnum): + """Тип аудитории таргетинга группы.""" + + BASIC = "basic" + READY = "ready" + AUTOTARGETING = "autotargeting" + + +class Paces(BaseEnum): + """Скорость показов группы.""" + + ASAP = "asap" + EVEN = "even" + + +class GroupPriceControl(BaseEnum): + """Контроль цены группы.""" + + MANUAL = "manual" + AUTO = "auto" + + +class ScheduleType(BaseEnum): + """Тип расписания показов группы.""" + + ALWAYS = "always" + WEEKDAYS_9_TO_20 = "weekdays9To20" + CUSTOM = "custom" diff --git a/avito_ads/exceptions.py b/avito_ads/exceptions.py index 3093e79..b81d55c 100644 --- a/avito_ads/exceptions.py +++ b/avito_ads/exceptions.py @@ -66,6 +66,16 @@ class NotFoundError(ApiError): """HTTP 404 — ресурс не найден.""" +class ConflictError(ApiError): + """HTTP 409 — конфликт версий. + + API возвращает 409 в ``change-budget`` и ``change-price``, если группу + изменили параллельно. Наследник :class:`ApiError`: обработчики по базовому + классу продолжают ловить эту ошибку. Обычно достаточно перечитать группу и + повторить изменение. + """ + + class RateLimitError(ApiError): """HTTP 429 — превышен лимит запросов. diff --git a/avito_ads/filters.py b/avito_ads/filters.py index f2555bb..9240af6 100644 --- a/avito_ads/filters.py +++ b/avito_ads/filters.py @@ -89,6 +89,10 @@ def campaign_types(self, types: List[str]) -> "CampaignsFilter": return self def statuses(self, statuses: List[str]) -> "CampaignsFilter": + """Статусы (значения :class:`~avito_ads.enums.CampaignStatus`). + + Значения передаются в API как есть, без проверки на клиенте. + """ self._set("statuses", statuses) return self @@ -129,6 +133,10 @@ def campaign_ids(self, ids: List[int]) -> "GroupsFilter": return self def statuses(self, statuses: List[str]) -> "GroupsFilter": + """Статусы (значения :class:`~avito_ads.enums.GroupsStatus`). + + Значения передаются в API как есть, без проверки на клиенте. + """ self._set("statuses", statuses) return self @@ -177,6 +185,10 @@ def campaign_types(self, types: List[str]) -> "CreativesFilter": return self def statuses(self, statuses: List[str]) -> "CreativesFilter": + """Статусы (значения :class:`~avito_ads.enums.CreativesStatus`). + + Значения передаются в API как есть, без проверки на клиенте. + """ self._set("statuses", statuses) return self diff --git a/avito_ads/models/__init__.py b/avito_ads/models/__init__.py index 24ec2b8..162fa1d 100644 --- a/avito_ads/models/__init__.py +++ b/avito_ads/models/__init__.py @@ -14,9 +14,16 @@ CreatedChildAccount, CreatedContract, ) -from .creative import Creative -from .group import Group -from .statistics import CampaignStatisticResult, EntityStatistic, StatsData +from .creative import Creative, KKTUFieldValue +from .group import FrequencyRule, Group +from .statistics import ( + CampaignStatistic, + CampaignStatisticResult, + CreativeStatistic, + EntityStatistic, + GroupStatistic, + StatsData, +) from .user import User __all__ = [ @@ -32,9 +39,14 @@ "CreatedChildAccount", "CreatedContract", "Creative", + "KKTUFieldValue", "Group", + "FrequencyRule", + "CampaignStatistic", "CampaignStatisticResult", + "CreativeStatistic", "EntityStatistic", + "GroupStatistic", "StatsData", "User", ] diff --git a/avito_ads/models/account.py b/avito_ads/models/account.py index e02acce..23c3652 100644 --- a/avito_ads/models/account.py +++ b/avito_ads/models/account.py @@ -48,12 +48,24 @@ def manager(self) -> Dict[str, Any]: class Balance(Model): - """Баланс аккаунта (рубли и бонусы, целые числа).""" + """Баланс аккаунта: целые рубли и точные суммы в копейках.""" @property def balance(self) -> int: + """Баланс в рублях.""" return self._int("balance") or 0 @property def bonus_balance(self) -> int: + """Бонусный баланс в рублях.""" return self._int("bonusBalance") or 0 + + @property + def balance_kopeks(self) -> int: + """Баланс в копейках (``balanceKopeks``).""" + return self._int("balanceKopeks") or 0 + + @property + def bonus_balance_kopeks(self) -> int: + """Бонусный баланс в копейках (``bonusBalanceKopeks``).""" + return self._int("bonusBalanceKopeks") or 0 diff --git a/avito_ads/models/base.py b/avito_ads/models/base.py index 43a898e..66c6b11 100644 --- a/avito_ads/models/base.py +++ b/avito_ads/models/base.py @@ -2,6 +2,7 @@ from __future__ import annotations +import warnings from typing import Any, Dict, List, Optional, Type, TypeVar M = TypeVar("M", bound="Model") @@ -63,3 +64,26 @@ def _dict(self, key: str) -> Dict[str, Any]: def _list(self, key: str) -> List[Any]: value = self._data.get(key) return value if isinstance(value, list) else [] + + def _str_list(self, key: str) -> List[str]: + """Список строк; ``null``/отсутствие — пустой список, ``None`` внутри пропускается.""" + return [str(item) for item in self._list(key) if item is not None] + + def _int_list(self, key: str) -> List[int]: + """Список целых; нечисловые элементы пропускаются.""" + result: List[int] = [] + for item in self._list(key): + try: + result.append(int(item)) + except (TypeError, ValueError): + continue + return result + + def _models(self, key: str, model: Type[M]) -> List[M]: + """Список вложенных объектов, обёрнутых в модель ``model``.""" + return [model.from_dict(row) for row in self._list(key) if isinstance(row, dict)] + + +def warn_deprecated(name: str, hint: str) -> None: + """Выдаёт ``DeprecationWarning`` при чтении устаревшего поля ответа.""" + warnings.warn(f"{name} устарело: {hint}", DeprecationWarning, stacklevel=3) diff --git a/avito_ads/models/campaign.py b/avito_ads/models/campaign.py index 1a2b2d4..0bcbc8b 100644 --- a/avito_ads/models/campaign.py +++ b/avito_ads/models/campaign.py @@ -2,13 +2,20 @@ from __future__ import annotations -from typing import Optional +from typing import List, Optional from .base import Model class Campaign(Model): - """Рекламная кампания.""" + """Рекламная кампания. + + Значения ``status``, ``budget_frequency``, ``status_reasons`` и + ``top_status_reason`` возвращаются строками как есть: новые значения, + добавленные в API, не вызывают ошибку. Известные значения — в + :class:`~avito_ads.enums.CampaignStatus` и + :class:`~avito_ads.enums.CampaignBudgetFrequency`. + """ @property def id(self) -> Optional[int]: @@ -20,12 +27,45 @@ def name(self) -> Optional[str]: @property def status(self) -> Optional[str]: + """Статус кампании (см. :class:`~avito_ads.enums.CampaignStatus`).""" return self._str("status") + @property + def status_reasons(self) -> List[str]: + """Все коды причин текущего статуса (``[]``, если причин нет). + + Порядок не отражает приоритет; возможны новые коды. + """ + return self._str_list("statusReasons") + + @property + def top_status_reason(self) -> str: + """Главная причина текущего статуса (``""``, если не определена).""" + return self._str("topStatusReason") or "" + @property def budget(self) -> Optional[int]: + """Сумма бюджетов групп в целых рублях с НДС. + + ``None`` — бюджета нет (``budget_frequency == "mixed"``: в кампании есть + группы и с дневным бюджетом, и с бюджетом на весь период). У пустой + кампании — ``0``. Не подменяйте ``None`` нулём. + """ return self._int("budget") + @property + def budget_kopeks(self) -> Optional[int]: + """Точная сумма бюджетов групп в копейках с НДС; ``None`` — как у :attr:`budget`.""" + return self._int("budgetKopeks") + + @property + def budget_frequency(self) -> Optional[str]: + """Тип агрегата бюджета: ``daily``, ``entirePeriod`` или ``mixed``. + + См. :class:`~avito_ads.enums.CampaignBudgetFrequency`. + """ + return self._str("budgetFrequency") + @property def payment_model(self) -> Optional[str]: return self._str("paymentModel") @@ -66,6 +106,11 @@ def manager_id(self) -> Optional[int]: def additional_agreement_id(self) -> Optional[int]: return self._int("additionalAgreementID") + @property + def performance_additional_agreement_id(self) -> Optional[int]: + """ID доп. соглашения к исполнительскому договору (``performanceAdditionalAgreementID``).""" + return self._int("performanceAdditionalAgreementID") + @property def created_at(self) -> Optional[str]: return self._str("createdAt") diff --git a/avito_ads/models/contract.py b/avito_ads/models/contract.py index c1b8d54..183afb5 100644 --- a/avito_ads/models/contract.py +++ b/avito_ads/models/contract.py @@ -58,3 +58,13 @@ def description(self) -> Optional[str]: @property def parent_id(self) -> Optional[int]: return self._int("parentId") + + @property + def is_agent_acting_for_publisher(self) -> Optional[bool]: + """``isAgentActingForPublisher``; ``None``, если не задано.""" + return self._bool("isAgentActingForPublisher") + + @property + def is_creative_reporter(self) -> Optional[bool]: + """``isCreativeReporter``; ``None``, если не задано.""" + return self._bool("isCreativeReporter") diff --git a/avito_ads/models/created.py b/avito_ads/models/created.py index fabb02b..9ce38e3 100644 --- a/avito_ads/models/created.py +++ b/avito_ads/models/created.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Optional +from typing import List, Optional from .base import Model @@ -24,12 +24,25 @@ def id(self) -> Optional[int]: class CreatedAccount(Model): - """Результат создания тестового аккаунта (песочница).""" + """Результат создания тестового аккаунта (песочница). + + API отвечает ``200``, если аккаунт подготовлен полностью, и ``207``, если + аккаунт создан, но часть sandbox-данных не подготовилась. Оба ответа — + успех; причины во втором случае — в :attr:`warnings`. + """ @property def account_id(self) -> Optional[int]: return self._int("accountID") + @property + def warnings(self) -> List[str]: + """Предупреждения о частично невыполненных sandbox-операциях. + + Пустой список — аккаунт подготовлен полностью. + """ + return self._str_list("warnings") + class CreatedChildAccount(Model): """Результат создания дочернего аккаунта.""" diff --git a/avito_ads/models/creative.py b/avito_ads/models/creative.py index b2046b2..ec0b863 100644 --- a/avito_ads/models/creative.py +++ b/avito_ads/models/creative.py @@ -2,13 +2,31 @@ from __future__ import annotations -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional -from .base import Model +from .base import Model, warn_deprecated + + +class KKTUFieldValue(Model): + """Заполненное поле динамической формы ККТУ (элемент ``kktuFields``).""" + + @property + def key(self) -> Optional[str]: + """Внутренний ключ поля.""" + return self._str("key") + + @property + def value(self) -> Optional[str]: + """Значение поля, приведённое к строке.""" + return self._str("value") class Creative(Model): - """Креатив.""" + """Креатив. + + ``status``, ``status_reasons`` и ``top_status_reason`` возвращаются строками + как есть: новые значения, добавленные в API, не вызывают ошибку. + """ @property def id(self) -> Optional[int]: @@ -36,8 +54,19 @@ def link(self) -> Optional[str]: @property def status(self) -> Optional[str]: + """Статус креатива (см. :class:`~avito_ads.enums.CreativesStatus`).""" return self._str("status") + @property + def status_reasons(self) -> List[str]: + """Все коды причин текущего статуса (``[]``, если причин нет).""" + return self._str_list("statusReasons") + + @property + def top_status_reason(self) -> str: + """Главная причина текущего статуса (``""``, если не определена).""" + return self._str("topStatusReason") or "" + @property def group_id(self) -> Optional[int]: return self._int("groupID") @@ -66,6 +95,37 @@ def payment_model(self) -> Optional[str]: def campaign_type(self) -> Optional[str]: return self._str("campaignType") + @property + def user_id(self) -> Optional[int]: + """ID пользователя, создавшего креатив (``userID``).""" + return self._int("userID") + + @property + def landing_id(self) -> Optional[int]: + """ID посадочной страницы (``landingID``).""" + return self._int("landingID") + + @property + def origin_url(self) -> Optional[str]: + """Оригинальная ссылка для аналитики (``originUrl``).""" + return self._str("originUrl") + + @property + def preview_url(self) -> Optional[str]: + """Ссылка на предпросмотр креатива (``previewUrl``).""" + return self._str("previewUrl") + + @property + def kktu_fields(self) -> List[KKTUFieldValue]: + """Заполненные поля динамической формы ККТУ (``kktuFields``).""" + return self._models("kktuFields", KKTUFieldValue) + @property def legal_info(self) -> Dict[str, Any]: + """Устаревшее представление юридических данных. + + .. deprecated:: 1.2.0 + Используйте :attr:`kktu_fields`. Поле остаётся для совместимости. + """ + warn_deprecated("Creative.legal_info", "используйте Creative.kktu_fields.") return self._dict("legalInfo") diff --git a/avito_ads/models/group.py b/avito_ads/models/group.py index d009ed5..b38c86f 100644 --- a/avito_ads/models/group.py +++ b/avito_ads/models/group.py @@ -2,13 +2,37 @@ from __future__ import annotations -from typing import Optional +from typing import Dict, List, Optional -from .base import Model +from .base import Model, warn_deprecated + +_WEEKDAYS = ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") + + +class FrequencyRule(Model): + """Правило частотного ограничения: не более ``count`` показов за ``period``.""" + + @property + def count(self) -> Optional[int]: + """Количество показов за период.""" + return self._int("count") + + @property + def period(self) -> Optional[str]: + """Период: ``no_limit``, ``day``, ``week`` или ``month``. + + См. :class:`~avito_ads.enums.FrequencyPeriod`. + """ + return self._str("period") class Group(Model): - """Группа объявлений.""" + """Группа объявлений. + + Значения перечислений (``status``, ``budget_frequency``, ``format``, + ``pace`` и др.) и коды причин возвращаются строками как есть: новые + значения, добавленные в API, не вызывают ошибку. + """ @property def id(self) -> Optional[int]: @@ -26,18 +50,178 @@ def account_id(self) -> Optional[int]: def campaign_id(self) -> Optional[int]: return self._int("campaignID") + @property + def user_id(self) -> Optional[int]: + """ID пользователя, создавшего группу (``userID``).""" + return self._int("userID") + @property def status(self) -> Optional[str]: + """Статус группы (см. :class:`~avito_ads.enums.GroupsStatus`).""" return self._str("status") + @property + def status_reasons(self) -> List[str]: + """Все коды причин текущего статуса (``[]``, если причин нет).""" + return self._str_list("statusReasons") + + @property + def top_status_reason(self) -> str: + """Главная причина текущего статуса (``""``, если не определена).""" + return self._str("topStatusReason") or "" + + @property + def actions(self) -> List[str]: + """Доступные действия с группой.""" + return self._str_list("actions") + @property def budget(self) -> Optional[int]: + """Бюджет группы в рублях с НДС.""" return self._int("budget") + @property + def budget_kopeks(self) -> Optional[int]: + """Бюджет группы в копейках с НДС (``budgetKopeks``).""" + return self._int("budgetKopeks") + + @property + def budget_frequency(self) -> Optional[str]: + """Частота расходования бюджета: ``daily`` или ``entirePeriod``. + + См. :class:`~avito_ads.enums.BudgetFrequency`. + """ + return self._str("budgetFrequency") + @property def price(self) -> Optional[int]: + """Цена в рублях с НДС.""" return self._int("price") + @property + def price_kopeks(self) -> Optional[int]: + """Цена в копейках с НДС (``priceKopeks``).""" + return self._int("priceKopeks") + + @property + def price_control(self) -> Optional[str]: + """Контроль цены: ``manual`` или ``auto`` (:class:`~avito_ads.enums.GroupPriceControl`).""" + return self._str("priceControl") + + @property + def frequency_rules(self) -> List[FrequencyRule]: + """Правила частотного ограничения (``frequencyRules``).""" + return self._models("frequencyRules", FrequencyRule) + + @property + def frequency_count(self) -> Optional[int]: + """Частота показов первого правила. + + .. deprecated:: 1.4.0 + Используйте :attr:`frequency_rules`; поле соответствует первому правилу. + """ + warn_deprecated("Group.frequency_count", "используйте Group.frequency_rules.") + return self._int("frequencyCount") + + @property + def frequency_period(self) -> Optional[str]: + """Период частоты первого правила. + + .. deprecated:: 1.4.0 + Используйте :attr:`frequency_rules`; поле соответствует первому правилу. + """ + warn_deprecated("Group.frequency_period", "используйте Group.frequency_rules.") + return self._str("frequencyPeriod") + + @property + def format(self) -> Optional[str]: + """Формат группы (см. :class:`~avito_ads.enums.GroupFormat`).""" + return self._str("format") + + @property + def audience_type(self) -> Optional[str]: + """Тип аудитории таргетинга (см. :class:`~avito_ads.enums.AudienceType`).""" + return self._str("audienceType") + + @property + def pace(self) -> Optional[str]: + """Скорость показов: ``asap`` или ``even`` (:class:`~avito_ads.enums.Paces`).""" + return self._str("pace") + + @property + def schedule_type(self) -> Optional[str]: + """Тип расписания показов (см. :class:`~avito_ads.enums.ScheduleType`).""" + return self._str("scheduleType") + + @property + def activity_schedule(self) -> Dict[str, List[int]]: + """Расписание активности: день недели (``monday`` … ``sunday``) -> часы 0–23. + + Отсутствующие в ответе дни в словарь не попадают. + """ + schedule = Model(self._dict("activitySchedule")) + return {day: schedule._int_list(day) for day in _WEEKDAYS if day in schedule.raw} + + @property + def start_asap(self) -> Optional[bool]: + """Запускать как можно скорее (``startASAP``).""" + return self._bool("startASAP") + + @property + def period_start_at(self) -> Optional[str]: + """Начало периода показов (date-time).""" + return self._str("periodStartAt") + + @property + def period_end_at(self) -> Optional[str]: + """Конец периода показов (date-time).""" + return self._str("periodEndAt") + + @property + def period_timezone(self) -> Optional[str]: + """Таймзона периода показов.""" + return self._str("periodTimezone") + + @property + def targeting_age_ids(self) -> List[int]: + """ID возрастных сегментов.""" + return self._int_list("targetingAgeIDs") + + @property + def targeting_audience_ids(self) -> List[str]: + """ID аудиторий.""" + return self._str_list("targetingAudienceIDs") + + @property + def targeting_family_status_ids(self) -> List[int]: + """ID семейного статуса.""" + return self._int_list("targetingFamilyStatusIDs") + + @property + def targeting_gender_ids(self) -> List[int]: + """ID пола.""" + return self._int_list("targetingGenderIDs") + + @property + def targeting_income_ids(self) -> List[int]: + """ID доходных сегментов.""" + return self._int_list("targetingIncomeIDs") + + @property + def targeting_interest_ids(self) -> List[str]: + """ID интересов.""" + return self._str_list("targetingInterestIDs") + + @property + def targeting_location_ids(self) -> List[int]: + """ID локаций.""" + return self._int_list("targetingLocationIDs") + + @property + def targeting_parent_status_ids(self) -> List[int]: + """ID родительского статуса.""" + return self._int_list("targetingParentStatusIDs") + @property def payment_model(self) -> Optional[str]: return self._str("paymentModel") diff --git a/avito_ads/models/statistics.py b/avito_ads/models/statistics.py index 5997029..7dfe294 100644 --- a/avito_ads/models/statistics.py +++ b/avito_ads/models/statistics.py @@ -4,7 +4,7 @@ from typing import List, Optional -from .base import Model +from .base import Model, warn_deprecated class StatsData(Model): @@ -34,6 +34,16 @@ def spend(self) -> int: def spend_bonus(self) -> int: return self._int("spendBonus") or 0 + @property + def spend_kopeks(self) -> Optional[int]: + """Потрачено денег в копейках (``spendKopeks``); ``None``, если поля нет в ответе.""" + return self._int("spendKopeks") + + @property + def spend_bonus_kopeks(self) -> Optional[int]: + """Потрачено бонусов в копейках (``spendBonusKopeks``); ``None``, если поля нет.""" + return self._int("spendBonusKopeks") + @property def cpm(self) -> Optional[float]: return self._float("cpm") @@ -76,7 +86,11 @@ def vtr(self) -> Optional[float]: class EntityStatistic(Model): - """Статистика по сущности (кампании, группе или креативу).""" + """Статистика по сущности: общая часть кампании, группы и креатива. + + Конкретные ответы — :class:`CampaignStatistic`, :class:`GroupStatistic` и + :class:`CreativeStatistic`. + """ @property def id(self) -> Optional[int]: @@ -88,14 +102,32 @@ def name(self) -> Optional[str]: @property def group_id(self) -> Optional[int]: + """ID группы креатива. + + .. deprecated:: 1.4.0 + Поле есть только в статистике креатива — :class:`CreativeStatistic`. + """ + warn_deprecated("EntityStatistic.group_id", "поле есть только у CreativeStatistic.") return self._int("groupId") @property def payment_model(self) -> Optional[str]: + """Модель оплаты. + + .. deprecated:: 1.4.0 + Поле есть только в статистике кампании — :class:`CampaignStatistic`. + """ + warn_deprecated("EntityStatistic.payment_model", "поле есть только у CampaignStatistic.") return self._str("paymentModel") @property def campaign_type(self) -> Optional[str]: + """Тип кампании. + + .. deprecated:: 1.4.0 + Поле есть только в статистике кампании — :class:`CampaignStatistic`. + """ + warn_deprecated("EntityStatistic.campaign_type", "поле есть только у CampaignStatistic.") return self._str("campaignType") @property @@ -107,17 +139,41 @@ def total_data(self) -> StatsData: return StatsData.from_dict(self._dict("totalData")) +class CampaignStatistic(EntityStatistic): + """Статистика кампании (с моделью оплаты и типом кампании).""" + + @property + def payment_model(self) -> Optional[str]: + return self._str("paymentModel") + + @property + def campaign_type(self) -> Optional[str]: + return self._str("campaignType") + + +class GroupStatistic(EntityStatistic): + """Статистика группы.""" + + +class CreativeStatistic(EntityStatistic): + """Статистика креатива (с ID группы).""" + + @property + def group_id(self) -> Optional[int]: + return self._int("groupId") + + class CampaignStatisticResult(Model): """Результат запроса статистики по кампании со сводками по группам и креативам.""" @property - def campaign(self) -> EntityStatistic: - return EntityStatistic.from_dict(self._dict("campaign")) + def campaign(self) -> CampaignStatistic: + return CampaignStatistic.from_dict(self._dict("campaign")) @property - def groups(self) -> List[EntityStatistic]: - return [EntityStatistic.from_dict(row) for row in self._list("groups")] + def groups(self) -> List[GroupStatistic]: + return self._models("groups", GroupStatistic) @property - def creatives(self) -> List[EntityStatistic]: - return [EntityStatistic.from_dict(row) for row in self._list("creatives")] + def creatives(self) -> List[CreativeStatistic]: + return self._models("creatives", CreativeStatistic) diff --git a/openapi.json b/openapi.json new file mode 100644 index 0000000..a402458 --- /dev/null +++ b/openapi.json @@ -0,0 +1,6652 @@ +{ + "components": { + "schemas": { + "Account": { + "properties": { + "actualAddress": { + "type": "string" + }, + "contact": { + "description": "Контактное лицо", + "properties": { + "name": { + "type": "string" + }, + "phone": { + "type": "string" + } + }, + "required": [ + "name", + "phone" + ], + "type": "object" + }, + "inn": { + "type": "string" + }, + "kpp": { + "type": "string" + }, + "legalAddress": { + "type": "string" + }, + "longName": { + "type": "string" + }, + "manager": { + "description": "MSD Менеджер", + "nullable": true, + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name", + "email" + ], + "type": "object" + }, + "ogrn": { + "type": "string" + }, + "shortName": { + "type": "string" + } + }, + "required": [ + "inn", + "shortName", + "longName", + "ogrn", + "kpp", + "legalAddress", + "actualAddress", + "contact" + ], + "type": "object" + }, + "ActivityScheduleDay": { + "description": "Активные часы в сутках", + "items": { + "maximum": 23, + "minimum": 0, + "type": "integer" + }, + "type": "array" + }, + "ActivityScheduleHours": { + "description": "Расписание активности на день по часам (0-23)", + "items": { + "type": "integer" + }, + "type": "array" + }, + "Advertiser": { + "properties": { + "accountId": { + "type": "integer" + }, + "actualAddress": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "inn": { + "type": "string" + }, + "kpp": { + "type": "string" + }, + "legalAddress": { + "type": "string" + }, + "legalRole": { + "$ref": "#/components/schemas/LegalRole" + }, + "legalType": { + "$ref": "#/components/schemas/LegalType" + }, + "longName": { + "type": "string" + }, + "ogrn": { + "type": "string" + }, + "shortName": { + "type": "string" + } + }, + "required": [ + "id", + "shortName", + "longName", + "inn", + "legalRole", + "ogrn", + "legalAddress", + "actualAddress", + "accountId", + "legalType" + ], + "type": "object" + }, + "AdvertiserFilter": { + "properties": { + "ids": { + "description": "Список ID рекламодателей", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "inns": { + "description": "Список ИНН рекламодателей", + "items": { + "type": "string" + }, + "nullable": true, + "type": "array" + }, + "roles": { + "description": "Список ролей рекламодателей", + "items": { + "$ref": "#/components/schemas/LegalRole" + }, + "nullable": true, + "type": "array" + } + }, + "type": "object" + }, + "AudienceType": { + "description": "Тип аудитории таргетинга группы", + "enum": [ + "basic", + "ready", + "autotargeting" + ], + "type": "string" + }, + "BannerFormat": { + "description": "Формат баннера", + "enum": [ + "standard", + "premium", + "root", + "seller_profile" + ], + "type": "string" + }, + "BudgetFrequency": { + "description": "Частота расходования бюджета", + "enum": [ + "daily", + "entirePeriod" + ], + "type": "string" + }, + "Campaign": { + "properties": { + "accountId": { + "description": "ID аккаунта", + "type": "integer" + }, + "additionalAgreementID": { + "description": "ID дополнительного соглашения к изначальному договору", + "nullable": true, + "type": "integer" + }, + "advertiserId": { + "description": "ID рекламодателя", + "type": "integer" + }, + "budget": { + "description": "Сумма бюджетов групп в целых рублях с НДС. Для mixed отсутствует; для пустой кампании равна 0.", + "nullable": true, + "type": "integer" + }, + "budgetFrequency": { + "$ref": "#/components/schemas/CampaignBudgetFrequency" + }, + "budgetKopeks": { + "description": "Точная сумма бюджетов групп в копейках с НДС. Для mixed отсутствует; для пустой кампании равна 0.", + "nullable": true, + "type": "integer" + }, + "campaignType": { + "$ref": "#/components/schemas/CampaignType" + }, + "contractId": { + "description": "ID контракта", + "type": "integer" + }, + "createdAt": { + "description": "Дата создания кампании", + "type": "string" + }, + "endDate": { + "description": "Дата окончания кампании", + "nullable": true, + "type": "string" + }, + "id": { + "description": "ID кампании", + "type": "integer" + }, + "managerID": { + "description": "ID менеджера, ответственного за кампанию (userID)", + "type": "integer" + }, + "name": { + "description": "Название кампании", + "type": "string" + }, + "paymentModel": { + "$ref": "#/components/schemas/CampaignPaymentModel" + }, + "performanceAdditionalAgreementID": { + "description": "ID доп соглашения к исполнительскому договору", + "nullable": true, + "type": "integer" + }, + "startDate": { + "description": "Дата начала кампании", + "nullable": true, + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/CampaignStatus" + }, + "statusReasons": { + "$ref": "#/components/schemas/StatusReasons" + }, + "topStatusReason": { + "$ref": "#/components/schemas/TopStatusReason" + }, + "updatedAt": { + "description": "Дата обновления кампании", + "nullable": true, + "type": "string" + }, + "userId": { + "description": "ID пользователя создавшего кампанию", + "type": "integer" + } + }, + "required": [ + "statusReasons", + "topStatusReason" + ], + "type": "object" + }, + "CampaignBudgetFrequency": { + "description": "Тип агрегата бюджета кампании; mixed — одновременно есть группы с дневным бюджетом и бюджетом на весь период", + "enum": [ + "daily", + "entirePeriod", + "mixed" + ], + "type": "string" + }, + "CampaignFieldName": { + "description": "Название поля кампании", + "enum": [ + "name", + "advertiserID", + "contractID", + "additionalAgreementID", + "performanceAdditionalAgreementID", + "managerID", + "campaignType", + "paymentModel" + ], + "type": "string" + }, + "CampaignGoalType": { + "description": "Цель кампании", + "enum": [ + "performance", + "reach" + ], + "type": "string" + }, + "CampaignLandingType": { + "description": "Тип посадочной страницы кампании", + "enum": [ + "external" + ], + "type": "string" + }, + "CampaignPaymentModel": { + "description": "Модель оплаты кампании", + "enum": [ + "CPM", + "CPC" + ], + "type": "string" + }, + "CampaignStatistic": { + "description": "Статистика кампании", + "properties": { + "campaignType": { + "$ref": "#/components/schemas/CampaignType" + }, + "data": { + "description": "Статистика в разбивке по дням", + "items": { + "$ref": "#/components/schemas/StatsData" + }, + "type": "array" + }, + "id": { + "description": "ID кампании", + "type": "integer" + }, + "name": { + "description": "Название кампании", + "type": "string" + }, + "paymentModel": { + "$ref": "#/components/schemas/CampaignPaymentModel" + }, + "totalData": { + "$ref": "#/components/schemas/StatsData" + } + }, + "required": [ + "id", + "name", + "paymentModel", + "campaignType", + "data", + "totalData" + ], + "type": "object" + }, + "CampaignStatus": { + "description": "Статус кампании", + "enum": [ + "draft", + "in_moderation", + "moderation_failed", + "partial_moderation", + "active", + "will_launch_soon", + "partially_active", + "will_stop_soon", + "pausing", + "paused", + "unpausing", + "stopped", + "finished", + "archived" + ], + "type": "string" + }, + "CampaignStrategy": { + "description": "Стратегия кампании", + "enum": [ + "maxclicks", + "maxviews" + ], + "type": "string" + }, + "CampaignType": { + "description": "Тип кампании", + "enum": [ + "textImage", + "HTML", + "video" + ], + "type": "string" + }, + "CampaignsFilter": { + "properties": { + "additionalAgreementIDs": { + "description": "Список ID дополнительных соглашений", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "advertisers": { + "description": "Список ID рекламодателей", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "campaignTypes": { + "description": "Список типов кампаний", + "items": { + "$ref": "#/components/schemas/CampaignType" + }, + "nullable": true, + "type": "array" + }, + "contractIDs": { + "description": "Список ID договоров", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "createdAt": { + "$ref": "#/components/schemas/DateRange" + }, + "ids": { + "description": "Список ID кампаний", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "managers": { + "description": "Список ID менеджеров", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "paymentModels": { + "description": "Список моделей оплаты", + "items": { + "$ref": "#/components/schemas/CampaignPaymentModel" + }, + "nullable": true, + "type": "array" + }, + "statuses": { + "description": "Список статусов кампаний", + "items": { + "$ref": "#/components/schemas/CampaignStatus" + }, + "nullable": true, + "type": "array" + }, + "timeFrame": { + "$ref": "#/components/schemas/DateRange" + } + }, + "type": "object" + }, + "Contract": { + "properties": { + "accountID": { + "type": "integer" + }, + "cid": { + "nullable": true, + "type": "string" + }, + "client": { + "$ref": "#/components/schemas/Advertiser" + }, + "contractor": { + "$ref": "#/components/schemas/Advertiser" + }, + "date": { + "nullable": true, + "type": "string" + }, + "description": { + "nullable": true, + "type": "string" + }, + "id": { + "type": "integer" + }, + "isAgentActingForPublisher": { + "nullable": true, + "type": "boolean" + }, + "isCreativeReporter": { + "nullable": true, + "type": "boolean" + }, + "number": { + "nullable": true, + "type": "string" + }, + "object": { + "nullable": true, + "type": "string" + }, + "parentId": { + "nullable": true, + "type": "integer" + }, + "subject": { + "nullable": true, + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/ContractType" + } + }, + "required": [ + "id", + "accountID", + "client", + "contractor", + "type" + ], + "type": "object" + }, + "ContractAction": { + "description": "Описание действия договора", + "enum": [ + "distribution", + "conclude", + "commercial", + "other" + ], + "type": "string" + }, + "ContractCounterpartyType": { + "enum": [ + "direct_with_advertiser", + "advertiser_intermediary" + ], + "type": "string" + }, + "ContractForChildAccount": { + "nullable": true, + "properties": { + "accountID": { + "type": "integer" + }, + "cid": { + "nullable": true, + "type": "string" + }, + "client": { + "$ref": "#/components/schemas/Advertiser" + }, + "contractor": { + "$ref": "#/components/schemas/Advertiser" + }, + "date": { + "nullable": true, + "type": "string" + }, + "description": { + "nullable": true, + "type": "string" + }, + "id": { + "type": "integer" + }, + "isAgentActingForPublisher": { + "nullable": true, + "type": "boolean" + }, + "isCreativeReporter": { + "nullable": true, + "type": "boolean" + }, + "number": { + "nullable": true, + "type": "string" + }, + "object": { + "nullable": true, + "type": "string" + }, + "parentId": { + "nullable": true, + "type": "integer" + }, + "subject": { + "nullable": true, + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/ContractType" + } + }, + "type": "object" + }, + "ContractSubject": { + "description": "Предмет договора", + "enum": [ + "org-distribution", + "mediation", + "distribution", + "representation", + "other" + ], + "type": "string" + }, + "ContractType": { + "description": "Тип контракта", + "enum": [ + "service", + "intermediary", + "external" + ], + "type": "string" + }, + "ContractsFilter": { + "properties": { + "clients": { + "$ref": "#/components/schemas/AdvertiserFilter" + }, + "contractors": { + "$ref": "#/components/schemas/AdvertiserFilter" + }, + "ids": { + "description": "Список ID договоров", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "numbers": { + "description": "Список номеров договоров", + "items": { + "type": "string" + }, + "nullable": true, + "type": "array" + } + }, + "type": "object" + }, + "CreateCampaignPaymentModel": { + "description": "Модель оплаты кампании для создания", + "enum": [ + "cpc", + "cpm" + ], + "type": "string" + }, + "CreateCampaignType": { + "description": "Тип кампании для создания", + "enum": [ + "textimg", + "html", + "video" + ], + "type": "string" + }, + "CreateGroupActivitySchedule": { + "description": "Кастомное расписание активности", + "properties": { + "friday": { + "$ref": "#/components/schemas/ActivityScheduleDay" + }, + "monday": { + "$ref": "#/components/schemas/ActivityScheduleDay" + }, + "saturday": { + "$ref": "#/components/schemas/ActivityScheduleDay" + }, + "sunday": { + "$ref": "#/components/schemas/ActivityScheduleDay" + }, + "thursday": { + "$ref": "#/components/schemas/ActivityScheduleDay" + }, + "tuesday": { + "$ref": "#/components/schemas/ActivityScheduleDay" + }, + "wednesday": { + "$ref": "#/components/schemas/ActivityScheduleDay" + } + }, + "type": "object" + }, + "Creative": { + "properties": { + "accountID": { + "description": "ID аккаунта", + "type": "integer" + }, + "advertiserID": { + "description": "ID рекламодателя", + "type": "integer" + }, + "buttonText": { + "description": "Текст на кнопке", + "nullable": true, + "type": "string" + }, + "campaignID": { + "description": "ID кампании", + "type": "integer" + }, + "campaignType": { + "$ref": "#/components/schemas/CampaignType" + }, + "description": { + "description": "Описание объявления", + "nullable": true, + "type": "string" + }, + "groupID": { + "description": "ID группы", + "type": "integer" + }, + "id": { + "description": "ID креатива", + "type": "integer" + }, + "kktuFields": { + "description": "Заполненное поле динамической формы ККТУ", + "items": { + "$ref": "#/components/schemas/KKTUFieldValue" + }, + "type": "array" + }, + "landingID": { + "description": "ID посадочной страницы", + "nullable": true, + "type": "integer" + }, + "legalInfo": { + "$ref": "#/components/schemas/LegalInfo" + }, + "link": { + "description": "Целевая ссылка", + "type": "string" + }, + "managerID": { + "description": "ID менеджера, ответственного за кампанию (userID)", + "type": "integer" + }, + "name": { + "description": "Название креатива", + "type": "string" + }, + "originUrl": { + "description": "Оригинальная ссылка для аналитики", + "nullable": true, + "type": "string" + }, + "paymentModel": { + "$ref": "#/components/schemas/CampaignPaymentModel" + }, + "previewUrl": { + "description": "Ссылка на предпросмотр креатива", + "nullable": true, + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/CreativesStatus" + }, + "statusReasons": { + "$ref": "#/components/schemas/StatusReasons" + }, + "title": { + "description": "Заголовок объявления", + "nullable": true, + "type": "string" + }, + "topStatusReason": { + "$ref": "#/components/schemas/TopStatusReason" + }, + "userID": { + "description": "ID пользователя, создавшего креатив", + "type": "integer" + } + }, + "required": [ + "statusReasons", + "topStatusReason" + ], + "type": "object" + }, + "CreativeStatistic": { + "description": "Статистика креатива", + "properties": { + "data": { + "description": "Статистика в разбивке по дням", + "items": { + "$ref": "#/components/schemas/StatsData" + }, + "type": "array" + }, + "groupId": { + "description": "ID группы, к которой относится креатив", + "type": "integer" + }, + "id": { + "description": "ID креатива", + "type": "integer" + }, + "name": { + "description": "Название креатива", + "type": "string" + }, + "totalData": { + "$ref": "#/components/schemas/StatsData" + } + }, + "required": [ + "id", + "groupId", + "name", + "data", + "totalData" + ], + "type": "object" + }, + "CreativesFilter": { + "properties": { + "advertisers": { + "description": "Список ID рекламодателей", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "campaignIDs": { + "description": "Список ID кампаний", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "campaignTypes": { + "description": "Список типов кампаний", + "items": { + "$ref": "#/components/schemas/CampaignType" + }, + "nullable": true, + "type": "array" + }, + "groupIDs": { + "description": "Список ID групп", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "ids": { + "description": "Список ID креативов", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "managers": { + "description": "Список ID менеджеров", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "paymentModels": { + "description": "Список моделей оплаты", + "items": { + "$ref": "#/components/schemas/CampaignPaymentModel" + }, + "nullable": true, + "type": "array" + }, + "statuses": { + "description": "Список статусов креативов", + "items": { + "$ref": "#/components/schemas/CreativesStatus" + }, + "nullable": true, + "type": "array" + }, + "timeFrame": { + "$ref": "#/components/schemas/DateRange" + } + }, + "type": "object" + }, + "CreativesStatus": { + "description": "Статус креатива", + "enum": [ + "draft", + "ready_for_moderation", + "in_moderation", + "moderation_failed", + "erir_registration", + "will_launch_soon", + "active", + "pausing", + "paused", + "unpausing", + "stopped", + "finished", + "archived" + ], + "type": "string" + }, + "CreteIntermediaryIn": { + "description": "Данные исполнителя по договору. Для доп соглашений не передаем. Для договоров обязательно передавать.", + "nullable": true, + "properties": { + "actualAddress": { + "description": "Почтовый адрес", + "type": "string" + }, + "inn": { + "description": "ИНН ЮЛ/ИП", + "type": "string" + }, + "kpp": { + "description": "КПП ЮЛ, для ИП не передаем", + "nullable": true, + "type": "string" + }, + "legalAddress": { + "description": "Юридически адрес", + "type": "string" + }, + "legalType": { + "$ref": "#/components/schemas/LegalType" + }, + "longName": { + "description": "Полное имя ЮЛ/ИП", + "type": "string" + }, + "ogrn": { + "description": "ОГРНИП для ИП, ОРГН для ЮЛ", + "type": "string" + }, + "shortName": { + "description": "Короткое имя ЮЛ/ИП", + "type": "string" + } + }, + "type": "object" + }, + "DateRange": { + "description": "Диапазон дат", + "nullable": true, + "properties": { + "from": { + "description": "Дата начала в формате YYYY-MM-DD", + "format": "date", + "type": "string" + }, + "to": { + "description": "Дата окончания в формате YYYY-MM-DD", + "format": "date", + "type": "string" + } + }, + "type": "object" + }, + "DetailedError": { + "properties": { + "code": { + "type": "string" + }, + "errors": { + "$ref": "#/components/schemas/DetailedErrors" + }, + "message": { + "type": "string" + } + }, + "required": [ + "message", + "code" + ], + "type": "object" + }, + "DetailedErrorItem": { + "properties": { + "id": { + "description": "ID сущности", + "format": "int64", + "type": "integer" + }, + "message": { + "description": "Описание ошибки", + "type": "string" + } + }, + "required": [ + "id", + "message" + ], + "type": "object" + }, + "DetailedErrors": { + "description": "Ошибки по ID сущности", + "items": { + "$ref": "#/components/schemas/DetailedErrorItem" + }, + "type": "array" + }, + "Disclaimer": { + "properties": { + "inputs": { + "items": { + "$ref": "#/components/schemas/DisclaimerInput" + }, + "type": "array" + }, + "key": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "key", + "title", + "inputs" + ], + "type": "object" + }, + "DisclaimerInput": { + "properties": { + "description": { + "type": "string" + }, + "key": { + "type": "string" + }, + "valueType": { + "type": "string" + } + }, + "required": [ + "key", + "description", + "valueType" + ], + "type": "object" + }, + "EmptyResponse": { + "type": "object" + }, + "EnumObject": { + "properties": { + "children": { + "items": { + "$ref": "#/components/schemas/EnumObject" + }, + "type": "array" + }, + "name": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "name", + "value" + ], + "type": "object" + }, + "Error": { + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "message", + "code" + ], + "type": "object" + }, + "FrequencyPeriod": { + "description": "Период частотного ограничения", + "enum": [ + "no_limit", + "day", + "week", + "month" + ], + "type": "string" + }, + "FrequencyRule": { + "description": "Правило частотного ограничения", + "properties": { + "count": { + "description": "Количество показов за указанный период", + "minimum": 0, + "type": "integer" + }, + "period": { + "$ref": "#/components/schemas/FrequencyPeriod" + } + }, + "required": [ + "count", + "period" + ], + "type": "object" + }, + "Group": { + "properties": { + "accountID": { + "description": "ID аккаунта", + "type": "integer" + }, + "actions": { + "description": "Доступные действия с группой", + "items": { + "type": "string" + }, + "type": "array" + }, + "activitySchedule": { + "description": "Расписание активности по дням", + "properties": { + "friday": { + "$ref": "#/components/schemas/ActivityScheduleHours" + }, + "monday": { + "$ref": "#/components/schemas/ActivityScheduleHours" + }, + "saturday": { + "$ref": "#/components/schemas/ActivityScheduleHours" + }, + "sunday": { + "$ref": "#/components/schemas/ActivityScheduleHours" + }, + "thursday": { + "$ref": "#/components/schemas/ActivityScheduleHours" + }, + "tuesday": { + "$ref": "#/components/schemas/ActivityScheduleHours" + }, + "wednesday": { + "$ref": "#/components/schemas/ActivityScheduleHours" + } + }, + "type": "object" + }, + "advertiserID": { + "description": "ID рекламодателя", + "type": "integer" + }, + "audienceType": { + "$ref": "#/components/schemas/AudienceType" + }, + "budget": { + "description": "Бюджет группы в рублях с НДС", + "type": "integer" + }, + "budgetFrequency": { + "$ref": "#/components/schemas/BudgetFrequency" + }, + "budgetKopeks": { + "description": "Бюджет группы в копейках с НДС", + "type": "integer" + }, + "campaignID": { + "description": "ID кампании", + "type": "integer" + }, + "campaignType": { + "$ref": "#/components/schemas/CampaignType" + }, + "createdAt": { + "description": "Дата создания группы", + "format": "date-time", + "type": "string" + }, + "format": { + "$ref": "#/components/schemas/GroupFormat" + }, + "frequencyCount": { + "description": "Частота показов в рамках периода", + "type": "integer" + }, + "frequencyPeriod": { + "$ref": "#/components/schemas/FrequencyPeriod" + }, + "frequencyRules": { + "description": "Правила частотного ограничения", + "items": { + "$ref": "#/components/schemas/FrequencyRule" + }, + "type": "array" + }, + "haveCreative": { + "description": "Есть ли в группе креатив", + "nullable": true, + "type": "boolean" + }, + "id": { + "description": "ID группы", + "type": "integer" + }, + "managerID": { + "description": "ID менеджера, ответственного за кампанию (userID)", + "type": "integer" + }, + "name": { + "description": "Название группы", + "type": "string" + }, + "pace": { + "$ref": "#/components/schemas/Paces" + }, + "paymentModel": { + "$ref": "#/components/schemas/CampaignPaymentModel" + }, + "periodEndAt": { + "description": "Конец периода кампании", + "format": "date-time", + "nullable": true, + "type": "string" + }, + "periodStartAt": { + "description": "Начало периода кампании", + "format": "date-time", + "nullable": true, + "type": "string" + }, + "periodTimezone": { + "description": "Таймзона периода показов", + "type": "string" + }, + "price": { + "description": "Цена в рублях с НДС", + "type": "integer" + }, + "priceControl": { + "$ref": "#/components/schemas/GroupPriceControl" + }, + "priceKopeks": { + "description": "Цена в копейках с НДС", + "type": "integer" + }, + "scheduleType": { + "$ref": "#/components/schemas/ScheduleType" + }, + "startASAP": { + "description": "Запускать как можно скорее", + "type": "boolean" + }, + "status": { + "$ref": "#/components/schemas/GroupsStatus" + }, + "statusReasons": { + "$ref": "#/components/schemas/StatusReasons" + }, + "targetingAgeIDs": { + "description": "ID возрастных сегментов", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingAudienceIDs": { + "description": "ID аудиторий", + "items": { + "type": "string" + }, + "type": "array" + }, + "targetingFamilyStatusIDs": { + "description": "ID семейного статуса", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingGenderIDs": { + "description": "ID пола", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingIncomeIDs": { + "description": "ID доходных сегментов", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingInterestIDs": { + "description": "ID интересов", + "items": { + "type": "string" + }, + "type": "array" + }, + "targetingLocationIDs": { + "description": "ID локаций", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingParentStatusIDs": { + "description": "ID родительского статуса", + "items": { + "type": "integer" + }, + "type": "array" + }, + "topStatusReason": { + "$ref": "#/components/schemas/TopStatusReason" + }, + "updatedAt": { + "description": "Дата обновления группы", + "format": "date-time", + "type": "string" + }, + "userID": { + "description": "ID пользователя, создавшего группу", + "type": "integer" + } + }, + "required": [ + "statusReasons", + "topStatusReason", + "startASAP", + "frequencyCount", + "frequencyRules" + ], + "type": "object" + }, + "GroupFormat": { + "description": "Формат группы объявлений", + "enum": [ + "mediaRoot", + "mediaSellerProfile", + "mediaPremium", + "media", + "native", + "htmlPremium", + "html", + "video" + ], + "type": "string" + }, + "GroupPriceControl": { + "description": "Контроль цены группы", + "enum": [ + "manual", + "auto" + ], + "type": "string" + }, + "GroupReferenceData": { + "properties": { + "bannerFormat": { + "items": { + "$ref": "#/components/schemas/EnumObject" + }, + "type": "array" + }, + "budgetThresholds": { + "items": { + "$ref": "#/components/schemas/ThresholdItem" + }, + "type": "array" + }, + "priceThresholds": { + "items": { + "$ref": "#/components/schemas/ThresholdItem" + }, + "type": "array" + }, + "targetingAgeIDs": { + "items": { + "$ref": "#/components/schemas/IdNameObject" + }, + "type": "array" + }, + "targetingAudienceIDs": { + "items": { + "$ref": "#/components/schemas/StringIdNameObject" + }, + "type": "array" + }, + "targetingFamilyStatusIDs": { + "items": { + "$ref": "#/components/schemas/IdNameObject" + }, + "type": "array" + }, + "targetingGenderIDs": { + "items": { + "$ref": "#/components/schemas/IdNameObject" + }, + "type": "array" + }, + "targetingIncomeIDs": { + "items": { + "$ref": "#/components/schemas/IdNameObject" + }, + "type": "array" + }, + "targetingInterestIDs": { + "items": { + "$ref": "#/components/schemas/EnumObject" + }, + "type": "array" + }, + "targetingLocationIDs": { + "items": { + "$ref": "#/components/schemas/IdNameObject" + }, + "type": "array" + }, + "targetingParentStatusIDs": { + "items": { + "$ref": "#/components/schemas/IdNameObject" + }, + "type": "array" + } + }, + "required": [ + "bannerFormat", + "priceThresholds", + "budgetThresholds", + "targetingLocationIDs", + "targetingInterestIDs", + "targetingAgeIDs", + "targetingGenderIDs", + "targetingIncomeIDs", + "targetingAudienceIDs", + "targetingFamilyStatusIDs", + "targetingParentStatusIDs" + ], + "type": "object" + }, + "GroupStatistic": { + "description": "Статистика группы", + "properties": { + "data": { + "description": "Статистика в разбивке по дням", + "items": { + "$ref": "#/components/schemas/StatsData" + }, + "type": "array" + }, + "id": { + "description": "ID группы", + "type": "integer" + }, + "name": { + "description": "Название группы", + "type": "string" + }, + "totalData": { + "$ref": "#/components/schemas/StatsData" + } + }, + "required": [ + "id", + "name", + "data", + "totalData" + ], + "type": "object" + }, + "GroupsFilter": { + "properties": { + "advertisers": { + "description": "Список ID рекламодателей", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "campaignIDs": { + "description": "Список ID кампаний", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "ids": { + "description": "Список ID групп", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "managers": { + "description": "Список ID менеджеров", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "paces": { + "description": "Скорости показов", + "items": { + "$ref": "#/components/schemas/Paces" + }, + "nullable": true, + "type": "array" + }, + "paymentModels": { + "description": "Список моделей оплаты", + "items": { + "$ref": "#/components/schemas/CampaignPaymentModel" + }, + "nullable": true, + "type": "array" + }, + "statuses": { + "description": "Список статусов групп", + "items": { + "$ref": "#/components/schemas/GroupsStatus" + }, + "nullable": true, + "type": "array" + }, + "timeFrame": { + "$ref": "#/components/schemas/DateRange" + } + }, + "type": "object" + }, + "GroupsStatus": { + "description": "Статус группы объявлений", + "enum": [ + "draft", + "in_moderation", + "moderation_failed", + "will_launch_soon", + "active", + "will_stop_soon", + "pausing", + "paused", + "unpausing", + "stopped", + "finished", + "archived" + ], + "type": "string" + }, + "IdNameObject": { + "properties": { + "children": { + "items": { + "$ref": "#/components/schemas/IdNameObject" + }, + "type": "array" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "KKTUFieldValue": { + "properties": { + "key": { + "description": "Внутренний ключ поля", + "type": "string" + }, + "value": { + "description": "Значение поля, приведённое к строке", + "type": "string" + } + }, + "required": [ + "key", + "value" + ], + "type": "object" + }, + "KktuItem": { + "properties": { + "category": { + "type": "string" + }, + "code": { + "type": "string" + }, + "level": { + "type": "integer" + }, + "subCategory": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "code", + "title", + "level", + "subCategory", + "category" + ], + "type": "object" + }, + "LegalInfo": { + "deprecated": true, + "description": "Устаревшее представление юридических данных. Используйте kktuFields.", + "properties": { + "ageRestriction": { + "description": "Возрастное ограничение", + "nullable": true, + "type": "integer" + }, + "description": { + "description": "Юридическое описание", + "nullable": true, + "type": "string" + }, + "kktu": { + "description": "ККТУ", + "type": "string" + }, + "notes": { + "description": "Примечания", + "nullable": true, + "type": "string" + } + }, + "type": "object" + }, + "LegalRole": { + "description": "Роль ЮЛ", + "enum": [ + "rd", + "ra", + "rr" + ], + "type": "string" + }, + "LegalType": { + "description": "Тип ЮЛ", + "enum": [ + "ul", + "ip" + ], + "type": "string" + }, + "ObjectSize": { + "properties": { + "height": { + "type": "integer" + }, + "width": { + "type": "integer" + } + }, + "required": [ + "width", + "height" + ], + "type": "object" + }, + "Paces": { + "description": "Скорости показов", + "enum": [ + "asap", + "even" + ], + "type": "string" + }, + "PeriodTimezone": { + "description": "Таймзона периода показов", + "enum": [ + "Europe/Kaliningrad", + "Europe/Moscow", + "Europe/Samara", + "Asia/Yekaterinburg", + "Asia/Omsk", + "Asia/Krasnoyarsk", + "Asia/Irkutsk", + "Asia/Yakutsk", + "Asia/Vladivostok", + "Asia/Magadan", + "Asia/Kamchatka" + ], + "type": "string" + }, + "ScheduleType": { + "description": "Тип расписания показов", + "enum": [ + "always", + "weekdays9To20", + "custom" + ], + "type": "string" + }, + "ShortAccount": { + "properties": { + "id": { + "type": "integer" + }, + "shortName": { + "type": "string" + } + }, + "required": [ + "id", + "shortName" + ], + "type": "object" + }, + "ShortAccountWithBalance": { + "properties": { + "account": { + "$ref": "#/components/schemas/ShortAccount" + }, + "balance": { + "$ref": "#/components/schemas/V1GetAccountBalanceByIdOut" + } + }, + "required": [ + "account", + "balance" + ], + "type": "object" + }, + "ShortAccountWithContract": { + "properties": { + "account": { + "$ref": "#/components/schemas/ShortAccount" + }, + "contract": { + "$ref": "#/components/schemas/ContractForChildAccount" + } + }, + "required": [ + "account" + ], + "type": "object" + }, + "StatsData": { + "description": "Данные статистики за период", + "properties": { + "clicks": { + "description": "Количество кликов", + "type": "integer" + }, + "cpc": { + "description": "Средняя стоимость CPC", + "format": "float", + "type": "number" + }, + "cpm": { + "description": "Средняя стоимость CPM", + "format": "float", + "type": "number" + }, + "ctr": { + "description": "CTR (Click-Through Rate)", + "format": "float", + "type": "number" + }, + "q25": { + "description": "Доля просмотров видео на 25%", + "format": "float", + "nullable": true, + "type": "number" + }, + "q50": { + "description": "Доля просмотров видео на 50%", + "format": "float", + "nullable": true, + "type": "number" + }, + "q75": { + "description": "Доля просмотров видео на 75%", + "format": "float", + "nullable": true, + "type": "number" + }, + "spend": { + "description": "Потрачено денег в рублях", + "type": "integer" + }, + "spendBonus": { + "description": "Потрачено бонусов в рублях", + "type": "integer" + }, + "spendBonusKopeks": { + "description": "Потрачено бонусов в копейках", + "type": "integer" + }, + "spendKopeks": { + "description": "Потрачено денег в копейках", + "type": "integer" + }, + "timestamp": { + "description": "Временная метка (гранулярность по дням). Заполняется в data[] и отсутствует в totalData.", + "format": "date-time", + "nullable": true, + "type": "string" + }, + "videoViews100": { + "description": "Количество просмотров видео на 100%", + "nullable": true, + "type": "integer" + }, + "videoViews25": { + "description": "Количество просмотров видео на 25%", + "nullable": true, + "type": "integer" + }, + "videoViews50": { + "description": "Количество просмотров видео на 50%", + "nullable": true, + "type": "integer" + }, + "videoViews75": { + "description": "Количество просмотров видео на 75%", + "nullable": true, + "type": "integer" + }, + "views": { + "description": "Количество показов", + "type": "integer" + }, + "vtr": { + "description": "Доля просмотров видео на 100%", + "format": "float", + "nullable": true, + "type": "number" + } + }, + "required": [ + "views", + "clicks", + "ctr", + "spend", + "spendBonus", + "cpm", + "cpc" + ], + "type": "object" + }, + "StatusReasons": { + "description": "Все коды причин текущего статуса. При отсутствии причин возвращается []. Порядок не отражает приоритет; главная причина передаётся в topStatusReason. Возможны новые коды причин.", + "example": [ + "manual", + "insufficient_funds" + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "StringIdNameObject": { + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "TemplateData": { + "properties": { + "fields": { + "items": { + "$ref": "#/components/schemas/TemplateField" + }, + "type": "array" + }, + "isOptional": { + "type": "boolean" + }, + "logoRatio": { + "items": { + "$ref": "#/components/schemas/ObjectSize" + }, + "type": "array" + }, + "mediaRatio": { + "$ref": "#/components/schemas/ObjectSize" + }, + "platforms": { + "items": { + "type": "string" + }, + "type": "array" + }, + "templateID": { + "type": "integer" + } + }, + "required": [ + "templateID", + "platforms", + "mediaRatio", + "logoRatio", + "fields", + "isOptional" + ], + "type": "object" + }, + "TemplateField": { + "properties": { + "canOverride": { + "nullable": true, + "type": "boolean" + }, + "defaultValue": { + "nullable": true, + "type": "string" + }, + "fieldType": { + "type": "string" + }, + "isRequired": { + "nullable": true, + "type": "boolean" + }, + "key": { + "type": "string" + } + }, + "required": [ + "fieldType", + "key" + ], + "type": "object" + }, + "ThresholdItem": { + "properties": { + "groupFormat": { + "$ref": "#/components/schemas/GroupFormat" + }, + "value": { + "description": "Минимальное значение в рублях", + "type": "integer" + }, + "valueKopeks": { + "description": "Минимальное значение в копейках", + "type": "integer" + } + }, + "required": [ + "groupFormat", + "value", + "valueKopeks" + ], + "type": "object" + }, + "TopStatusReason": { + "description": "Главная причина текущего статуса, определённая API. Если главная причина не определена, возвращается пустая строка, даже если statusReasons не пуст. Возможны новые коды причин.", + "example": "insufficient_funds", + "type": "string" + }, + "User": { + "properties": { + "hasLoggedIn": { + "description": "Флаг, показывающий, заходил ли пользователь в аккаунт", + "type": "boolean" + }, + "id": { + "description": "ID пользователя", + "type": "integer" + }, + "role": { + "$ref": "#/components/schemas/UserRole" + } + }, + "required": [ + "id", + "role", + "hasLoggedIn" + ], + "type": "object" + }, + "UserRole": { + "description": "Роль пользователя в рекламном кабинете", + "enum": [ + "admin", + "viewer" + ], + "type": "string" + }, + "V1AddUserIn": { + "description": "Payload добавления пользователя в аккаунт", + "properties": { + "role": { + "$ref": "#/components/schemas/UserRole" + }, + "userId": { + "description": "ID пользователя авито", + "type": "integer" + } + }, + "required": [ + "userId", + "role" + ], + "type": "object" + }, + "V1ChangeBudgetIn": { + "description": "Payload для изменения бюджета группы", + "properties": { + "budget": { + "description": "Новый бюджет группы в рублях с НДС", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "budget" + ], + "type": "object" + }, + "V1ChangePriceIn": { + "description": "Payload для изменения ставки группы", + "properties": { + "price": { + "description": "Новая ставка группы в рублях с НДС", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "price" + ], + "type": "object" + }, + "V1CopyCampaignGroup": { + "description": "Группа и список креативов для копирования", + "properties": { + "creativeIDs": { + "description": "Список ID копируемых креативов. Если не передано или передано пустым списком, копируется только группа", + "items": { + "minimum": 1, + "type": "integer" + }, + "type": "array" + }, + "groupID": { + "description": "ID копируемой группы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "groupID" + ], + "type": "object" + }, + "V1CopyCampaignIn": { + "description": "Payload копирования кампании аккаунта", + "properties": { + "campaignID": { + "description": "ID копируемой кампании", + "minimum": 1, + "type": "integer" + }, + "groups": { + "description": "Группы и креативы, которые нужно скопировать вместе с кампанией. Если не передано или передано пустым списком, копируется только кампания", + "items": { + "$ref": "#/components/schemas/V1CopyCampaignGroup" + }, + "type": "array" + } + }, + "required": [ + "campaignID" + ], + "type": "object" + }, + "V1CopyCampaignOut": { + "properties": { + "campaignID": { + "description": "ID новой кампании", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "campaignID" + ], + "type": "object" + }, + "V1CopyCreativeIn": { + "description": "Payload копирования креатива аккаунта", + "properties": { + "creativeID": { + "description": "ID копируемого креатива", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "creativeID" + ], + "type": "object" + }, + "V1CopyCreativeOut": { + "properties": { + "creativeID": { + "description": "ID нового креатива", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "creativeID" + ], + "type": "object" + }, + "V1CopyGroupIn": { + "description": "Payload копирования группы аккаунта", + "properties": { + "creativeIDs": { + "description": "Список ID креативов, которые нужно скопировать вместе с группой. Если не передано или передано пустым списком, копируется только группа", + "items": { + "minimum": 1, + "type": "integer" + }, + "type": "array" + }, + "groupID": { + "description": "ID копируемой группы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "groupID" + ], + "type": "object" + }, + "V1CopyGroupOut": { + "properties": { + "newGroupID": { + "description": "ID новой группы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "newGroupID" + ], + "type": "object" + }, + "V1CreateAccountIn": { + "description": "Payload создания аккаунта", + "properties": { + "actualAddress": { + "description": "Фактический адрес. Если не передан, используется legalAddress.", + "nullable": true, + "type": "string" + }, + "contact": { + "description": "Контактное лицо", + "properties": { + "name": { + "description": "ФИО контактного лица", + "type": "string" + }, + "phone": { + "description": "Контактный телефон", + "type": "string" + } + }, + "required": [ + "name", + "phone" + ], + "type": "object" + }, + "inn": { + "description": "ИНН организации или ИП", + "type": "string" + }, + "kpp": { + "description": "КПП организации", + "nullable": true, + "type": "string" + }, + "legalAddress": { + "description": "Юридический адрес или адрес регистрации", + "type": "string" + }, + "legalType": { + "$ref": "#/components/schemas/LegalType" + }, + "longName": { + "description": "Полное наименование организации или ИП", + "type": "string" + }, + "ogrn": { + "description": "ОГРН или ОГРНИП", + "type": "string" + }, + "shortName": { + "description": "Краткое название аккаунта", + "type": "string" + } + }, + "required": [ + "inn", + "shortName", + "longName", + "ogrn", + "legalAddress", + "legalType", + "contact" + ], + "type": "object" + }, + "V1CreateAccountOut": { + "properties": { + "accountID": { + "type": "integer" + }, + "warnings": { + "description": "Предупреждения о частично невыполненных sandbox-операциях. Если массив пустой, аккаунт подготовлен полностью.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "accountID", + "warnings" + ], + "type": "object" + }, + "V1CreateAdvertiserIn": { + "description": "Payload создания рекламодателя", + "properties": { + "actualAddress": { + "description": "Фактический адрес. Если не передан, используется legalAddress. Пример корректного адреса: 127015, г. Москва, ул. Лесная, д. 7", + "nullable": true, + "type": "string" + }, + "inn": { + "description": "ИНН организации", + "type": "string" + }, + "kpp": { + "description": "КПП организации", + "nullable": true, + "type": "string" + }, + "legalAddress": { + "description": "Юридический адрес или адрес регистрации. Пример корректного адреса: 127015, г. Москва, ул. Лесная, д. 7", + "type": "string" + }, + "legalRole": { + "$ref": "#/components/schemas/LegalRole" + }, + "legalType": { + "$ref": "#/components/schemas/LegalType" + }, + "longName": { + "description": "Полное наименование организации или ИП", + "type": "string" + }, + "ogrn": { + "description": "ОГРН или ОГРНИП", + "type": "string" + }, + "shortName": { + "description": "Краткое наименование организации или ИП", + "type": "string" + } + }, + "required": [ + "inn", + "shortName", + "longName", + "ogrn", + "legalAddress", + "legalRole", + "legalType" + ], + "type": "object" + }, + "V1CreateAdvertiserOut": { + "properties": { + "id": { + "type": "integer" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "V1CreateCampaignIn": { + "description": "Payload запроса на создание кампании", + "properties": { + "additionalAgreementID": { + "description": "ID дополнительного соглашения", + "nullable": true, + "type": "integer" + }, + "advertiserID": { + "description": "ID рекламодателя. Может быть null, если для аккаунта включен флаг sSelfAdvertisingEnabled=true (используется 1 кейс)", + "nullable": true, + "type": "integer" + }, + "campaignGoals": { + "description": "Цели кампании. Пока поддерживается только пустой массив", + "items": { + "type": "string" + }, + "maxItems": 0, + "type": "array" + }, + "campaignStrategy": { + "$ref": "#/components/schemas/CampaignStrategy" + }, + "campaignType": { + "$ref": "#/components/schemas/CreateCampaignType" + }, + "contractID": { + "description": "ID договора. Может быть null, если advertiserID=null. Если advertiserID задан, поле обязательно и принимает контракт 2 или 3 кейса", + "nullable": true, + "type": "integer" + }, + "goalType": { + "$ref": "#/components/schemas/CampaignGoalType" + }, + "landingPage": { + "description": "Посадочная страница. Пока поле не сохраняется", + "nullable": true, + "type": "string" + }, + "landingType": { + "$ref": "#/components/schemas/CampaignLandingType" + }, + "managerID": { + "description": "ID менеджера, ответственного за кампанию (userID)", + "type": "integer" + }, + "name": { + "description": "Название кампании", + "type": "string" + }, + "paymentModel": { + "$ref": "#/components/schemas/CreateCampaignPaymentModel" + } + }, + "required": [ + "name", + "goalType", + "campaignType", + "paymentModel", + "campaignStrategy", + "campaignGoals", + "managerID", + "landingType" + ], + "type": "object" + }, + "V1CreateCampaignOut": { + "properties": { + "id": { + "type": "integer" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "V1CreateContractIn": { + "description": "Payload запроса на создание договора.\nБазово обязательны `description`, `advertiserId`, `type`.\nДля `type = service` дополнительно передаются `subject`, `isReportingRequired`, `date`, `number`; `cid` не передаётся.\nДля `type = intermediary` дополнительно передаются `subject`, `object`, `isReportingRequired`, `isFundsAllocationToPrincipal`, `date`, `number`; `cid` не передаётся.\nДля `type = external` передаётся `cid`; `parentId` не передаётся.\nДополнительное соглашение создаётся через `parentId` к родительскому договору, без отдельного `type = additional`.\nЕсли `parentId` задан, `intermediary` не передаётся; если `parentId` не задан, `intermediary` обязателен.\n", + "properties": { + "advertiserId": { + "description": "Id рекламодателя. Указываем только рекламодателей которые не являются аккаунтом. Если рекламодатель и аккаунт одно и тоже ЮЛ, договор создавать не надо", + "type": "integer" + }, + "cid": { + "description": "CID внешнего договора, заполняется только для type = external.", + "nullable": true, + "type": "string" + }, + "date": { + "description": "Дата в формате YYYY-MM-DD. Можно не передавать только для type = external.", + "format": "date", + "nullable": true, + "type": "string" + }, + "description": { + "$ref": "#/components/schemas/ContractCounterpartyType" + }, + "intermediary": { + "$ref": "#/components/schemas/CreteIntermediaryIn" + }, + "isFundsAllocationToPrincipal": { + "description": "Денежные средства на размещение рекламы идут в сторону принципала", + "type": "boolean" + }, + "isReportingRequired": { + "description": "На исполнителе лежит обязанность отчитываться по креативам", + "type": "boolean" + }, + "number": { + "description": "Номер договора. Можно не передавать только для type = external.", + "nullable": true, + "type": "string" + }, + "object": { + "$ref": "#/components/schemas/ContractAction" + }, + "parentId": { + "description": "ID родительского договора для доп. соглашения", + "nullable": true, + "type": "integer" + }, + "subject": { + "$ref": "#/components/schemas/ContractSubject" + }, + "type": { + "$ref": "#/components/schemas/ContractType" + } + }, + "required": [ + "description", + "advertiserId", + "type" + ], + "type": "object" + }, + "V1CreateContractOut": { + "properties": { + "id": { + "type": "integer" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "V1CreateGroupIn": { + "description": "Payload запроса на создание группы", + "properties": { + "activitySchedule": { + "$ref": "#/components/schemas/CreateGroupActivitySchedule" + }, + "bannerFormat": { + "$ref": "#/components/schemas/BannerFormat" + }, + "budget": { + "description": "Бюджет группы в рублях с НДС", + "minimum": 1, + "type": "integer" + }, + "budgetFrequency": { + "$ref": "#/components/schemas/BudgetFrequency" + }, + "campaignID": { + "description": "ID кампании", + "type": "integer" + }, + "frequencyRules": { + "description": "Правила ограничения частоты показов. Если поле отсутствует, передано null или передан пустой массив, ограничение не применяется.", + "items": { + "$ref": "#/components/schemas/FrequencyRule" + }, + "maxItems": 2, + "type": "array" + }, + "name": { + "description": "Название группы", + "maxLength": 99, + "minLength": 1, + "type": "string" + }, + "pace": { + "$ref": "#/components/schemas/Paces" + }, + "periodEndAt": { + "description": "Окончание периода показов в формате RFC3339, например 2026-12-31T23:59:59+03:00", + "format": "date-time", + "nullable": true, + "type": "string" + }, + "periodStartAt": { + "description": "Начало периода показов в формате RFC3339, например 2026-07-01T10:00:00+03:00", + "format": "date-time", + "nullable": true, + "type": "string" + }, + "periodTimezone": { + "$ref": "#/components/schemas/PeriodTimezone" + }, + "price": { + "description": "Ставка в рублях с НДС", + "minimum": 1, + "type": "integer" + }, + "priceControl": { + "$ref": "#/components/schemas/GroupPriceControl" + }, + "scheduleType": { + "$ref": "#/components/schemas/ScheduleType" + }, + "startASAP": { + "description": "Запускать как можно скорее", + "type": "boolean" + }, + "targetingAgeIDs": { + "description": "ID возрастных сегментов", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingFamilyStatusIDs": { + "description": "ID family status сегментов", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + }, + "targetingGenderIDs": { + "description": "ID пола", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingIncomeIDs": { + "description": "ID доходных сегментов", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingInterestIDs": { + "description": "ID интересов", + "items": { + "type": "string" + }, + "type": "array" + }, + "targetingLocationIDs": { + "description": "ID локаций", + "items": { + "type": "integer" + }, + "type": "array" + }, + "targetingParentStatusIDs": { + "description": "ID parent status сегментов", + "items": { + "type": "integer" + }, + "nullable": true, + "type": "array" + } + }, + "required": [ + "campaignID", + "name", + "budget", + "budgetFrequency", + "price", + "priceControl", + "pace", + "frequencyRules", + "scheduleType", + "periodTimezone", + "startASAP", + "bannerFormat", + "targetingLocationIDs", + "targetingInterestIDs", + "targetingGenderIDs", + "targetingAgeIDs", + "targetingIncomeIDs" + ], + "type": "object" + }, + "V1CreateGroupOut": { + "properties": { + "id": { + "description": "ID созданной группы", + "type": "integer" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "V1CreateNonPayerAccountIn": { + "description": "Payload создания аккаунта", + "properties": { + "isSelfAdvertisingEnabled": { + "description": "Флаг разрешающий рекламировать родительский аккаунт. Если вам надо рекламировать нового рекламодателя без возможности рекламировать родителя, выставлять - false", + "nullable": true, + "type": "boolean" + }, + "shortName": { + "description": "Краткое название дочернего аккаунта, меньше 64 символов", + "type": "string" + } + }, + "required": [ + "shortName", + "isSelfAdvertisingEnabled" + ], + "type": "object" + }, + "V1CreateNonPayerAccountOut": { + "properties": { + "accountID": { + "type": "integer" + }, + "clientKey": { + "type": "string" + }, + "clientSecret": { + "type": "string" + } + }, + "required": [ + "accountID", + "clientKey", + "clientSecret" + ], + "type": "object" + }, + "V1DeleteCampaignsIn": { + "description": "Payload удаления кампаний аккаунта", + "properties": { + "campaignIDs": { + "description": "Список ID кампаний", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "campaignIDs" + ], + "type": "object" + }, + "V1DeleteCreativesIn": { + "description": "Payload удаления креативов аккаунта", + "properties": { + "creativeIDs": { + "description": "Список ID креативов", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "creativeIDs" + ], + "type": "object" + }, + "V1DeleteGroupsIn": { + "description": "Payload удаления групп аккаунта", + "properties": { + "groupIDs": { + "description": "Список ID групп", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "groupIDs" + ], + "type": "object" + }, + "V1GetAccountBalanceByIdOut": { + "properties": { + "balance": { + "description": "Баланс аккаунта в рублях", + "type": "integer" + }, + "balanceKopeks": { + "description": "Баланс аккаунта в копейках", + "type": "integer" + }, + "bonusBalance": { + "description": "Баланс бонусов на аккаунте в рублях", + "type": "integer" + }, + "bonusBalanceKopeks": { + "description": "Баланс бонусов на аккаунте в копейках", + "type": "integer" + } + }, + "required": [ + "balance", + "balanceKopeks", + "bonusBalance", + "bonusBalanceKopeks" + ], + "type": "object" + }, + "V1GetAccountByIdOut": { + "properties": { + "account": { + "$ref": "#/components/schemas/Account" + } + }, + "type": "object" + }, + "V1GetAdvertisersListIn": { + "description": "Payload запроса на получение списка рекламодателей", + "properties": { + "filter": { + "$ref": "#/components/schemas/AdvertiserFilter" + }, + "limit": { + "default": 20, + "description": "Количество записей на странице", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "page": { + "default": 1, + "description": "Номер страницы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "filter", + "limit", + "page" + ], + "type": "object" + }, + "V1GetAdvertisersListOut": { + "properties": { + "advertisers": { + "items": { + "$ref": "#/components/schemas/Advertiser" + }, + "type": "array" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "total", + "advertisers" + ], + "type": "object" + }, + "V1GetCampaignByIdWithFieldsOut": { + "properties": { + "campaign": { + "$ref": "#/components/schemas/Campaign" + }, + "editableFields": { + "items": { + "$ref": "#/components/schemas/CampaignFieldName" + }, + "type": "array" + }, + "warnings": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "campaign", + "warnings", + "editableFields" + ], + "type": "object" + }, + "V1GetCampaignStatisticIn": { + "description": "Request body для запроса статистики по кампании. Максимальный период между dateFrom и dateTo — 100 дней.", + "properties": { + "dateFrom": { + "description": "Дата начала периода в формате YYYY-MM-DD", + "format": "date", + "type": "string" + }, + "dateTo": { + "description": "Дата окончания периода в формате YYYY-MM-DD", + "format": "date", + "type": "string" + } + }, + "required": [ + "dateFrom", + "dateTo" + ], + "type": "object" + }, + "V1GetCampaignStatisticOut": { + "description": "Статистика по кампании", + "properties": { + "campaign": { + "$ref": "#/components/schemas/CampaignStatistic" + }, + "creatives": { + "description": "Статистика по креативам кампании", + "items": { + "$ref": "#/components/schemas/CreativeStatistic" + }, + "type": "array" + }, + "groups": { + "description": "Статистика по группам кампании", + "items": { + "$ref": "#/components/schemas/GroupStatistic" + }, + "type": "array" + } + }, + "required": [ + "campaign", + "groups", + "creatives" + ], + "type": "object" + }, + "V1GetCampaignsListIn": { + "description": "Payload запроса на получение списка кампаний", + "properties": { + "filter": { + "$ref": "#/components/schemas/CampaignsFilter" + }, + "limit": { + "default": 20, + "description": "Количество записей на странице", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "page": { + "default": 1, + "description": "Номер страницы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "filter", + "limit", + "page" + ], + "type": "object" + }, + "V1GetCampaignsListOut": { + "properties": { + "campaigns": { + "items": { + "$ref": "#/components/schemas/Campaign" + }, + "type": "array" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "total", + "campaigns" + ], + "type": "object" + }, + "V1GetChildAccountsListOut": { + "properties": { + "children": { + "items": { + "$ref": "#/components/schemas/ShortAccountWithContract" + }, + "type": "array" + } + }, + "required": [ + "children" + ], + "type": "object" + }, + "V1GetChildAccountsWithBalancesListOut": { + "properties": { + "children": { + "items": { + "$ref": "#/components/schemas/ShortAccountWithBalance" + }, + "type": "array" + } + }, + "required": [ + "children" + ], + "type": "object" + }, + "V1GetContractsListIn": { + "description": "Payload запроса на получение списка договоров", + "properties": { + "filter": { + "$ref": "#/components/schemas/ContractsFilter" + }, + "limit": { + "default": 20, + "description": "Количество записей на странице", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "page": { + "default": 1, + "description": "Номер страницы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "filter", + "limit", + "page" + ], + "type": "object" + }, + "V1GetContractsListOut": { + "properties": { + "contracts": { + "items": { + "$ref": "#/components/schemas/Contract" + }, + "type": "array" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "total", + "contracts" + ], + "type": "object" + }, + "V1GetCreativesListIn": { + "description": "Payload запроса на получение списка креативов", + "properties": { + "filter": { + "$ref": "#/components/schemas/CreativesFilter" + }, + "limit": { + "default": 20, + "description": "Количество записей на странице", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "page": { + "default": 1, + "description": "Номер страницы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "filter", + "limit", + "page" + ], + "type": "object" + }, + "V1GetCreativesListOut": { + "properties": { + "creatives": { + "items": { + "$ref": "#/components/schemas/Creative" + }, + "type": "array" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "total", + "creatives" + ], + "type": "object" + }, + "V1GetCreativesStatisticIn": { + "description": "Request body для запроса статистики по креативам кампании. Максимальный период между dateFrom и dateTo — 100 дней.", + "properties": { + "creativeIDs": { + "description": "Список ID креативов для получения статистики", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + }, + "dateFrom": { + "description": "Дата начала периода в формате YYYY-MM-DD", + "format": "date", + "type": "string" + }, + "dateTo": { + "description": "Дата окончания периода в формате YYYY-MM-DD", + "format": "date", + "type": "string" + } + }, + "required": [ + "dateFrom", + "dateTo", + "creativeIDs" + ], + "type": "object" + }, + "V1GetCreativesStatisticOut": { + "description": "Статистика по креативам кампании", + "properties": { + "creatives": { + "description": "Статистика по креативам кампании", + "items": { + "$ref": "#/components/schemas/CreativeStatistic" + }, + "type": "array" + } + }, + "required": [ + "creatives" + ], + "type": "object" + }, + "V1GetGroupReferenceDataOut": { + "properties": { + "referenceData": { + "$ref": "#/components/schemas/GroupReferenceData" + } + }, + "required": [ + "referenceData" + ], + "type": "object" + }, + "V1GetGroupsListIn": { + "description": "Payload запроса на получение списка кампаний", + "properties": { + "filter": { + "$ref": "#/components/schemas/GroupsFilter" + }, + "limit": { + "default": 20, + "description": "Количество записей на странице", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "page": { + "default": 1, + "description": "Номер страницы", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "filter", + "limit", + "page" + ], + "type": "object" + }, + "V1GetGroupsListOut": { + "properties": { + "groups": { + "items": { + "$ref": "#/components/schemas/Group" + }, + "type": "array" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "total", + "groups" + ], + "type": "object" + }, + "V1GetGroupsStatisticIn": { + "description": "Request body для запроса статистики по группам кампании. Максимальный период между dateFrom и dateTo — 100 дней.", + "properties": { + "dateFrom": { + "description": "Дата начала периода в формате YYYY-MM-DD", + "format": "date", + "type": "string" + }, + "dateTo": { + "description": "Дата окончания периода в формате YYYY-MM-DD", + "format": "date", + "type": "string" + }, + "groupIDs": { + "description": "Список ID групп для получения статистики", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "dateFrom", + "dateTo", + "groupIDs" + ], + "type": "object" + }, + "V1GetGroupsStatisticOut": { + "description": "Статистика по группам кампании", + "properties": { + "groups": { + "description": "Статистика по группам кампании", + "items": { + "$ref": "#/components/schemas/GroupStatistic" + }, + "type": "array" + } + }, + "required": [ + "groups" + ], + "type": "object" + }, + "V1GetHtmlOut": { + "properties": { + "errorReason": { + "description": "Причина ошибки (заполнено если status = ERROR)", + "nullable": true, + "type": "string" + }, + "id": { + "description": "ID HTML", + "type": "string" + }, + "status": { + "enum": [ + "UPLOADING", + "READY", + "ERROR" + ], + "type": "string" + }, + "url": { + "description": "URL HTML файла", + "nullable": true, + "type": "string" + } + }, + "required": [ + "id", + "status" + ], + "type": "object" + }, + "V1GetImageOut": { + "properties": { + "id": { + "description": "ID изображения", + "type": "integer" + }, + "url": { + "description": "URL изображения", + "type": "string" + } + }, + "required": [ + "id", + "url" + ], + "type": "object" + }, + "V1GetLegalAttachmentsOut": { + "properties": { + "id": { + "description": "ID файла", + "type": "string" + }, + "publicUrl": { + "description": "Публичный URL файла", + "type": "string" + } + }, + "required": [ + "id", + "publicUrl" + ], + "type": "object" + }, + "V1GetUsersListByAccountOut": { + "properties": { + "total": { + "type": "integer" + }, + "users": { + "items": { + "$ref": "#/components/schemas/User" + }, + "type": "array" + } + }, + "required": [ + "total", + "users" + ], + "type": "object" + }, + "V1GetVideoOut": { + "properties": { + "errorReason": { + "description": "Причина ошибки обработки видео", + "nullable": true, + "type": "string" + }, + "id": { + "description": "ID видео", + "type": "string" + }, + "status": { + "description": "Статус видео", + "type": "string" + }, + "thumbnailUrl": { + "description": "URL превью", + "nullable": true, + "type": "string" + }, + "thumbnailVideoUrl": { + "description": "Видео-превью от хостинга", + "nullable": true, + "type": "string" + }, + "title": { + "description": "Название видео", + "type": "string" + }, + "videoUrl": { + "description": "URL видео", + "nullable": true, + "type": "string" + } + }, + "required": [ + "id", + "title", + "status" + ], + "type": "object" + }, + "V1LaunchCampaignsIn": { + "description": "Payload запуска кампаний аккаунта", + "properties": { + "campaignIDs": { + "description": "Список ID кампаний", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "campaignIDs" + ], + "type": "object" + }, + "V1LaunchGroupIn": { + "description": "Payload запуска группы аккаунта", + "properties": { + "groupID": { + "description": "ID группы", + "type": "integer" + } + }, + "required": [ + "groupID" + ], + "type": "object" + }, + "V1PauseCampaignsIn": { + "description": "Payload паузы кампаний", + "properties": { + "campaignIDs": { + "description": "Список ID кампаний для паузы", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "campaignIDs" + ], + "type": "object" + }, + "V1PauseCreativesIn": { + "description": "Payload паузы креативов аккаунта", + "properties": { + "creativeIDs": { + "description": "Список ID креативов", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "creativeIDs" + ], + "type": "object" + }, + "V1PauseGroupsIn": { + "description": "Payload паузы групп аккаунта", + "properties": { + "groupIDs": { + "description": "Список ID групп", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "groupIDs" + ], + "type": "object" + }, + "V1ReferenceDataCreateCreativeOut": { + "properties": { + "classifier": { + "items": { + "$ref": "#/components/schemas/KktuItem" + }, + "type": "array" + }, + "disclaimers": { + "items": { + "$ref": "#/components/schemas/Disclaimer" + }, + "type": "array" + }, + "templates": { + "items": { + "$ref": "#/components/schemas/TemplateData" + }, + "type": "array" + } + }, + "required": [ + "classifier", + "disclaimers", + "templates" + ], + "type": "object" + }, + "V1SetUserRoleIn": { + "description": "Payload изменение роли пользователя в аккаунте", + "properties": { + "role": { + "$ref": "#/components/schemas/UserRole" + }, + "userId": { + "description": "ID пользователя авито", + "type": "integer" + } + }, + "required": [ + "userId", + "role" + ], + "type": "object" + }, + "V1StopCampaignsIn": { + "description": "Payload остановки кампаний", + "properties": { + "campaignIDs": { + "description": "Список ID кампаний для остановки", + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "campaignIDs" + ], + "type": "object" + }, + "V1TransferBonusIn": { + "description": "Payload Перевода денег между аккаунтом родителем и дочками неплательщиками", + "properties": { + "accountIdTo": { + "description": "accountId на который перевести", + "type": "integer" + }, + "amount": { + "description": "Сумма бонусов, не меньше 1 бонуса", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "accountIdTo", + "amount" + ], + "type": "object" + }, + "V1TransferFundsIn": { + "description": "Payload Перевода денег между аккаунтом родителем и дочками неплательщиками", + "properties": { + "accountIdTo": { + "description": "accountId на который перевести", + "type": "integer" + }, + "amount": { + "description": "Сумма перевода в рублях, не меньше 1 рубля", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "accountIdTo", + "amount" + ], + "type": "object" + }, + "V1UnpauseCampaignsIn": { + "description": "Payload снятия кампаний с паузы", + "properties": { + "campaignIDs": { + "description": "Список ID кампаний для снятия с паузы", + "items": { + "minimum": 1, + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "campaignIDs" + ], + "type": "object" + }, + "V1UnpauseCreativesIn": { + "description": "Payload снятия креативов аккаунта с паузы", + "properties": { + "creativeIDs": { + "description": "Список ID креативов", + "items": { + "minimum": 1, + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "creativeIDs" + ], + "type": "object" + }, + "V1UnpauseGroupsIn": { + "description": "Payload снятия групп аккаунта с паузы", + "properties": { + "groupIDs": { + "description": "Список ID групп", + "items": { + "minimum": 1, + "type": "integer" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "groupIDs" + ], + "type": "object" + }, + "V1UploadHtmlOut": { + "properties": { + "id": { + "description": "ID загруженного HTML", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "V1UploadImageOut": { + "properties": { + "id": { + "description": "ID загруженного изображения", + "type": "integer" + }, + "url": { + "description": "URL изображения", + "type": "string" + } + }, + "required": [ + "id", + "url" + ], + "type": "object" + }, + "V1UploadLegalAttachmentsOut": { + "properties": { + "id": { + "description": "ID загруженного документа", + "type": "string" + }, + "name": { + "description": "Имя файла", + "type": "string" + }, + "url": { + "description": "Публичный URL файла", + "type": "string" + } + }, + "required": [ + "id", + "name", + "url" + ], + "type": "object" + }, + "V1UploadVideoOut": { + "properties": { + "id": { + "description": "ID загруженного видео", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + } + } + }, + "info": { + "description": "Публичное API кабинета Авито Реклама", + "title": "Авито Реклама", + "version": "1.4.0", + "x-skip-documentation": false + }, + "openapi": "3.0.0", + "paths": { + "/ads/v1/account/{accountID}": { + "get": { + "description": "Возвращает реквизиты рекламного аккаунта по его ID: ИНН, КПП, ОГРН, юридический и фактический адреса, контактное лицо и менеджера.\nТокен имеет доступ только к тому аккаунту, в котором был выдан.\n", + "operationId": "V1GetAccountByID", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetAccountByIdOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Получить аккаунт по ID", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + }, + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Создаёт тестовый аккаунт. Метод работает **только в песочнице** (`https://api.avito.ru/ads-sandbox/`); для боевых аккаунтов используйте веб-интерфейс кабинета.\nОграничения песочницы: время жизни аккаунта — до 00:00 текущего дня; в сутки можно создать не более 1 тестового аккаунта.\n", + "operationId": "V1CreateAccount", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateAccountIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateAccountOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "207": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateAccountOut" + } + } + }, + "description": "Аккаунт создан, но часть sandbox-данных не подготовилась", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Создать аккаунт в песочнице", + "x-cost": { + "default": 0, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/add-user": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Добавляет пользователя Авито в рекламный аккаунт с указанной ролью. Доступные роли: `admin` (полный доступ) и `viewer` (только просмотр).\nПользователь идентифицируется по `userId` (ID профиля на Авито).\n", + "operationId": "V1AddUser", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1AddUserIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyResponse" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Добавить пользователя в аккаунт", + "x-cost": { + "default": 5, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/advertisers": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает список рекламодателей аккаунта с пагинацией. Доступные фильтры: список `ids`, список `inns`, список ролей (`roles`).\nПараметры пагинации: `limit` — от 1 до 100 (по умолчанию 20), `page` — от 1.\n", + "operationId": "V1GetAdvertisersList", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetAdvertisersListIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetAdvertisersListOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Получить список рекламодателей по фильтрам", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/balance": { + "get": { + "description": "Возвращает текущий баланс рекламного аккаунта: денежные средства (`balance`) и бонусы (`bonusBalance`).\nВсе суммы — в рублях, целые числа.\n", + "operationId": "V1GetAccountBalanceByID", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetAccountBalanceByIdOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Получить баланс аккаунта по ID", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + }, + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ] + }, + "/ads/v1/account/{accountID}/bonus-transfer": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Переводит бонусы между родительским и дочерним аккаунтом-неплательщиком. Логика направления та же, что у `funds-transfer`: `accountID` в path — источник, `accountIdTo` в body — получатель; для перевода с дочернего на родителя нужен токен дочернего аккаунта.\nСумма `amount` — целое число, не меньше 1 бонуса.\n", + "operationId": "V1TransferBonus", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1TransferBonusIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyResponse" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Перевод бонусов между аккаунтом родителем и дочерними на одном договоре", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/campaigns": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает список рекламных кампаний аккаунта с пагинацией. Поддерживает фильтрацию по ID, моделям оплаты (`CPM`/`CPC`), типам кампании (`textImage`/`HTML`/`video`), статусам, менеджерам, рекламодателям, договорам, диапазону дат создания и диапазону периода размещения.\nПараметры пагинации: `limit` — от 1 до 100 (по умолчанию 20), `page` — от 1.\n", + "operationId": "V1GetCampaignsList", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCampaignsListIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCampaignsListOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Получить список кампаний по фильтрам", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/campaigns/{campaignID}/creatives/stats": { + "parameters": [ + { + "description": "ID аккаунта", + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "description": "ID кампании", + "in": "path", + "name": "campaignID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает статистику по конкретным креативам указанной кампании за заданный период. В `creativeIDs` нужно передать минимум один ID креатива.\n**Ограничение:** максимальный период между `dateFrom` и `dateTo` — 100 дней.\nСтатистика обновляется раз в 30 минут, поэтому более частые запросы не дадут более свежих данных.\n", + "operationId": "V1GetCreativesStatistic", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCreativesStatisticIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCreativesStatisticOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Кампания не найдена" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Получить статистику по креативам кампании", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 10 + } + } + }, + "/ads/v1/account/{accountID}/campaigns/{campaignID}/groups/stats": { + "parameters": [ + { + "description": "ID аккаунта", + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "description": "ID кампании", + "in": "path", + "name": "campaignID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает статистику по конкретным группам объявлений внутри указанной кампании за заданный период. В `groupIDs` нужно передать минимум один ID группы.\n**Ограничение:** максимальный период между `dateFrom` и `dateTo` — 100 дней.\nСтатистика обновляется раз в 30 минут, поэтому более частые запросы не дадут более свежих данных.\n", + "operationId": "V1GetGroupsStatistic", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetGroupsStatisticIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetGroupsStatisticOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Кампания не найдена" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Получить статистику по группам кампании", + "x-cost": { + "default": 5, + "type": "integer" + }, + "x-rate-limiter": { + "default": 10 + } + } + }, + "/ads/v1/account/{accountID}/campaigns/{campaignID}/stats": { + "parameters": [ + { + "description": "ID аккаунта", + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "description": "ID кампании", + "in": "path", + "name": "campaignID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает агрегированную статистику по кампании (показы, клики, CTR, расход, CPM/CPC, метрики видеопросмотров) за указанный период с дневной гранулярностью, а также сводку по группам и креативам кампании.\n**Ограничение:** максимальный период между `dateFrom` и `dateTo` — 100 дней.\nСтатистика обновляется раз в 30 минут, поэтому более частые запросы не дадут более свежих данных.\n", + "operationId": "V1GetCampaignStatistic", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCampaignStatisticIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCampaignStatisticOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Кампания не найдена" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Получить статистику по кампании", + "x-cost": { + "default": 10, + "type": "integer" + }, + "x-rate-limiter": { + "default": 5 + } + } + }, + "/ads/v1/account/{accountID}/children": { + "get": { + "description": "Возвращает список дочерних аккаунтов, привязанных к текущему (родительскому) аккаунту, вместе с их договорами. \nУ дочерних аккаунтов на одном договоре с родителем не передается информация о договоре.\nЕсли нужны также балансы дочерних аккаунтов, используйте `GET /ads/v1/account/{accountID}/children-with-balances`.\n", + "operationId": "V1GetChildAccountsList", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetChildAccountsListOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Получить список дочерних аккаунтов", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + }, + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ] + }, + "/ads/v1/account/{accountID}/children-with-balances": { + "get": { + "description": "Возвращает список дочерних аккаунтов вместе с их балансами (денежные средства, бонусы).\nУдобно для проверки результата переводов через `funds-transfer` / `bonus-transfer`.\n", + "operationId": "V1GetChildAccountsWithBalancesList", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetChildAccountsWithBalancesListOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Получить список дочерних аккаунтов с балансами", + "x-cost": { + "default": 5, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + }, + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ] + }, + "/ads/v1/account/{accountID}/contracts": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает список договоров аккаунта с пагинацией. Доступные фильтры: `ids` (ID договоров), `numbers` (номера договоров), `contractors` и `clients` (фильтры по сторонам договора).\nПараметры пагинации: `limit` — от 1 до 100 (по умолчанию 20), `page` — от 1.\n", + "operationId": "V1GetContractsList", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetContractsListIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetContractsListOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Получить список договоров по фильтрам", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/create-advertiser": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Создаёт рекламодателя — юридическое лицо (или ИП), от лица которого будут размещаться рекламные кампании в этом аккаунте.\nОдин аккаунт может иметь несколько рекламодателей. Если рекламодатель и аккаунт — одно и то же ЮЛ/ИП, договор между ними создавать не нужно; иначе после создания рекламодателя необходимо создать договор через `POST /ads/v1/account/{accountID}/create-contract`.\n", + "operationId": "V1CreateAdvertiser", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateAdvertiserIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateAdvertiserOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Создать рекламодателя", + "x-cost": { + "default": 2, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/create-contract": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Создаёт изначальный договор между аккаунтом и рекламодателем. Договор требуется только если рекламодатель и аккаунт — не одно и то же ЮЛ/ИП; для совпадающих контрагентов договор не создаётся.\nДля дополнительного соглашения укажите `parentId` (родительский договор) и не передавайте `intermediary`; для внешнего договора (`type = external`) передайте `cid` и не передавайте `parentId`.\n", + "operationId": "V1CreateContract", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateContractIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateContractOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Создание изначального договора", + "x-cost": { + "default": 2, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/create-nonpayer-child-account": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Создаёт дочерний аккаунта под текущим (родительским) аккаунтом на том же договоре. В ответе возвращаются `accountID`, `clientKey` и `clientSecret` — пара ключей для генерации отдельного токена дочернего аккаунта.\nВ песочнице токен для созданного дочернего аккаунта использовать **нельзя**; проверить факт создания можно через `GET /ads/v1/account/{accountID}/children`.\n", + "operationId": "V1CreateNonPayerAccount", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateNonPayerAccountIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1CreateNonPayerAccountOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Создание дочернего аккаунта на договоре родителя", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/creatives": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает список креативов аккаунта с пагинацией. Поддерживает фильтрацию по ID креативов, ID групп, ID кампаний, моделям оплаты, типам кампании, статусам, менеджерам, рекламодателям и периоду размещения.\nПараметры пагинации: `limit` — от 1 до 100 (по умолчанию 20), `page` — от 1.\n", + "operationId": "V1GetCreativesList", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCreativesListIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetCreativesListOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Получить список креативов по фильтрам", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/delete-user/{userID}": { + "delete": { + "description": "Удаляет пользователя из рекламного аккаунта. Доступ пользователя к аккаунту прекращается сразу после успешного выполнения запроса.\n`userID` в path — ID пользователя, которого нужно удалить.\n", + "operationId": "V1DeleteUser", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyResponse" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Удалить пользователя из аккаунта", + "x-cost": { + "default": 5, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + }, + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "in": "path", + "name": "userID", + "required": true, + "schema": { + "type": "integer" + } + } + ] + }, + "/ads/v1/account/{accountID}/funds-transfer": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Переводит денежные средства между родительским и дочерним аккаунтом на одном договоре. `accountID` в path — аккаунт-источник (с него списываются деньги), `accountIdTo` в body — аккаунт-получатель.\nПеревод выполняется от имени аккаунта-источника, поэтому для перевода с дочернего на родительский нужен токен дочернего аккаунта. Сумма `amount` — целое число, не меньше 1 рубля.\n", + "operationId": "V1TransferFunds", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1TransferFundsIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyResponse" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Перевод денег между аккаунтом родителем и дочерними на одном договоре", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/group/{groupID}/change-budget": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "in": "path", + "name": "groupID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Устанавливает новый бюджет для указанной группы объявлений. Значение `budget` указывается в рублях с НДС, целое число.\n**Ограничение:** `budget` — целое число не меньше 1. Метод работает только для групп с ручным управлением ставкой.\n", + "operationId": "V1ChangeBudget", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1ChangeBudgetIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyResponse" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт или группа не найдены" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Конфликт версий группы" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Изменить бюджет группы", + "x-cost": { + "default": 3, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/group/{groupID}/change-price": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "in": "path", + "name": "groupID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Устанавливает новую цену (CPC или CPM в зависимости от модели оплаты кампании) для указанной группы объявлений. Значение `price` указывается в рублях с НДС, целое число.\n**Ограничение:** `price` — целое число не меньше 1. Метод работает только для групп с ручным управлением ставкой.\n", + "operationId": "V1ChangePrice", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1ChangePriceIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyResponse" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт или группа не найдены" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Конфликт версий группы" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Изменить цену группы", + "x-cost": { + "default": 3, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/groups": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Возвращает список групп объявлений аккаунта с пагинацией. Поддерживает фильтрацию по ID групп, ID кампаний, статусам, скоростям показов (`paces`), менеджерам, рекламодателям, моделям оплаты и периоду размещения.\nПараметры пагинации: `limit` — от 1 до 100 (по умолчанию 20), `page` — от 1.\n", + "operationId": "V1GetGroupsList", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetGroupsListIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetGroupsListOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Аккаунт не найден" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Получить список групп по фильтрам", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/set-user-role": { + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "post": { + "description": "Меняет роль уже добавленного в аккаунт пользователя. Доступные значения роли: `admin` (полный доступ) и `viewer` (только просмотр).\nЕсли пользователя нужно полностью убрать, используйте `DELETE /ads/v1/account/{accountID}/delete-user/{userID}`.\n", + "operationId": "V1SetUserRole", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1SetUserRoleIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyResponse" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "summary": "Изменить роль пользователя в аккаунте", + "x-cost": { + "default": 5, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + } + }, + "/ads/v1/account/{accountID}/users": { + "get": { + "description": "Возвращает список пользователей, имеющих доступ к рекламному аккаунту, с их ролями и флагом `hasLoggedIn` (заходил ли пользователь в аккаунт хотя бы раз).\nМетод без пагинации — возвращает всех пользователей сразу.\n", + "operationId": "V1GetUsersListByAccount", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V1GetUsersListByAccountOut" + } + } + }, + "description": "Ok", + "headers": { + "Api-Point-Balance": { + "description": "Остаток API-баллов после выполнения запроса", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Некорректный запрос" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Не авторизован" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Доступ запрещен" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Слишком много запросов" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Ошибка сервера" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + }, + "description": "Сервис недоступен" + } + }, + "security": [ + { + "ClientCredentials": [] + } + ], + "summary": "Получить список пользователей аккаунта", + "x-cost": { + "default": 1, + "type": "integer" + }, + "x-rate-limiter": { + "default": 500 + } + }, + "parameters": [ + { + "in": "path", + "name": "accountID", + "required": true, + "schema": { + "type": "integer" + } + } + ] + } + }, + "servers": [ + { + "url": "https://api.avito.ru/" + } + ] +} \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 5df6043..755dad8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,8 @@ build-backend = "setuptools.build_meta" [project] name = "avito-ads" -version = "0.1.0" +# Версия — единственный источник avito_ads/_version.py (см. [tool.setuptools.dynamic]). +dynamic = ["version"] description = "Python SDK для публичного API кабинета Авито Реклама (Avito Ads). Синхронный и асинхронный режимы (httpx), Python 3.8+, интеграции с Django, Flask и FastAPI." readme = "README.md" requires-python = ">=3.8" @@ -48,6 +49,9 @@ dev = [ where = ["."] include = ["avito_ads*"] +[tool.setuptools.dynamic] +version = { attr = "avito_ads._version.__version__" } + [tool.setuptools.package-data] avito_ads = ["py.typed"] diff --git a/tests/unit/test_swagger_1_4_0.py b/tests/unit/test_swagger_1_4_0.py new file mode 100644 index 0000000..67283b7 --- /dev/null +++ b/tests/unit/test_swagger_1_4_0.py @@ -0,0 +1,339 @@ +"""Изменения swagger 1.4.0: новые поля, статусы, 409, 207 и терпимость к новым значениям.""" + +from __future__ import annotations + +import warnings + +import pytest + +from avito_ads import ( + BudgetFrequency, + CampaignBudgetFrequency, + CampaignStatus, + CreativesStatus, + FrequencyPeriod, + LegalType, +) +from avito_ads.exceptions import ApiError, ConflictError, ValidationError +from avito_ads.models import ( + Balance, + Campaign, + CampaignStatistic, + Contract, + CreativeStatistic, + EntityStatistic, + Group, + GroupStatistic, + StatsData, +) +from avito_ads.models.creative import Creative + +from ..conftest import ACCT_PATH, MockRouter, call + +SANDBOX_ACCT = "/ads-sandbox/v1/account/123456789" + + +# --- Политика неизвестных значений ------------------------------------------- + + +async def test_unknown_enum_values_and_reasons_are_kept_as_strings(clients): + router = MockRouter() + router.add_token() + router.add("POST", f"{ACCT_PATH}/campaigns", json={ + "total": 1, + "campaigns": [{ + "id": 1, + "status": "some_future_status", + "budgetFrequency": "weekly_future", + "statusReasons": ["manual", "brand_new_reason"], + "topStatusReason": "brand_new_reason", + }], + }) + router.add("POST", f"{ACCT_PATH}/groups", json={ + "total": 1, + "groups": [{"id": 2, "status": "x_status", "budgetFrequency": "x_freq", + "statusReasons": ["x_reason"], "topStatusReason": "", + "frequencyRules": [{"count": 3, "period": "x_period"}]}], + }) + router.add("POST", f"{ACCT_PATH}/creatives", json={ + "total": 1, + "creatives": [{"id": 3, "status": "x_status", "statusReasons": [], "topStatusReason": ""}], + }) + client = clients(router) + + campaign = (await call(client.campaigns.list())).items[0] + assert campaign.status == "some_future_status" + assert campaign.budget_frequency == "weekly_future" + assert campaign.status_reasons == ["manual", "brand_new_reason"] + assert campaign.top_status_reason == "brand_new_reason" + + group = (await call(client.groups.list())).items[0] + assert group.status == "x_status" + assert group.budget_frequency == "x_freq" + assert group.status_reasons == ["x_reason"] + assert group.frequency_rules[0].period == "x_period" + + creative = (await call(client.creatives.list())).items[0] + assert creative.status == "x_status" + assert creative.status_reasons == [] + assert creative.top_status_reason == "" + + +def test_new_status_values(): + for value in ("will_launch_soon", "partially_active", "will_stop_soon", "pausing", + "unpausing"): + assert CampaignStatus.is_valid(value) + for value in ("will_launch_soon", "pausing", "unpausing"): + assert CreativesStatus.is_valid(value) + assert CampaignBudgetFrequency.values() == ["daily", "entirePeriod", "mixed"] + assert BudgetFrequency.values() == ["daily", "entirePeriod"] + assert FrequencyPeriod.values() == ["no_limit", "day", "week", "month"] + + +# --- Деньги ------------------------------------------------------------------ + + +def test_campaign_budget_absent_null_and_zero_are_distinct(): + mixed = Campaign.from_dict({"budgetFrequency": "mixed"}) + assert mixed.budget is None + assert mixed.budget_kopeks is None + assert mixed.budget_frequency == CampaignBudgetFrequency.MIXED + + null = Campaign.from_dict({"budget": None, "budgetKopeks": None}) + assert null.budget is None + assert null.budget_kopeks is None + + empty = Campaign.from_dict({"budget": 0, "budgetKopeks": 0, "budgetFrequency": "daily"}) + assert empty.budget == 0 + assert empty.budget_kopeks == 0 + + +def test_campaign_new_fields_and_defaults(): + campaign = Campaign.from_dict({"performanceAdditionalAgreementID": 77, "budgetKopeks": 1050}) + assert campaign.performance_additional_agreement_id == 77 + assert campaign.budget_kopeks == 1050 + assert campaign.status_reasons == [] + assert campaign.top_status_reason == "" + + +def test_kopeks_fields(): + balance = Balance.from_dict( + {"balance": 10, "balanceKopeks": 1050, "bonusBalance": 1, "bonusBalanceKopeks": 150} + ) + assert balance.balance_kopeks == 1050 + assert balance.bonus_balance_kopeks == 150 + + stats = StatsData.from_dict({"spend": 1, "spendKopeks": 125, "spendBonusKopeks": 5}) + assert stats.spend_kopeks == 125 + assert stats.spend_bonus_kopeks == 5 + assert StatsData.from_dict({}).spend_kopeks is None + + +# --- Группа ------------------------------------------------------------------ + + +GROUP = { + "id": 5, + "budgetKopeks": 100000, + "priceKopeks": 2550, + "budgetFrequency": "daily", + "frequencyRules": [{"count": 3, "period": "day"}, {"count": 10, "period": "week"}], + "frequencyCount": 3, + "frequencyPeriod": "day", + "actions": ["pause", "edit"], + "activitySchedule": {"monday": [9, 10, 11], "sunday": []}, + "audienceType": "basic", + "format": "native", + "pace": "even", + "periodStartAt": "2026-11-01T00:00:00Z", + "periodEndAt": None, + "periodTimezone": "Europe/Moscow", + "priceControl": "manual", + "scheduleType": "custom", + "startASAP": True, + "userID": 42, + "targetingAgeIDs": [1, 2], + "targetingAudienceIDs": ["a1"], + "targetingFamilyStatusIDs": [3], + "targetingGenderIDs": [1], + "targetingIncomeIDs": [4], + "targetingInterestIDs": ["i1", "i2"], + "targetingLocationIDs": [637640], + "targetingParentStatusIDs": [5], + "statusReasons": ["insufficient_funds"], + "topStatusReason": "insufficient_funds", +} + + +def test_group_new_fields(): + group = Group.from_dict(GROUP) + assert group.budget_kopeks == 100000 + assert group.price_kopeks == 2550 + assert group.budget_frequency == BudgetFrequency.DAILY + assert [(r.count, r.period) for r in group.frequency_rules] == [(3, "day"), (10, "week")] + assert group.actions == ["pause", "edit"] + assert group.activity_schedule == {"monday": [9, 10, 11], "sunday": []} + assert group.audience_type == "basic" + assert group.format == "native" + assert group.pace == "even" + assert group.period_start_at == "2026-11-01T00:00:00Z" + assert group.period_end_at is None + assert group.period_timezone == "Europe/Moscow" + assert group.price_control == "manual" + assert group.schedule_type == "custom" + assert group.start_asap is True + assert group.user_id == 42 + assert group.targeting_age_ids == [1, 2] + assert group.targeting_audience_ids == ["a1"] + assert group.targeting_family_status_ids == [3] + assert group.targeting_gender_ids == [1] + assert group.targeting_income_ids == [4] + assert group.targeting_interest_ids == ["i1", "i2"] + assert group.targeting_location_ids == [637640] + assert group.targeting_parent_status_ids == [5] + assert group.status_reasons == ["insufficient_funds"] + assert group.top_status_reason == "insufficient_funds" + + +def test_group_legacy_frequency_fields_are_deprecated(): + group = Group.from_dict(GROUP) + with pytest.warns(DeprecationWarning, match="frequency_rules"): + assert group.frequency_count == 3 + with pytest.warns(DeprecationWarning, match="frequency_rules"): + assert group.frequency_period == "day" + + +# --- Креатив и договор -------------------------------------------------------- + + +def test_creative_new_fields_and_deprecated_legal_info(): + creative = Creative.from_dict({ + "kktuFields": [{"key": "kktu", "value": "30.10.1"}], + "landingID": 9, + "originUrl": "https://example.com/?utm=1", + "previewUrl": "https://example.com/preview", + "userID": 7, + "legalInfo": {"kktu": "30.10.1"}, + }) + assert [(f.key, f.value) for f in creative.kktu_fields] == [("kktu", "30.10.1")] + assert creative.landing_id == 9 + assert creative.origin_url == "https://example.com/?utm=1" + assert creative.preview_url == "https://example.com/preview" + assert creative.user_id == 7 + with pytest.warns(DeprecationWarning, match="kktu_fields"): + assert creative.legal_info == {"kktu": "30.10.1"} + + +def test_contract_flags(): + contract = Contract.from_dict({"isAgentActingForPublisher": True, "isCreativeReporter": None}) + assert contract.is_agent_acting_for_publisher is True + assert contract.is_creative_reporter is None + + +# --- Статистика --------------------------------------------------------------- + + +async def test_statistics_specific_types(clients): + router = MockRouter() + router.add_token() + router.add("POST", f"{ACCT_PATH}/campaigns/1/groups/stats", + json={"groups": [{"id": 2, "name": "G", "data": [], "totalData": {}}]}) + router.add("POST", f"{ACCT_PATH}/campaigns/1/creatives/stats", + json={"creatives": [{"id": 3, "groupId": 2, "data": [], "totalData": {}}]}) + client = clients(router) + + groups = await call(client.statistics.groups(1, "2026-11-01", "2026-11-02", [2])) + assert isinstance(groups[0], GroupStatistic) + creatives = await call(client.statistics.creatives(1, "2026-11-01", "2026-11-02", [3])) + assert isinstance(creatives[0], CreativeStatistic) + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert creatives[0].group_id == 2 + + +def test_campaign_statistic_fields_without_warning_and_legacy_access_warns(): + campaign = CampaignStatistic.from_dict({"paymentModel": "CPC", "campaignType": "video"}) + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert campaign.payment_model == "CPC" + assert campaign.campaign_type == "video" + assert isinstance(campaign, EntityStatistic) + with pytest.warns(DeprecationWarning): + assert GroupStatistic.from_dict({}).payment_model is None + + +# --- 409 у change-budget / change-price --------------------------------------- + + +@pytest.mark.parametrize( + "path,method_name,value", + [("change-budget", "change_budget", 1000), ("change-price", "change_price", 25)], +) +async def test_conflict_409_raises_conflict_error(clients, path, method_name, value): + router = MockRouter() + router.add_token() + router.add("POST", f"{ACCT_PATH}/group/5/{path}", + json={"code": "conflict", "message": "Конфликт версий группы"}, status=409) + client = clients(router) + + with pytest.raises(ConflictError) as info: + await call(getattr(client.groups, method_name)(5, value)) + assert isinstance(info.value, ApiError) + assert info.value.status_code == 409 + assert info.value.error_code == "conflict" + assert str(info.value) == "Конфликт версий группы" + + +# --- Sandbox: 207 и warnings, обязательный legal_type ------------------------- + + +def _create_sandbox(client, **overrides): # type: ignore[no-untyped-def] + kwargs = { + "inn": "7712345678", + "short_name": "Тест", + "long_name": "ООО Тест", + "ogrn": "1177746123456", + "legal_address": "г. Москва", + "actual_address": None, + "contact": {"name": "Иван", "phone": "+79001234567"}, + "legal_type": LegalType.UL, + } + kwargs.update(overrides) + return client.account.create_sandbox_account(**kwargs) + + +async def test_sandbox_207_is_success_with_warnings(clients): + router = MockRouter() + router.add_token() + router.add("POST", SANDBOX_ACCT, status=207, + json={"accountID": 555, "warnings": ["contracts: not prepared"]}) + client = clients(router, sandbox=True) + + created = await call(_create_sandbox(client)) + assert created.account_id == 555 + assert created.warnings == ["contracts: not prepared"] + body = router.last_body() + assert body["legalType"] == "ul" + assert "actualAddress" not in body + + +async def test_sandbox_200_has_empty_warnings(clients): + router = MockRouter() + router.add_token() + router.add("POST", SANDBOX_ACCT, json={"accountID": 556, "warnings": []}) + client = clients(router, sandbox=True) + + created = await call(_create_sandbox(client, actual_address="г. Москва, д. 2")) + assert created.warnings == [] + assert router.last_body()["actualAddress"] == "г. Москва, д. 2" + + +async def test_sandbox_requires_valid_legal_type(clients): + router = MockRouter() + client = clients(router, sandbox=True) + + with pytest.raises(ValidationError): + await call(_create_sandbox(client, legal_type=None)) + with pytest.raises(ValidationError): + await call(_create_sandbox(client, legal_type="llc")) + assert router.requests == [] diff --git a/tests/unit/test_user_agent.py b/tests/unit/test_user_agent.py new file mode 100644 index 0000000..e23ba7c --- /dev/null +++ b/tests/unit/test_user_agent.py @@ -0,0 +1,67 @@ +"""Тесты заголовка User-Agent (sync + async): метка SDK, дописывание, запрос токена.""" + +from __future__ import annotations + +import httpx + +import avito_ads +from avito_ads import AsyncClient, Client, Configuration +from avito_ads._version import build_user_agent + +from ..conftest import ACCOUNT_ID, ACCT_PATH, TOKEN_PATH, MockRouter, aclose, call + +BALANCE = f"{ACCT_PATH}/balance" +SDK_MARK = f"avito-ads-sdk-python3/{avito_ads.__version__}" + + +def _client(mode: str, router: MockRouter, user_agent: str = "") -> object: + config = Configuration.create("id", "secret", ACCOUNT_ID).with_retry_base_delay(0) + if user_agent: + config = config.with_user_agent(user_agent) + transport = httpx.MockTransport(router.handler) + if mode == "async": + return AsyncClient(config.with_async_client(httpx.AsyncClient(transport=transport))) + return Client(config.with_http_client(httpx.Client(transport=transport))) + + +async def _user_agents(mode: str, user_agent: str = "") -> dict: + router = MockRouter() + router.add_token() + router.add("GET", BALANCE, json={"balance": 1, "bonusBalance": 0}) + client = _client(mode, router, user_agent) + try: + await call(client.account.get_balance()) # type: ignore[attr-defined] + finally: + await aclose(client) + return {req.url.path: req.headers.get("User-Agent") for req in router.requests} + + +def test_default_user_agent_constant(): + assert avito_ads.DEFAULT_USER_AGENT == SDK_MARK + assert Configuration.create("id", "secret", 1).effective_user_agent == SDK_MARK + + +async def test_default_user_agent_in_requests_and_token(mode): + agents = await _user_agents(mode) + assert agents[BALANCE] == SDK_MARK + assert agents[TOKEN_PATH] == SDK_MARK + + +async def test_custom_user_agent_gets_sdk_mark(mode): + agents = await _user_agents(mode, "my-app/1.0") + assert agents[BALANCE] == f"my-app/1.0 {SDK_MARK}" + assert agents[TOKEN_PATH] == f"my-app/1.0 {SDK_MARK}" + + +async def test_custom_user_agent_with_mark_is_not_duplicated(mode): + custom = "my-app/1.0 Avito-Ads-SDK-Python3/9.9.9" + agents = await _user_agents(mode, custom) + assert agents[BALANCE] == custom + assert agents[TOKEN_PATH] == custom + + +def test_build_user_agent_edge_cases(): + assert build_user_agent(None) == SDK_MARK + assert build_user_agent(" ") == SDK_MARK + assert build_user_agent(" my-app/1.0 ") == f"my-app/1.0 {SDK_MARK}" + assert build_user_agent(SDK_MARK) == SDK_MARK diff --git a/tests/unit/test_version.py b/tests/unit/test_version.py new file mode 100644 index 0000000..6bc25f6 --- /dev/null +++ b/tests/unit/test_version.py @@ -0,0 +1,16 @@ +"""Версия SDK совпадает с версией swagger в openapi.json.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import avito_ads + +OPENAPI = Path(__file__).resolve().parents[2] / "openapi.json" + + +def test_versions_match_openapi(): + spec_version = json.loads(OPENAPI.read_text(encoding="utf-8"))["info"]["version"] + assert spec_version == avito_ads.API_VERSION + assert avito_ads.__version__ == spec_version