feat: add Belichya Nora calculator and VK bot
This commit is contained in:
1 parent
cd6a594ed4
commit
c86d077f9f
20 files changed
+2002
-18
No files matched your search
@@ -0,0 +1,147 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict
|
||||
from typing import Any
|
||||
|
||||
from .domain import (
|
||||
CoachingSession,
|
||||
InspectionReport,
|
||||
TrainingSession,
|
||||
calculate_coaching,
|
||||
calculate_training,
|
||||
)
|
||||
from .reports import render_coaching, render_inspection, render_training
|
||||
from .identity import IdentityDirectory
|
||||
from .history import CalculationStore
|
||||
|
||||
|
||||
class ApiError(ValueError):
|
||||
"""A user-facing validation error suitable for a JSON response."""
|
||||
|
||||
|
||||
_IDENTITY_DIRECTORY: IdentityDirectory | None = None
|
||||
_CALCULATION_STORE: CalculationStore | None = None
|
||||
|
||||
|
||||
def _identity_directory() -> IdentityDirectory:
|
||||
global _IDENTITY_DIRECTORY
|
||||
if _IDENTITY_DIRECTORY is None:
|
||||
_IDENTITY_DIRECTORY = IdentityDirectory.from_environment(persistent=True)
|
||||
return _IDENTITY_DIRECTORY
|
||||
|
||||
|
||||
def _calculation_store() -> CalculationStore:
|
||||
global _CALCULATION_STORE
|
||||
if _CALCULATION_STORE is None:
|
||||
_CALCULATION_STORE = CalculationStore.from_environment()
|
||||
return _CALCULATION_STORE
|
||||
|
||||
|
||||
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]:
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("text"), str):
|
||||
raise ApiError("Ожидалось текстовое поле text")
|
||||
from .vk_bot import inspect_bulk_text
|
||||
return inspect_bulk_text(payload["text"])
|
||||
|
||||
|
||||
def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Resolve either character name or ID from the optional configured directory."""
|
||||
if not isinstance(payload, dict):
|
||||
raise ApiError("Ожидался JSON-объект")
|
||||
name = str(payload.get("name", "")).strip() or None
|
||||
raw_id = payload.get("character_id")
|
||||
if not name and raw_id in (None, ""):
|
||||
raise ApiError("Укажите имя или ID персонажа")
|
||||
try:
|
||||
character_id = int(raw_id) if raw_id not in (None, "") else None
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApiError("ID персонажа должно быть числом") from exc
|
||||
directory = _identity_directory()
|
||||
identity = directory.resolve(name=name, character_id=character_id)
|
||||
if identity:
|
||||
return {"status": "found", "name": identity.name, "character_id": identity.character_id}
|
||||
if payload.get("remember") and name and character_id is not None:
|
||||
identity = directory.remember(name=name, character_id=character_id)
|
||||
return {"status": "saved", "name": identity.name, "character_id": identity.character_id}
|
||||
return {
|
||||
"status": "needs_input",
|
||||
"name": name or "",
|
||||
"character_id": character_id,
|
||||
"message": directory.suggest(name=name, character_id=character_id),
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
value = _required(payload, key)
|
||||
if isinstance(value, bool):
|
||||
raise ApiError(f"Поле {key} должно быть числом")
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApiError(f"Поле {key} должно быть числом") from exc
|
||||
|
||||
|
||||
def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not isinstance(payload, dict):
|
||||
raise ApiError("Ожидался JSON-объект")
|
||||
mode = payload.get("mode")
|
||||
try:
|
||||
if mode == "coaching":
|
||||
extras = tuple(
|
||||
(str(item["name"]), int(item["id"]), str(item.get("independence", "самостоятельно")))
|
||||
for item in payload.get("extra_kittens", [])
|
||||
)
|
||||
session = CoachingSession(
|
||||
date=str(_required(payload, "date")),
|
||||
skill=str(_required(payload, "skill")),
|
||||
start=str(_required(payload, "start")),
|
||||
end=str(_required(payload, "end")),
|
||||
escort_name=str(_required(payload, "escort_name")),
|
||||
escort_id=_int(payload, "escort_id"),
|
||||
kitten_name=str(_required(payload, "kitten_name")),
|
||||
kitten_id=_int(payload, "kitten_id"),
|
||||
kitten_independence=str(payload.get("kitten_independence", "самостоятельно")),
|
||||
extra_kittens=extras,
|
||||
)
|
||||
result = calculate_coaching(session)
|
||||
return {
|
||||
"mode": mode,
|
||||
"result": asdict(result),
|
||||
"message": render_coaching(session, result),
|
||||
}
|
||||
if mode == "training":
|
||||
session = TrainingSession(
|
||||
escort_name=str(_required(payload, "escort_name")),
|
||||
escort_id=_int(payload, "escort_id"),
|
||||
kitten_name=str(_required(payload, "kitten_name")),
|
||||
kitten_id=_int(payload, "kitten_id"),
|
||||
)
|
||||
result = calculate_training(session)
|
||||
return {"mode": mode, "result": asdict(result), "message": render_training(session, result)}
|
||||
if mode == "inspection":
|
||||
resources = tuple((str(name), int(amount)) for name, amount in payload.get("resources", []))
|
||||
report = InspectionReport(
|
||||
character_name=str(_required(payload, "character_name")),
|
||||
character_id=_int(payload, "character_id"),
|
||||
place=str(_required(payload, "place")),
|
||||
inspections=_int(payload, "inspections"),
|
||||
resources=resources,
|
||||
)
|
||||
return {"mode": mode, "message": render_inspection(report)}
|
||||
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
||||
if isinstance(exc, ApiError):
|
||||
raise
|
||||
raise ApiError(str(exc)) from exc
|
||||
raise ApiError("Неизвестный режим калькулятора")
|
||||
Reference in new issue
Block a user