fix(api): validate nested report fields
This commit is contained in:
1 parent
92171731ae
commit
0aec421ad2
6 files changed
+48
-6
No files matched your search
+25
-5
@@ -12,6 +12,7 @@ from typing import Any
|
||||
from .domain import (
|
||||
CoachingSession,
|
||||
InspectionReport,
|
||||
MAX_INSPECTION_RESOURCES,
|
||||
TrainingSession,
|
||||
calculate_coaching,
|
||||
calculate_inspection,
|
||||
@@ -114,13 +115,17 @@ def _required(payload: dict[str, Any], key: str) -> Any:
|
||||
|
||||
def _int(payload: dict[str, Any], key: str) -> int:
|
||||
"""Преобразует значение в int с валидацией и понятным сообщением об ошибке."""
|
||||
value = _required(payload, key)
|
||||
return _int_value(_required(payload, key), f"Поле {key}")
|
||||
|
||||
|
||||
def _int_value(value: Any, label: str) -> int:
|
||||
"""Convert one JSON integer while refusing Python's boolean coercion."""
|
||||
if isinstance(value, bool):
|
||||
raise ApiError(f"Поле {key} должно быть числом")
|
||||
raise ApiError(f"{label} должно быть числом")
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApiError(f"Поле {key} должно быть числом") from exc
|
||||
raise ApiError(f"{label} должно быть числом") from exc
|
||||
|
||||
|
||||
def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -154,7 +159,9 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
independence = item[2] if len(item) > 2 else "самостоятельно"
|
||||
else:
|
||||
raise ApiError("Дополнительный котёнок должен содержать имя и ID")
|
||||
extras_list.append((str(name), int(kitten_id), str(independence)))
|
||||
if not isinstance(name, str) or not name.strip():
|
||||
raise ApiError("Укажите имя дополнительного котёнка")
|
||||
extras_list.append((name, _int_value(kitten_id, "ID дополнительного котёнка"), str(independence)))
|
||||
extras = tuple(extras_list)
|
||||
session = CoachingSession(
|
||||
date=str(_required(payload, "date")),
|
||||
@@ -184,7 +191,20 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
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", []))
|
||||
raw_resources = payload.get("resources", [])
|
||||
if not isinstance(raw_resources, (list, tuple)):
|
||||
raise ApiError("Поле resources должно быть списком")
|
||||
if len(raw_resources) > MAX_INSPECTION_RESOURCES:
|
||||
raise ApiError(f"В одном отчёте может быть не более {MAX_INSPECTION_RESOURCES} ресурсов")
|
||||
resources_list = []
|
||||
for item in raw_resources:
|
||||
if not isinstance(item, (list, tuple)) or len(item) != 2:
|
||||
raise ApiError("Каждый ресурс должен содержать название и количество")
|
||||
name, amount = item
|
||||
if not isinstance(name, str) or not name.strip():
|
||||
raise ApiError("Укажите название ресурса")
|
||||
resources_list.append((name, _int_value(amount, "Количество ресурса")))
|
||||
resources = tuple(resources_list)
|
||||
report = InspectionReport(
|
||||
character_name=str(_required(payload, "character_name")),
|
||||
character_id=_int(payload, "character_id"),
|
||||
|
||||
Reference in new issue
Block a user