Added comments to Python Code.
This commit is contained in:
1 parent
aa4c5f3681
commit
7bd6b9c4b8
8 files changed
+448
-24
No files matched your search
+38
-4
@@ -1,3 +1,8 @@
|
||||
"""
|
||||
API-слой: парсинг JSON-пейлоадов и диспетчеризация на функции расчёта.
|
||||
|
||||
Связывает веб/Hook-вход с доменной логикой (domain, reports).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict
|
||||
@@ -17,14 +22,15 @@ from .history import CalculationStore
|
||||
|
||||
|
||||
class ApiError(ValueError):
|
||||
"""A user-facing validation error suitable for a JSON response."""
|
||||
|
||||
"""Ошибка валидации, возвращаемая клиенту в виде JSON."""
|
||||
|
||||
# Лениво загружаемые синглотоны
|
||||
_IDENTITY_DIRECTORY: IdentityDirectory | None = None
|
||||
_CALCULATION_STORE: CalculationStore | None = None
|
||||
_CALUCALUTION_STORE: CalculationStore | None = None
|
||||
|
||||
|
||||
def _identity_directory() -> IdentityDirectory:
|
||||
"""Ленивая инициализация справочника идентичностей (синглотон)."""
|
||||
global _IDENTITY_DIRECTORY
|
||||
if _IDENTITY_DIRECTORY is None:
|
||||
_IDENTITY_DIRECTORY = IdentityDirectory.from_environment(persistent=True)
|
||||
@@ -32,6 +38,7 @@ def _identity_directory() -> IdentityDirectory:
|
||||
|
||||
|
||||
def _calculation_store() -> CalculationStore:
|
||||
"""Ленивая инициализация хранилища расчётов (синглотон)."""
|
||||
global _CALCULATION_STORE
|
||||
if _CALCULATION_STORE is None:
|
||||
_CALCULATION_STORE = CalculationStore.from_environment()
|
||||
@@ -39,12 +46,22 @@ def _calculation_store() -> CalculationStore:
|
||||
|
||||
|
||||
def calculate_and_store(payload: dict[str, Any], *, actor_id: int | None, source: str) -> dict[str, Any]:
|
||||
"""
|
||||
Расчёт + сохранение в историю за один вызов.
|
||||
|
||||
Используется веб-хуками и сторонними интеграциями.
|
||||
"""
|
||||
response = calculate_payload(payload)
|
||||
_calculation_store().save(actor_id=actor_id, source=source, payload=payload, response=response)
|
||||
return response
|
||||
|
||||
|
||||
def inspect_bulk_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Предварительная проверка массового ввода без выполнения расчёта.
|
||||
|
||||
Используется для AJAX-подсказок при вводе.
|
||||
"""
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("text"), str):
|
||||
raise ApiError("Ожидалось текстовое поле text")
|
||||
from .vk_bot import inspect_bulk_text
|
||||
@@ -52,7 +69,11 @@ def inspect_bulk_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Resolve either character name or ID from the optional configured directory."""
|
||||
"""
|
||||
Разрешает связку имени и ID персонажа из справочника.
|
||||
|
||||
Поддерживает поиск по имени или ID, а также сохранение новой связки.
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise ApiError("Ожидался JSON-объект")
|
||||
name = str(payload.get("name", "")).strip() or None
|
||||
@@ -79,12 +100,14 @@ def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _required(payload: dict[str, Any], key: str) -> Any:
|
||||
"""Проверяет наличие обязательного поля в пейлоаде."""
|
||||
if key not in payload:
|
||||
raise ApiError(f"Не заполнено поле: {key}")
|
||||
return payload[key]
|
||||
|
||||
|
||||
def _int(payload: dict[str, Any], key: str) -> int:
|
||||
"""Преобразует значение в int с валидацией и понятным сообщением об ошибке."""
|
||||
value = _required(payload, key)
|
||||
if isinstance(value, bool):
|
||||
raise ApiError(f"Поле {key} должно быть числом")
|
||||
@@ -95,11 +118,22 @@ def _int(payload: dict[str, Any], key: str) -> int:
|
||||
|
||||
|
||||
def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Главный диспетчер расчётов.
|
||||
|
||||
Распознаёт mode из payload и делегирует:
|
||||
- "coaching" → расчёт ЛУ/ЗУ (CoachingSession)
|
||||
- "training" → расчёт тренировки (TrainingSession)
|
||||
- "inspection" → расчёт осмотра (InspectionReport)
|
||||
|
||||
Возвращает словарь с mode, result (dict) и message (строка).
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise ApiError("Ожидался JSON-объект")
|
||||
mode = payload.get("mode")
|
||||
try:
|
||||
if mode == "coaching":
|
||||
# Парсинг дополнительных котят: поддерживаются dict и tuple/list
|
||||
raw_extras = payload.get("extra_kittens", [])
|
||||
if not isinstance(raw_extras, (list, tuple)):
|
||||
raise ApiError("Поле extra_kittens должно быть списком")
|
||||
|
||||
Reference in new issue
Block a user