feat: calculate inspection resource points

This commit is contained in:
nyan404 committed 2026-08-16 16:41:31 +03:00
1 parent 5809d5a595
commit 21652d0001
6 files changed
+46 -2

No files matched your search

+2
View File
@@ -39,6 +39,8 @@ python3 -m app.belki.vk_bot
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот скачивает фото, загружает его через API `image-hosting-web` и сохраняет постоянный `mirror_url`; админская панель показывает зеркальную ссылку. Без настройки API сохраняется исходная ссылка VK. Google Sheets пока не подключён.
Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Количество ресурса умножается на его стоимость с учётом знака.
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля и показывает сохранённые расчёты с сортировкой по ID или имени котёнка. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
## Структура
+3 -1
View File
@@ -8,6 +8,7 @@ from .domain import (
InspectionReport,
TrainingSession,
calculate_coaching,
calculate_inspection,
calculate_training,
)
from .reports import render_coaching, render_inspection, render_training
@@ -139,7 +140,8 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
inspections=_int(payload, "inspections"),
resources=resources,
)
return {"mode": mode, "message": render_inspection(report)}
result = calculate_inspection(report)
return {"mode": mode, "result": asdict(result), "message": render_inspection(report, result)}
except (KeyError, IndexError, TypeError, ValueError) as exc:
if isinstance(exc, ApiError):
raise
+24
View File
@@ -146,3 +146,27 @@ class InspectionReport:
for name, amount in self.resources:
if not name.strip() or not isinstance(amount, int):
raise ValueError("Ресурс должен иметь название и целое количество")
@dataclass(frozen=True)
class InspectionResult:
points: int
def _inspection_resource_value(name: str) -> int:
normalized = " ".join(name.casefold().replace("ё", "е").split())
if "надпис" in normalized or "ядовит" in normalized:
return 0
if normalized in ("паутина", "паук"):
return 7
if normalized == "обычный мох":
return 3
if normalized == "водяной мох":
return 2
return 1
def calculate_inspection(report: InspectionReport) -> InspectionResult:
points = report.inspections * 2
points += sum(amount * _inspection_resource_value(name) for name, amount in report.resources)
return InspectionResult(points=points)
+5 -1
View File
@@ -4,8 +4,10 @@ from .domain import (
CoachingResult,
CoachingSession,
InspectionReport,
InspectionResult,
TrainingSession,
TrainingResult,
calculate_inspection,
format_clock,
parse_clock,
)
@@ -38,7 +40,8 @@ def render_training(session: TrainingSession, result: TrainingResult | None = No
)
def render_inspection(report: InspectionReport) -> str:
def render_inspection(report: InspectionReport, result: InspectionResult | None = None) -> str:
result = result or calculate_inspection(report)
if report.inspections == 1:
word = "раз"
else:
@@ -55,4 +58,5 @@ def render_inspection(report: InspectionReport) -> str:
)
else:
lines.append("0")
lines.append(f"Баллы осмотра: {result.points} баллы.")
return "\n".join(lines)
+1
View File
@@ -41,6 +41,7 @@ class ApiTests(unittest.TestCase):
}
)
self.assertIn("осмотрел(-а) дупло 6 раз", response["message"])
self.assertEqual(response["result"]["points"], 17)
def test_bulk_inspection_payload_explains_missing_fields(self):
response = inspect_bulk_payload({"text": "/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]"})
+11
View File
@@ -5,6 +5,7 @@ from app.belki.domain import (
InspectionReport,
TrainingSession,
calculate_coaching,
calculate_inspection,
calculate_training,
format_clock,
parse_clock,
@@ -112,6 +113,16 @@ class ReportTests(unittest.TestCase):
self.assertIn("-2 вьюнок.", text)
self.assertIn("+1 паук.", text)
self.assertNotIn("Скриншот", text)
self.assertIn("Баллы осмотра: 17 баллы.", text)
def test_inspection_points_include_attempts_and_resource_values(self):
report = InspectionReport(
character_name="Дикая Вишня", character_id=1604614,
place="дупло", inspections=2,
resources=(("паутина", 1), ("надпись", 1)),
)
self.assertEqual(calculate_inspection(report).points, 11)
self.assertIn("Баллы осмотра: 11 баллы.", render_inspection(report))
if __name__ == "__main__":