amochka 0.1.8__py3-none-any.whl → 0.1.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
amochka/client.py DELETED
@@ -1,1101 +0,0 @@
1
- import os
2
- import time
3
- import json
4
- import requests
5
- import logging
6
- from datetime import datetime
7
- from typing import Iterator, List, Optional, Sequence, Union
8
- from ratelimit import limits, sleep_and_retry
9
-
10
- # Создаём базовый логгер
11
- logger = logging.getLogger(__name__)
12
- if not logger.handlers:
13
- ch = logging.StreamHandler()
14
- formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
15
- ch.setFormatter(formatter)
16
- logger.addHandler(ch)
17
-
18
- RATE_LIMIT = 7 # Максимум 7 запросов в секунду
19
-
20
- class Deal(dict):
21
- """
22
- Объект сделки расширяет стандартный словарь данными из custom_fields_values.
23
-
24
- Обеспечивает два способа доступа к кастомным полям:
25
- 1. get(key): при обращении по названию (строкой) или по ID поля (integer)
26
- возвращает текстовое значение поля (например, «Дурина Юлия»).
27
- 2. get_id(key): возвращает идентификатор выбранного варианта (enum_id) для полей типа select.
28
- Если в данных enum_id отсутствует, производится поиск в переданной конфигурации полей,
29
- сравнение выполняется без учёта регистра и лишних пробелов.
30
-
31
- Параметр custom_fields_config – словарь, где ключи – ID полей, а значения – модели полей.
32
- """
33
- def __init__(self, data, custom_fields_config=None, logger=None):
34
- super().__init__(data)
35
- self._custom = {}
36
- self._custom_config = custom_fields_config # сохраняем конфигурацию кастомных полей
37
- self._logger = logger or logging.getLogger(__name__)
38
- custom = data.get("custom_fields_values") or []
39
- self._logger.debug(f"Processing custom_fields_values: {custom}")
40
- for field in custom:
41
- if isinstance(field, dict):
42
- field_name = field.get("field_name")
43
- values = field.get("values")
44
- if field_name and values and isinstance(values, list) and len(values) > 0:
45
- key_name = field_name.lower().strip()
46
- stored_value = values[0].get("value")
47
- stored_enum_id = values[0].get("enum_id") # может быть None для некоторых полей
48
- # Сохраняем полную информацию (и для get() и для get_id())
49
- self._custom[key_name] = {"value": stored_value, "enum_id": stored_enum_id}
50
- self._logger.debug(f"Set custom field '{key_name}' = {{'value': {stored_value}, 'enum_id': {stored_enum_id}}}")
51
- field_id = field.get("field_id")
52
- if field_id is not None and values and isinstance(values, list) and len(values) > 0:
53
- stored_value = values[0].get("value")
54
- stored_enum_id = values[0].get("enum_id") # может быть None для некоторых полей
55
- self._custom[int(field_id)] = {"value": stored_value, "enum_id": stored_enum_id}
56
- self._logger.debug(f"Set custom field id {field_id} = {{'value': {stored_value}, 'enum_id': {stored_enum_id}}}")
57
- if custom_fields_config:
58
- for cid, field_obj in custom_fields_config.items():
59
- key = field_obj.get("name", "").lower().strip() if isinstance(field_obj, dict) else str(field_obj).lower().strip()
60
- if key not in self._custom:
61
- self._custom[key] = None
62
- self._logger.debug(f"Field '{key}' not found in deal data; set to None")
63
-
64
- def __getitem__(self, key):
65
- if key in super().keys():
66
- return super().__getitem__(key)
67
- if isinstance(key, str):
68
- lower_key = key.lower().strip()
69
- if lower_key in self._custom:
70
- stored = self._custom[lower_key]
71
- return stored.get("value") if isinstance(stored, dict) else stored
72
- if isinstance(key, int):
73
- if key in self._custom:
74
- stored = self._custom[key]
75
- return stored.get("value") if isinstance(stored, dict) else stored
76
- raise KeyError(key)
77
-
78
- def get(self, key, default=None):
79
- try:
80
- return self.__getitem__(key)
81
- except KeyError:
82
- return default
83
-
84
- def get_field_type(self, key):
85
- """
86
- Определяет тип кастомного поля.
87
-
88
- :param key: Название поля (строка) или ID поля (integer).
89
- :return: Строка с типом поля ('text', 'select', 'numeric', 'checkbox', и т.д.)
90
- или None, если поле не найдено или тип не определён.
91
- """
92
- field_def = None
93
-
94
- # Получаем определение поля из конфигурации
95
- if self._custom_config:
96
- if isinstance(key, int):
97
- field_def = self._custom_config.get(key)
98
- else:
99
- for fid, fdef in self._custom_config.items():
100
- if isinstance(fdef, dict) and fdef.get("name", "").lower().strip() == key.lower().strip():
101
- field_def = fdef
102
- break
103
-
104
- # Если нашли определение, возвращаем его тип
105
- if field_def and isinstance(field_def, dict):
106
- return field_def.get("type")
107
-
108
- # Если конфигурации нет или поле не найдено, пробуем определить тип по данным
109
- stored = None
110
- if isinstance(key, str):
111
- lower_key = key.lower().strip()
112
- if lower_key in self._custom:
113
- stored = self._custom[lower_key]
114
- elif isinstance(key, int):
115
- if key in self._custom:
116
- stored = self._custom[key]
117
-
118
- if isinstance(stored, dict) and "enum_id" in stored:
119
- return "select"
120
-
121
- return None
122
-
123
- def get_id(self, key, default=None):
124
- """
125
- Возвращает идентификатор выбранного варианта (enum_id) для кастомного поля типа select.
126
- Для полей других типов возвращает их значение, как метод get().
127
-
128
- Если значение enum_id отсутствует в данных, производится поиск в конфигурации кастомных полей,
129
- сравнение значения выполняется без учёта регистра и пробелов.
130
-
131
- :param key: Название поля (строка) или ID поля (integer).
132
- :param default: Значение по умолчанию, если enum_id не найден.
133
- :return: Для полей типа select - идентификатор варианта (целое число).
134
- Для других типов полей - значение поля.
135
- Если поле не найдено - default.
136
- """
137
- field_type = self.get_field_type(key)
138
-
139
- # Если это не поле списка, возвращаем значение как get()
140
- if field_type is not None and field_type != "select":
141
- return self.get(key, default)
142
-
143
- stored = None
144
- if isinstance(key, str):
145
- lower_key = key.lower().strip()
146
- if lower_key in self._custom:
147
- stored = self._custom[lower_key]
148
- elif isinstance(key, int):
149
- if key in self._custom:
150
- stored = self._custom[key]
151
- if isinstance(stored, dict):
152
- enum_id = stored.get("enum_id")
153
- if enum_id is not None:
154
- return enum_id
155
- if self._custom_config:
156
- field_def = None
157
- if isinstance(key, int):
158
- field_def = self._custom_config.get(key)
159
- else:
160
- for fid, fdef in self._custom_config.items():
161
- if fdef.get("name", "").lower().strip() == key.lower().strip():
162
- field_def = fdef
163
- break
164
- if field_def:
165
- enums = field_def.get("enums") or []
166
- for enum in enums:
167
- if enum.get("value", "").lower().strip() == stored.get("value", "").lower().strip():
168
- return enum.get("id", default)
169
-
170
- # Если это не поле типа select или не удалось найти enum_id,
171
- # возвращаем значение поля
172
- return self.get(key, default)
173
-
174
- class CacheConfig:
175
- """
176
- Конфигурация кэширования для AmoCRMClient.
177
-
178
- Параметры:
179
- enabled (bool): Включено ли кэширование
180
- storage (str): Тип хранилища ('file' или 'memory')
181
- file (str): Путь к файлу кэша (используется только при storage='file')
182
- lifetime_hours (int|None): Время жизни кэша в часах (None для бесконечного)
183
- """
184
- def __init__(self, enabled=True, storage='file', file=None, lifetime_hours=24):
185
- self.enabled = enabled
186
- self.storage = storage.lower()
187
- self.file = file
188
- self.lifetime_hours = lifetime_hours
189
-
190
- @classmethod
191
- def disabled(cls):
192
- """Создает конфигурацию с отключенным кэшированием"""
193
- return cls(enabled=False)
194
-
195
- @classmethod
196
- def memory_only(cls, lifetime_hours=24):
197
- """Создает конфигурацию с кэшированием только в памяти"""
198
- return cls(enabled=True, storage='memory', lifetime_hours=lifetime_hours)
199
-
200
- @classmethod
201
- def file_cache(cls, file=None, lifetime_hours=24):
202
- """Создает конфигурацию с файловым кэшированием"""
203
- return cls(enabled=True, storage='file', file=file, lifetime_hours=lifetime_hours)
204
-
205
- class AmoCRMClient:
206
- """
207
- Клиент для работы с API amoCRM.
208
-
209
- Основные функции:
210
- - load_token: Загружает и проверяет токен авторизации.
211
- - _make_request: Выполняет HTTP-запрос с учетом ограничения по скорости.
212
- - get_deal_by_id: Получает данные сделки по ID и возвращает объект Deal.
213
- - get_custom_fields_mapping: Загружает и кэширует список кастомных полей.
214
- - find_custom_field_id: Ищет кастомное поле по его названию.
215
- - update_lead: Обновляет сделку, включая стандартные и кастомные поля.
216
-
217
- Дополнительно можно задать уровень логирования через параметр log_level,
218
- либо полностью отключить логирование, установив disable_logging=True.
219
- """
220
- def __init__(
221
- self,
222
- base_url,
223
- token_file=None,
224
- cache_config=None,
225
- log_level=logging.INFO,
226
- disable_logging=False,
227
- *,
228
- client_id: Optional[str] = None,
229
- client_secret: Optional[str] = None,
230
- redirect_uri: Optional[str] = None,
231
- ):
232
- """
233
- Инициализирует клиента, задавая базовый URL, токен авторизации и настройки кэша для кастомных полей.
234
-
235
- :param base_url: Базовый URL API amoCRM.
236
- :param token_file: Файл, содержащий токен авторизации.
237
- :param cache_config: Конфигурация кэширования (объект CacheConfig или None для значений по умолчанию)
238
- :param log_level: Уровень логирования (например, logging.DEBUG, logging.INFO).
239
- :param disable_logging: Если True, логирование будет отключено.
240
- """
241
- self.base_url = base_url.rstrip('/')
242
- domain = self.base_url.split("//")[-1].split(".")[0]
243
- self.domain = domain
244
- self.token_file = token_file or os.path.join(os.path.expanduser('~'), '.amocrm_token.json')
245
-
246
- # OAuth2 credentials (используются для авто‑refresh токена)
247
- self.client_id = client_id
248
- self.client_secret = client_secret
249
- self.redirect_uri = redirect_uri
250
-
251
- # Создаем логгер для конкретного экземпляра клиента
252
- self.logger = logging.getLogger(f"{__name__}.{self.domain}")
253
- if not self.logger.handlers:
254
- handler = logging.StreamHandler()
255
- formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
256
- handler.setFormatter(formatter)
257
- self.logger.addHandler(handler)
258
- self.logger.propagate = False # Отключаем передачу логов в родительский логгер
259
-
260
- if disable_logging:
261
- self.logger.setLevel(logging.CRITICAL + 1) # Выше, чем любой стандартный уровень
262
- else:
263
- self.logger.setLevel(log_level)
264
-
265
- # Настройка кэширования
266
- if cache_config is None:
267
- self.cache_config = CacheConfig()
268
- else:
269
- self.cache_config = cache_config
270
-
271
- # Установка файла кэша, если используется файловое хранилище
272
- if self.cache_config.enabled and self.cache_config.storage == 'file':
273
- if not self.cache_config.file:
274
- self.cache_config.file = f"custom_fields_cache_{self.domain}.json"
275
-
276
- self.logger.debug(f"AmoCRMClient initialized for domain {self.domain}")
277
-
278
- self.token = None
279
- self.refresh_token = None
280
- self.expires_at = None
281
- self.load_token()
282
- self._custom_fields_mapping = None
283
-
284
- def load_token(self):
285
- """
286
- Загружает токен авторизации из файла или строки, проверяет его срок действия.
287
- При наличии refresh_token и учётных данных пробует обновить токен.
288
-
289
- :return: Действительный access_token.
290
- :raises Exception: Если токен не найден или истёк и нет возможности обновить.
291
- """
292
- data = None
293
- if os.path.exists(self.token_file):
294
- with open(self.token_file, 'r') as f:
295
- data = json.load(f)
296
- self.logger.debug(f"Token loaded from file: {self.token_file}")
297
- else:
298
- try:
299
- data = json.loads(self.token_file)
300
- self.logger.debug("Token parsed from provided string.")
301
- except Exception as e:
302
- raise Exception("Токен не найден и не удалось распарсить переданное содержимое.") from e
303
-
304
- self.refresh_token = data.get('refresh_token', self.refresh_token)
305
- self.client_id = data.get('client_id', self.client_id)
306
- self.client_secret = data.get('client_secret', self.client_secret)
307
- self.redirect_uri = data.get('redirect_uri', self.redirect_uri)
308
-
309
- expires_at_str = data.get('expires_at')
310
- expires_at = None
311
- if expires_at_str:
312
- try:
313
- expires_at = datetime.fromisoformat(expires_at_str).timestamp()
314
- except Exception:
315
- try:
316
- expires_at = float(expires_at_str)
317
- except Exception:
318
- expires_at = None
319
- self.expires_at = expires_at
320
-
321
- access_token = data.get('access_token')
322
- if access_token and expires_at and time.time() < expires_at:
323
- self.logger.debug("Token is valid.")
324
- self.token = access_token
325
- return access_token
326
-
327
- if self.refresh_token and self.client_id and self.client_secret and self.redirect_uri:
328
- self.logger.info("Access token истёк, пробую обновить через refresh_token…")
329
- return self._refresh_access_token()
330
-
331
- raise Exception("Токен истёк или некорректен, и нет данных для refresh_token. Обновите токен.")
332
-
333
- @sleep_and_retry
334
- @limits(calls=RATE_LIMIT, period=1)
335
- def _make_request(self, method, endpoint, params=None, data=None, timeout=10):
336
- """
337
- Выполняет HTTP-запрос к API amoCRM с учетом ограничения по скорости (rate limit).
338
-
339
- :param method: HTTP-метод (GET, PATCH, POST, DELETE и т.д.).
340
- :param endpoint: Конечная точка API (начинается с /api/v4/).
341
- :param params: GET-параметры запроса.
342
- :param data: Данные, отправляемые в JSON-формате.
343
- :param timeout: Тайм‑аут запроса в секундах (по умолчанию 10).
344
- :return: Ответ в формате JSON или None (если статус 204).
345
- :raises Exception: При получении кода ошибки, отличного от 200/204.
346
- """
347
- url = f"{self.base_url}{endpoint}"
348
- headers = {
349
- "Authorization": f"Bearer {self.token}",
350
- "Content-Type": "application/json"
351
- }
352
- self.logger.debug(f"Making {method} request to {url} with params {params} and data {data}")
353
- response = requests.request(method, url, headers=headers, params=params, json=data, timeout=timeout)
354
-
355
- if response.status_code == 401 and self.refresh_token:
356
- self.logger.info("Получен 401, пробую обновить токен и повторить запрос…")
357
- self._refresh_access_token()
358
- headers["Authorization"] = f"Bearer {self.token}"
359
- response = requests.request(method, url, headers=headers, params=params, json=data, timeout=timeout)
360
-
361
- if response.status_code not in (200, 204):
362
- self.logger.error(f"Request error {response.status_code}: {response.text}")
363
- raise Exception(f"Ошибка запроса: {response.status_code}, {response.text}")
364
- if response.status_code == 204:
365
- return None
366
- return response.json()
367
-
368
- def _refresh_access_token(self):
369
- """Обновляет access_token по refresh_token и сохраняет его в token_file."""
370
- if not all([self.refresh_token, self.client_id, self.client_secret, self.redirect_uri]):
371
- raise Exception("Нельзя обновить токен: отсутствует refresh_token или client_id/client_secret/redirect_uri")
372
-
373
- payload = {
374
- "client_id": self.client_id,
375
- "client_secret": self.client_secret,
376
- "grant_type": "refresh_token",
377
- "refresh_token": self.refresh_token,
378
- "redirect_uri": self.redirect_uri,
379
- }
380
- token_url = f"{self.base_url}/oauth2/access_token"
381
- self.logger.debug(f"Refreshing token via {token_url}")
382
- resp = requests.post(token_url, json=payload, timeout=10)
383
- if resp.status_code != 200:
384
- self.logger.error(f"Не удалось обновить токен: {resp.status_code} {resp.text}")
385
- raise Exception(f"Не удалось обновить токен: {resp.status_code}")
386
-
387
- data = resp.json() or {}
388
- access_token = data.get("access_token")
389
- refresh_token = data.get("refresh_token", self.refresh_token)
390
- expires_in = data.get("expires_in")
391
- if not access_token:
392
- raise Exception("Ответ на refresh не содержит access_token")
393
-
394
- expires_at = None
395
- if expires_in:
396
- expires_at = time.time() + int(expires_in)
397
-
398
- self.token = access_token
399
- self.refresh_token = refresh_token
400
- self.expires_at = expires_at
401
-
402
- if self.token_file:
403
- try:
404
- with open(self.token_file, "w") as f:
405
- json.dump({
406
- "access_token": access_token,
407
- "refresh_token": refresh_token,
408
- "expires_at": datetime.fromtimestamp(expires_at).isoformat() if expires_at else None,
409
- "client_id": self.client_id,
410
- "client_secret": self.client_secret,
411
- "redirect_uri": self.redirect_uri,
412
- }, f)
413
- self.logger.debug(f"Новый токен сохранён в {self.token_file}")
414
- except Exception as exc:
415
- self.logger.error(f"Не удалось сохранить обновлённый токен: {exc}")
416
-
417
- return access_token
418
-
419
- def _to_timestamp(self, value: Optional[Union[int, float, str, datetime]]) -> Optional[int]:
420
- """
421
- Преобразует значение даты/времени в Unix timestamp.
422
- Возвращает None, если значение не указано.
423
- """
424
- if value is None:
425
- return None
426
- if isinstance(value, datetime):
427
- return int(value.timestamp())
428
- if isinstance(value, (int, float)):
429
- return int(value)
430
- if isinstance(value, str):
431
- try:
432
- return int(datetime.fromisoformat(value).timestamp())
433
- except ValueError as exc:
434
- raise ValueError(f"Не удалось преобразовать '{value}' в timestamp") from exc
435
- raise TypeError(f"Неподдерживаемый тип для timestamp: {type(value)}")
436
-
437
- def _format_filter_values(self, values: Optional[Union[int, Sequence[Union[int, str]], str]]) -> Optional[Union[str, Sequence[Union[int, str]]]]:
438
- """
439
- Преобразует значение или последовательность значений для передачи в запрос.
440
- """
441
- if values is None:
442
- return None
443
- if isinstance(values, (list, tuple, set)):
444
- return [str(v) for v in values]
445
- return str(values)
446
-
447
- def _extract_collection(self, response: dict, data_path: Sequence[str]) -> list:
448
- """
449
- Извлекает коллекцию элементов из ответа API по указанному пути ключей.
450
- """
451
- data = response or {}
452
- for key in data_path:
453
- if not isinstance(data, dict):
454
- return []
455
- data = data.get(key)
456
- if data is None:
457
- return []
458
- if isinstance(data, list):
459
- return data
460
- return []
461
-
462
- def _iterate_paginated(
463
- self,
464
- endpoint: str,
465
- params: Optional[dict] = None,
466
- data_path: Sequence[str] = ("_embedded",),
467
- ) -> Iterator[dict]:
468
- """
469
- Возвращает генератор, проходящий по всем страницам ответа API и
470
- yielding элементы коллекции.
471
- """
472
- query = dict(params or {})
473
- query.setdefault("page", 1)
474
- query.setdefault("limit", 250)
475
-
476
- while True:
477
- response = self._make_request("GET", endpoint, params=query)
478
- if not response:
479
- break
480
- items = self._extract_collection(response, data_path)
481
- if not items:
482
- break
483
- for item in items:
484
- yield item
485
-
486
- total_pages = response.get("_page_count")
487
- if total_pages is not None:
488
- has_next = query["page"] < total_pages
489
- else:
490
- links = response.get("_links") or {}
491
- next_link = links.get("next") if isinstance(links, dict) else None
492
- has_next = bool(next_link)
493
- if not has_next:
494
- break
495
- query["page"] += 1
496
-
497
- def iter_leads(
498
- self,
499
- updated_from: Optional[Union[int, float, str, datetime]] = None,
500
- updated_to: Optional[Union[int, float, str, datetime]] = None,
501
- pipeline_ids: Optional[Union[int, Sequence[Union[int, str]]]] = None,
502
- include_contacts: bool = False,
503
- include: Optional[Union[str, Sequence[str]]] = None,
504
- limit: int = 250,
505
- extra_params: Optional[dict] = None,
506
- ) -> Iterator[dict]:
507
- """
508
- Итератор сделок с фильтрацией по диапазону обновления и воронкам.
509
- """
510
- params = {"limit": limit, "page": 1}
511
- start_ts = self._to_timestamp(updated_from)
512
- end_ts = self._to_timestamp(updated_to)
513
- if start_ts is not None:
514
- params["filter[updated_at][from]"] = start_ts
515
- if end_ts is not None:
516
- params["filter[updated_at][to]"] = end_ts
517
- pipeline_param = self._format_filter_values(pipeline_ids)
518
- if pipeline_param:
519
- params["filter[pipeline_id]"] = pipeline_param
520
-
521
- include_parts: List[str] = []
522
- if include_contacts:
523
- include_parts.append("contacts")
524
- if include:
525
- if isinstance(include, str):
526
- include_parts.append(include)
527
- else:
528
- include_parts.extend([str(item) for item in include])
529
- if include_parts:
530
- params["with"] = ",".join(sorted(set(include_parts)))
531
- if extra_params:
532
- params.update(extra_params)
533
-
534
- yield from self._iterate_paginated(
535
- "/api/v4/leads", params=params, data_path=("_embedded", "leads")
536
- )
537
-
538
- def fetch_leads(self, *args, **kwargs) -> List[dict]:
539
- """
540
- Возвращает список сделок. Обёртка над iter_leads.
541
- """
542
- return list(self.iter_leads(*args, **kwargs))
543
-
544
- def iter_contacts(
545
- self,
546
- updated_from: Optional[Union[int, float, str, datetime]] = None,
547
- updated_to: Optional[Union[int, float, str, datetime]] = None,
548
- contact_ids: Optional[Union[int, Sequence[Union[int, str]]]] = None,
549
- limit: int = 250,
550
- extra_params: Optional[dict] = None,
551
- ) -> Iterator[dict]:
552
- """
553
- Итератор контактов с фильтрацией по диапазону обновления или списку ID.
554
- """
555
- params = {"limit": limit, "page": 1}
556
- start_ts = self._to_timestamp(updated_from)
557
- end_ts = self._to_timestamp(updated_to)
558
- if start_ts is not None:
559
- params["filter[updated_at][from]"] = start_ts
560
- if end_ts is not None:
561
- params["filter[updated_at][to]"] = end_ts
562
- contact_param = self._format_filter_values(contact_ids)
563
- if contact_param:
564
- params["filter[id][]"] = contact_param
565
- if extra_params:
566
- params.update(extra_params)
567
-
568
- yield from self._iterate_paginated(
569
- "/api/v4/contacts", params=params, data_path=("_embedded", "contacts")
570
- )
571
-
572
- def fetch_contacts(self, *args, **kwargs) -> List[dict]:
573
- """
574
- Возвращает список контактов. Обёртка над iter_contacts.
575
- """
576
- return list(self.iter_contacts(*args, **kwargs))
577
-
578
- def get_contact_by_id(self, contact_id: Union[int, str], include: Optional[Union[str, Sequence[str]]] = None) -> dict:
579
- """
580
- Получает данные контакта по его ID.
581
- """
582
- endpoint = f"/api/v4/contacts/{contact_id}"
583
- params = {}
584
- if include:
585
- if isinstance(include, str):
586
- params["with"] = include
587
- else:
588
- params["with"] = ",".join(str(item) for item in include)
589
- data = self._make_request("GET", endpoint, params=params)
590
- if not data or not isinstance(data, dict) or "id" not in data:
591
- raise Exception(f"Contact {contact_id} not found or invalid response.")
592
- return data
593
-
594
- def iter_notes(
595
- self,
596
- entity: str = "lead",
597
- updated_from: Optional[Union[int, float, str, datetime]] = None,
598
- updated_to: Optional[Union[int, float, str, datetime]] = None,
599
- note_type: Optional[Union[str, Sequence[str]]] = None,
600
- entity_ids: Optional[Union[int, Sequence[Union[int, str]]]] = None,
601
- limit: int = 250,
602
- extra_params: Optional[dict] = None,
603
- ) -> Iterator[dict]:
604
- """
605
- Итератор примечаний для заданной сущности.
606
- """
607
- mapping = {
608
- "lead": "leads",
609
- "contact": "contacts",
610
- "company": "companies",
611
- "customer": "customers",
612
- }
613
- plural = mapping.get(entity.lower(), entity.lower() + "s")
614
- endpoint = f"/api/v4/{plural}/notes"
615
-
616
- params = {"limit": limit, "page": 1}
617
- start_ts = self._to_timestamp(updated_from)
618
- end_ts = self._to_timestamp(updated_to)
619
- if start_ts is not None:
620
- params["filter[updated_at][from]"] = start_ts
621
- if end_ts is not None:
622
- params["filter[updated_at][to]"] = end_ts
623
- note_type_param = self._format_filter_values(note_type)
624
- if note_type_param:
625
- params["filter[note_type]"] = note_type_param
626
- entity_param = self._format_filter_values(entity_ids)
627
- if entity_param:
628
- params["filter[entity_id]"] = entity_param
629
- if extra_params:
630
- params.update(extra_params)
631
-
632
- yield from self._iterate_paginated(
633
- endpoint, params=params, data_path=("_embedded", "notes")
634
- )
635
-
636
- def fetch_notes(self, *args, **kwargs) -> List[dict]:
637
- """
638
- Возвращает список примечаний. Обёртка над iter_notes.
639
- """
640
- return list(self.iter_notes(*args, **kwargs))
641
-
642
- def iter_events(
643
- self,
644
- entity: Optional[str] = None,
645
- entity_ids: Optional[Union[int, Sequence[Union[int, str]]]] = None,
646
- event_type: Optional[Union[str, Sequence[str]]] = None,
647
- created_from: Optional[Union[int, float, str, datetime]] = None,
648
- created_to: Optional[Union[int, float, str, datetime]] = None,
649
- limit: int = 250,
650
- extra_params: Optional[dict] = None,
651
- ) -> Iterator[dict]:
652
- """
653
- Итератор событий с фильтрацией по сущности, типам и диапазону дат.
654
- """
655
- params = {"limit": limit, "page": 1}
656
- if entity:
657
- params["filter[entity]"] = entity
658
- entity_param = self._format_filter_values(entity_ids)
659
- if entity_param:
660
- params["filter[entity_id]"] = entity_param
661
- event_type_param = self._format_filter_values(event_type)
662
- if event_type_param:
663
- params["filter[type]"] = event_type_param
664
- start_ts = self._to_timestamp(created_from)
665
- end_ts = self._to_timestamp(created_to)
666
- if start_ts is not None:
667
- params["filter[created_at][from]"] = start_ts
668
- if end_ts is not None:
669
- params["filter[created_at][to]"] = end_ts
670
- if extra_params:
671
- params.update(extra_params)
672
-
673
- yield from self._iterate_paginated(
674
- "/api/v4/events", params=params, data_path=("_embedded", "events")
675
- )
676
-
677
- def fetch_events(self, *args, **kwargs) -> List[dict]:
678
- """
679
- Возвращает список событий. Обёртка над iter_events.
680
- """
681
- return list(self.iter_events(*args, **kwargs))
682
-
683
- def iter_users(
684
- self,
685
- limit: int = 250,
686
- extra_params: Optional[dict] = None,
687
- ) -> Iterator[dict]:
688
- """
689
- Итератор пользователей аккаунта.
690
- """
691
- params = {"limit": limit, "page": 1}
692
- if extra_params:
693
- params.update(extra_params)
694
- yield from self._iterate_paginated(
695
- "/api/v4/users", params=params, data_path=("_embedded", "users")
696
- )
697
-
698
- def fetch_users(self, *args, **kwargs) -> List[dict]:
699
- """
700
- Возвращает список пользователей. Обёртка над iter_users.
701
- """
702
- return list(self.iter_users(*args, **kwargs))
703
-
704
- def iter_pipelines(
705
- self,
706
- limit: int = 250,
707
- extra_params: Optional[dict] = None,
708
- ) -> Iterator[dict]:
709
- """
710
- Итератор воронок со статусами.
711
- """
712
- params = {"limit": limit, "page": 1}
713
- if extra_params:
714
- params.update(extra_params)
715
- yield from self._iterate_paginated(
716
- "/api/v4/leads/pipelines", params=params, data_path=("_embedded", "pipelines")
717
- )
718
-
719
- def fetch_pipelines(self, *args, **kwargs) -> List[dict]:
720
- """
721
- Возвращает список воронок. Обёртка над iter_pipelines.
722
- """
723
- return list(self.iter_pipelines(*args, **kwargs))
724
-
725
- def get_deal_by_id(self, deal_id, skip_fields_mapping=False):
726
- """
727
- Получает данные сделки по её ID и возвращает объект Deal.
728
- Если данные отсутствуют или имеют неверную структуру, выбрасывается исключение.
729
-
730
- :param deal_id: ID сделки для получения
731
- :param skip_fields_mapping: Если True, не загружает справочник кастомных полей
732
- (используйте для работы только с ID полей)
733
- :return: Объект Deal с данными сделки
734
- """
735
- endpoint = f"/api/v4/leads/{deal_id}"
736
- params = {'with': 'contacts,companies,catalog_elements,loss_reason,tags'}
737
- data = self._make_request("GET", endpoint, params=params)
738
-
739
- # Проверяем, что получили данные и что они содержат ключ "id"
740
- if not data or not isinstance(data, dict) or "id" not in data:
741
- self.logger.error(f"Deal {deal_id} not found or invalid response: {data}")
742
- raise Exception(f"Deal {deal_id} not found or invalid response.")
743
-
744
- custom_config = None if skip_fields_mapping else self.get_custom_fields_mapping()
745
- self.logger.debug(f"Deal {deal_id} data received (содержимое полей не выводится полностью).")
746
- return Deal(data, custom_fields_config=custom_config, logger=self.logger)
747
-
748
- def _save_custom_fields_cache(self, mapping):
749
- """
750
- Сохраняет кэш кастомных полей в файл, если используется файловый кэш.
751
- Если кэширование отключено или выбран кэш в памяти, операция пропускается.
752
- """
753
- if not self.cache_config.enabled:
754
- self.logger.debug("Caching disabled; cache not saved.")
755
- return
756
- if self.cache_config.storage != 'file':
757
- self.logger.debug("Using memory caching; no file cache saved.")
758
- return
759
- cache_data = {"last_updated": time.time(), "mapping": mapping}
760
- with open(self.cache_config.file, "w") as f:
761
- json.dump(cache_data, f)
762
- self.logger.debug(f"Custom fields cache saved to {self.cache_config.file}")
763
-
764
- def _load_custom_fields_cache(self):
765
- """
766
- Загружает кэш кастомных полей из файла, если используется файловый кэш.
767
- Если кэширование отключено или выбран кэш в памяти, возвращает None.
768
- """
769
- if not self.cache_config.enabled:
770
- self.logger.debug("Caching disabled; no cache loaded.")
771
- return None
772
- if self.cache_config.storage != 'file':
773
- self.logger.debug("Using memory caching; cache will be kept in memory only.")
774
- return None
775
- if os.path.exists(self.cache_config.file):
776
- with open(self.cache_config.file, "r") as f:
777
- try:
778
- cache_data = json.load(f)
779
- self.logger.debug("Custom fields cache loaded successfully.")
780
- return cache_data
781
- except Exception as e:
782
- self.logger.error(f"Error loading cache: {e}")
783
- return None
784
- return None
785
-
786
- def get_custom_fields_mapping(self, force_update=False):
787
- """
788
- Возвращает словарь отображения кастомных полей для сделок.
789
- Если данные кэшированы и не устарели, возвращает кэш; иначе выполняет запросы для получения данных.
790
- """
791
- if not force_update and self._custom_fields_mapping is not None:
792
- return self._custom_fields_mapping
793
-
794
- cache_data = self._load_custom_fields_cache() if self.cache_config.enabled else None
795
- if cache_data:
796
- last_updated = cache_data.get("last_updated", 0)
797
- if self.cache_config.lifetime_hours is not None:
798
- if time.time() - last_updated < self.cache_config.lifetime_hours * 3600:
799
- self._custom_fields_mapping = cache_data.get("mapping")
800
- self.logger.debug("Using cached custom fields mapping.")
801
- return self._custom_fields_mapping
802
- else:
803
- # Бесконечный кэш – не проверяем срок
804
- self._custom_fields_mapping = cache_data.get("mapping")
805
- self.logger.debug("Using cached custom fields mapping (infinite cache).")
806
- return self._custom_fields_mapping
807
-
808
- mapping = {}
809
- page = 1
810
- total_pages = 1 # Значение по умолчанию
811
- while page <= total_pages:
812
- endpoint = f"/api/v4/leads/custom_fields?limit=250&page={page}"
813
- response = self._make_request("GET", endpoint)
814
- if response and "_embedded" in response and "custom_fields" in response["_embedded"]:
815
- for field in response["_embedded"]["custom_fields"]:
816
- mapping[field["id"]] = field
817
- total_pages = response.get("_page_count", page)
818
- self.logger.debug(f"Fetched page {page} of {total_pages}")
819
- page += 1
820
- else:
821
- break
822
-
823
- self.logger.debug("Custom fields mapping fetched (содержимое маппинга не выводится полностью).")
824
- self._custom_fields_mapping = mapping
825
- if self.cache_config.enabled:
826
- self._save_custom_fields_cache(mapping)
827
- return mapping
828
-
829
- def find_custom_field_id(self, search_term):
830
- """
831
- Ищет кастомное поле по заданному названию (или части названия).
832
-
833
- :param search_term: Строка для поиска по имени поля.
834
- :return: Кортеж (field_id, field_obj) если найдено, иначе (None, None).
835
- """
836
- mapping = self.get_custom_fields_mapping()
837
- search_term_lower = search_term.lower().strip()
838
- for key, field_obj in mapping.items():
839
- if isinstance(field_obj, dict):
840
- name = field_obj.get("name", "").lower().strip()
841
- else:
842
- name = str(field_obj).lower().strip()
843
- if search_term_lower == name or search_term_lower in name:
844
- self.logger.debug(f"Found custom field '{name}' with id {key}")
845
- return int(key), field_obj
846
- self.logger.debug(f"Custom field containing '{search_term}' not found.")
847
- return None, None
848
-
849
- def update_lead(self, lead_id, update_fields: dict, tags_to_add: list = None, tags_to_delete: list = None):
850
- """
851
- Обновляет сделку, задавая новые значения для стандартных и кастомных полей.
852
-
853
- Для кастомных полей:
854
- - Если значение передается как целое число, оно интерпретируется как идентификатор варианта (enum_id)
855
- для полей типа select.
856
- - Если значение передается как строка, используется ключ "value".
857
-
858
- :param lead_id: ID сделки, которую нужно обновить.
859
- :param update_fields: Словарь с полями для обновления. Ключи могут быть стандартными или названием кастомного поля.
860
- :param tags_to_add: Список тегов для добавления к сделке.
861
- :param tags_to_delete: Список тегов для удаления из сделки.
862
- :return: Ответ API в формате JSON.
863
- :raises Exception: Если одно из кастомных полей не найдено.
864
- """
865
- payload = {}
866
- standard_fields = {
867
- "name", "price", "status_id", "pipeline_id", "created_by", "updated_by",
868
- "closed_at", "created_at", "updated_at", "loss_reason_id", "responsible_user_id"
869
- }
870
- custom_fields = []
871
- for key, value in update_fields.items():
872
- if key in standard_fields:
873
- payload[key] = value
874
- self.logger.debug(f"Standard field {key} set to {value}")
875
- else:
876
- if isinstance(value, int):
877
- field_value_dict = {"enum_id": value}
878
- else:
879
- field_value_dict = {"value": value}
880
- try:
881
- field_id = int(key)
882
- custom_fields.append({"field_id": field_id, "values": [field_value_dict]})
883
- self.logger.debug(f"Custom field by id {field_id} set to {value}")
884
- except ValueError:
885
- field_id, field_obj = self.find_custom_field_id(key)
886
- if field_id is not None:
887
- custom_fields.append({"field_id": field_id, "values": [field_value_dict]})
888
- self.logger.debug(f"Custom field '{key}' found with id {field_id} set to {value}")
889
- else:
890
- raise Exception(f"Custom field '{key}' не найден.")
891
- if custom_fields:
892
- payload["custom_fields_values"] = custom_fields
893
- if tags_to_add:
894
- payload["tags_to_add"] = tags_to_add
895
- if tags_to_delete:
896
- payload["tags_to_delete"] = tags_to_delete
897
- self.logger.debug("Update payload for lead {} prepared (содержимое payload не выводится полностью).".format(lead_id))
898
- endpoint = f"/api/v4/leads/{lead_id}"
899
- response = self._make_request("PATCH", endpoint, data=payload)
900
- self.logger.debug("Update response received.")
901
- return response
902
-
903
- def get_entity_notes(self, entity, entity_id, get_all=False, note_type=None, extra_params=None):
904
- """
905
- Получает список примечаний для указанной сущности и её ID.
906
-
907
- Используется эндпоинт:
908
- GET /api/v4/{entity_plural}/{entity_id}/notes
909
-
910
- :param entity: Тип сущности (например, 'lead', 'contact', 'company', 'customer' и т.д.).
911
- Передаётся в единственном числе, для формирования конечной точки будет использована
912
- таблица преобразования (например, 'lead' -> 'leads').
913
- :param entity_id: ID сущности.
914
- :param get_all: Если True, метод автоматически проходит по всем страницам пагинации.
915
- :param note_type: Фильтр по типу примечания. Может быть строкой (например, 'common') или списком строк.
916
- :param extra_params: Словарь дополнительных GET-параметров, если требуется.
917
- :return: Список примечаний (каждый элемент – словарь с данными примечания).
918
- """
919
- # Преобразуем тип сущности в форму во множественном числе (для известных типов)
920
- mapping = {
921
- 'lead': 'leads',
922
- 'contact': 'contacts',
923
- 'company': 'companies',
924
- 'customer': 'customers'
925
- }
926
- plural = mapping.get(entity.lower(), entity.lower() + "s")
927
-
928
- endpoint = f"/api/v4/{plural}/{entity_id}/notes"
929
- params = {
930
- "page": 1,
931
- "limit": 250
932
- }
933
- if note_type is not None:
934
- params["filter[note_type]"] = note_type
935
- if extra_params:
936
- params.update(extra_params)
937
-
938
- notes = []
939
- while True:
940
- response = self._make_request("GET", endpoint, params=params)
941
- if response and "_embedded" in response and "notes" in response["_embedded"]:
942
- notes.extend(response["_embedded"]["notes"])
943
- if not get_all:
944
- break
945
- total_pages = response.get("_page_count", params["page"])
946
- if params["page"] >= total_pages:
947
- break
948
- params["page"] += 1
949
- self.logger.debug(f"Retrieved {len(notes)} notes for {entity} {entity_id}")
950
- return notes
951
-
952
- def get_entity_note(self, entity, entity_id, note_id):
953
- """
954
- Получает расширенную информацию по конкретному примечанию для указанной сущности.
955
-
956
- Используется эндпоинт:
957
- GET /api/v4/{entity_plural}/{entity_id}/notes/{note_id}
958
-
959
- :param entity: Тип сущности (например, 'lead', 'contact', 'company', 'customer' и т.д.).
960
- :param entity_id: ID сущности.
961
- :param note_id: ID примечания.
962
- :return: Словарь с полной информацией о примечании.
963
- :raises Exception: При ошибке запроса.
964
- """
965
- mapping = {
966
- 'lead': 'leads',
967
- 'contact': 'contacts',
968
- 'company': 'companies',
969
- 'customer': 'customers'
970
- }
971
- plural = mapping.get(entity.lower(), entity.lower() + "s")
972
- endpoint = f"/api/v4/{plural}/{entity_id}/notes/{note_id}"
973
- self.logger.debug(f"Fetching note {note_id} for {entity} {entity_id}")
974
- note_data = self._make_request("GET", endpoint)
975
- self.logger.debug(f"Note {note_id} for {entity} {entity_id} fetched successfully.")
976
- return note_data
977
-
978
- # Удобные обёртки для сделок и контактов:
979
- def get_deal_notes(self, deal_id, **kwargs):
980
- return self.get_entity_notes("lead", deal_id, **kwargs)
981
-
982
- def get_deal_note(self, deal_id, note_id):
983
- return self.get_entity_note("lead", deal_id, note_id)
984
-
985
- def get_contact_notes(self, contact_id, **kwargs):
986
- return self.get_entity_notes("contact", contact_id, **kwargs)
987
-
988
- def get_contact_note(self, contact_id, note_id):
989
- return self.get_entity_note("contact", contact_id, note_id)
990
-
991
- def get_entity_events(self, entity, entity_id=None, get_all=False, event_type=None, extra_params=None):
992
- """
993
- Получает список событий для указанной сущности.
994
- Если entity_id не указан (None), возвращает события для всех сущностей данного типа.
995
-
996
- :param entity: Тип сущности (например, 'lead', 'contact', 'company' и т.д.).
997
- :param entity_id: ID сущности или None для получения событий по всем сущностям данного типа.
998
- :param get_all: Если True, автоматически проходит по всем страницам пагинации.
999
- :param event_type: Фильтр по типу события. Может быть строкой или списком строк.
1000
- :param extra_params: Словарь дополнительных GET-параметров.
1001
- :return: Список событий (каждый элемент – словарь с данными события).
1002
- """
1003
- params = {
1004
- 'page': 1,
1005
- 'limit': 100,
1006
- 'filter[entity]': entity,
1007
- }
1008
- # Добавляем фильтр по ID, если он указан
1009
- if entity_id is not None:
1010
- params['filter[entity_id]'] = entity_id
1011
- # Фильтр по типу события
1012
- if event_type is not None:
1013
- params['filter[type]'] = event_type
1014
- if extra_params:
1015
- params.update(extra_params)
1016
-
1017
- events = []
1018
- while True:
1019
- response = self._make_request("GET", "/api/v4/events", params=params)
1020
- if response and "_embedded" in response and "events" in response["_embedded"]:
1021
- events.extend(response["_embedded"]["events"])
1022
- # Если не нужно получать все страницы, выходим
1023
- if not get_all:
1024
- break
1025
- total_pages = response.get("_page_count", params['page'])
1026
- if params['page'] >= total_pages:
1027
- break
1028
- params['page'] += 1
1029
- return events
1030
-
1031
- # Удобные обёртки:
1032
- def get_deal_events(self, deal_id, **kwargs):
1033
- return self.get_entity_events("lead", deal_id, **kwargs)
1034
-
1035
- def get_contact_events(self, contact_id, **kwargs):
1036
- return self.get_entity_events("contact", contact_id, **kwargs)
1037
-
1038
- def fetch_updated_leads_raw(
1039
- self,
1040
- pipeline_id,
1041
- updated_from,
1042
- updated_to=None,
1043
- save_to_file=None,
1044
- limit=250,
1045
- include_contacts=False,
1046
- ):
1047
- """Возвращает сделки из указанной воронки, обновленные в заданный период.
1048
-
1049
- :param pipeline_id: ID воронки.
1050
- :param updated_from: datetime, начиная с которого искать изменения.
1051
- :param updated_to: datetime окончания диапазона (опционально).
1052
- :param save_to_file: путь к файлу для сохранения результатов в формате JSON.
1053
- :param limit: количество элементов на страницу (максимум 250).
1054
- :param include_contacts: если True, в ответ будут включены данные контактов.
1055
- :return: список словарей со сделками.
1056
- """
1057
-
1058
- all_leads = self.fetch_leads(
1059
- updated_from=updated_from,
1060
- updated_to=updated_to,
1061
- pipeline_ids=pipeline_id,
1062
- include_contacts=include_contacts,
1063
- limit=limit,
1064
- )
1065
- if save_to_file:
1066
- with open(save_to_file, "w", encoding="utf-8") as f:
1067
- json.dump(all_leads, f, ensure_ascii=False, indent=2)
1068
-
1069
- self.logger.debug(f"Fetched {len(all_leads)} leads from pipeline {pipeline_id}")
1070
- return all_leads
1071
-
1072
- def get_event(self, event_id):
1073
- """
1074
- Получает подробную информацию по конкретному событию по его ID.
1075
-
1076
- Используется эндпоинт:
1077
- GET /api/v4/events/{event_id}
1078
-
1079
- :param event_id: ID события.
1080
- :return: Словарь с подробной информацией о событии.
1081
- :raises Exception: При ошибке запроса.
1082
- """
1083
- endpoint = f"/api/v4/events/{event_id}"
1084
- self.logger.debug(f"Fetching event with ID {event_id}")
1085
- event_data = self._make_request("GET", endpoint)
1086
- self.logger.debug(f"Event {event_id} details fetched successfully.")
1087
- return event_data
1088
-
1089
- def get_pipelines(self):
1090
- """
1091
- Получает список всех воронок и их статусов из amoCRM.
1092
-
1093
- :return: Список словарей, где каждый словарь содержит данные воронки, а также, если присутствует, вложенные статусы.
1094
- :raises Exception: Если данные не получены или структура ответа неверна.
1095
- """
1096
- pipelines = self.fetch_pipelines()
1097
- if pipelines:
1098
- self.logger.debug(f"Получено {len(pipelines)} воронок")
1099
- return pipelines
1100
- self.logger.error("Не удалось получить воронки из amoCRM")
1101
- raise Exception("Ошибка получения воронок из amoCRM")