feat: add earned points calculator

This commit is contained in:
nyan404 committed 2026-08-25 13:32:33 +03:00
1 parent 8e4f461e8b
commit 9e3b50c967
7 files changed
+160 -5

No files matched your search

+31
View File
@@ -148,6 +148,37 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
raise ApiError("Ожидался JSON-объект")
mode = payload.get("mode")
try:
if mode == "points":
activity = str(_required(payload, "activity"))
if activity == "coaching":
statuses = payload.get("kitten_statuses", ["самостоятельно"])
if not isinstance(statuses, list) or not 1 <= len(statuses) <= 3:
raise ApiError("Укажите от одного до трёх статусов котят")
primary_status, *extra_statuses = [str(status) for status in statuses]
session = CoachingSession(
date="01.01", skill=str(_required(payload, "skill")),
start=str(_required(payload, "start")), end=str(_required(payload, "end")),
escort_name="Куратор", escort_id=1, kitten_name="Бельчонок 1", kitten_id=2,
kitten_independence=primary_status,
extra_kittens=tuple((f"Бельчонок {index}", index + 2, status)
for index, status in enumerate(extra_statuses, start=2)),
)
result = calculate_coaching(session)
return {"mode": mode, "activity": activity, "result": {
"minutes": result.minutes, "curator_points": result.escort_points,
"kitten_points": [result.kitten_points] * result.kitten_count,
}}
if activity == "training":
return {"mode": mode, "activity": activity, "result": {"kitten_points": calculate_training(
TrainingSession("Куратор", 1, "Бельчонок 1", 2)).points}}
if activity == "inspection":
raw_resources = payload.get("resources", [])
if not isinstance(raw_resources, list):
raise ApiError("Поле resources должно быть списком")
resources = tuple((str(item[0]), _int_value(item[1], "Количество ресурса")) for item in raw_resources)
result = calculate_inspection(InspectionReport("Персонаж", 1, str(_required(payload, "place")), _int(payload, "inspections"), resources))
return {"mode": mode, "activity": activity, "result": {"points": result.points}}
raise ApiError("Неизвестный вид занятия")
if mode == "coaching":
# Парсинг дополнительных котят: поддерживаются dict и tuple/list
raw_extras = payload.get("extra_kittens", [])
+43 -3
View File
@@ -954,6 +954,10 @@ class BelkiDialog:
("kitten_independence", "Котёнок самостоятельный или несамостоятельный?"),
("kitten_count", "Сколько котят участвует в одном заходе?"),
),
"points_choice": (("activity", "Что посчитать: прокачку, тренировку или осмотр?"),),
"points_coaching": (("skill", "Какой навык считать: ЛУ или ЗУ?"), ("start", "Укажите время начала в формате HH:MM."), ("end", "Укажите время конца в формате HH:MM."), ("kitten_count", "Сколько бельчат участвует (от 1 до 3)?"), ("independence", "Укажите статус каждого бельчонка через запятую: сам или несам.")),
"points_inspection": (("place", "Укажите место: дупло или расщелина."), ("inspections", "Сколько было осмотров?"), ("resources", "Перечислите ресурсы, например: +1 вьюнок, +3 паук — или напишите «без ресурсов'.")),
"points_training": (),
}
def __init__(self, identity_directory: IdentityDirectory | None = None, *, onboarding: bool = False,
@@ -1097,7 +1101,7 @@ class BelkiDialog:
"buttons": [
[self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")],
[self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")],
[self._button("Калькулятор цели", "menu:goal", "secondary")],
[self._button("Калькулятор баллов", "menu:goal", "secondary")],
[self._button("Подать заявку", "menu:application", "secondary")],
[self._button("Помощь", "menu:help", "secondary")],
],
@@ -1169,6 +1173,21 @@ class BelkiDialog:
count = 1 + len(state["extra_kittens"])
return f"Укажите статус каждого котёнка по порядку (НЕ КНОПКАМИ, ТЕКСТОМ через запятую, всего {count}): сам/самостоятельно или несам/несамостоятельно.\nПример: сам, несам\nСам, сам"
return prompt
if state["mode"].startswith("points_"):
activity = state["mode"].removeprefix("points_")
payload = {key: value for key, value in state.items() if key != "mode"}
if activity == "coaching":
payload["kitten_statuses"] = state.pop("kitten_statuses")
response = calculate_payload({"mode": "points", "activity": activity, **payload})
result = response["result"]
if activity == "coaching":
lines = [f"Куратор: {result['curator_points']} баллов."] + [f"Бельчонок {index}: {value} баллов." for index, value in enumerate(result['kitten_points'], start=1)]
elif activity == "training":
lines = [f"Бельчонок: {result['kitten_points']} баллов."]
else:
lines = [f"Баллы осмотра: {result['points']} баллов."]
state.clear()
return "\n".join(lines)
if state["mode"] == "goal":
state["confirm"] = True
return self._confirmation(state)
@@ -1286,7 +1305,7 @@ class BelkiDialog:
self._states[peer_id] = state
return self._ask_next(self._states[peer_id])
if command.lower() in ("/цель", "/калькулятор"):
self._states[peer_id] = {"mode": "goal"}
self._states[peer_id] = {"mode": "points_choice"}
return self._ask_next(self._states[peer_id])
if command.lower().startswith(("/урок ", "/тренировка ", "/осмотр ", "/осмотры ")):
try:
@@ -1323,6 +1342,19 @@ class BelkiDialog:
Возвращает сообщение-ответ для пользователя.
"""
key = next((key for key, _ in self._ORDERS[state["mode"]] if not self._has_field(state, key)), None)
if state["mode"] == "points_choice" and key == "activity":
activity = text.lower()
if activity in ("прокачка", "лу", "зу"):
state["mode"] = "points_coaching"
if activity in ("лу", "зу"):
state["skill"] = activity.upper()
elif activity in ("тренировка", "урок"):
state["mode"] = "points_training"
elif activity in ("осмотр", "осмотры"):
state["mode"] = "points_inspection"
else:
return "Выберите: прокачка, тренировка или осмотр."
return self._ask_next(state)
if key == "date":
if text.lower() in ("сегодня", "__today__"):
state[key] = datetime.now().strftime("%d.%m")
@@ -1368,6 +1400,14 @@ class BelkiDialog:
return str(exc)
state[key] = True
elif key == "independence":
if state["mode"] == "points_coaching":
statuses = [self._independence(value.strip()) for value in text.split(",") if value.strip()]
if len(statuses) != state["kitten_count"] or any(status is None for status in statuses):
return f"Укажите {state['kitten_count']} статуса через запятую: сам или несам."
state["kitten_statuses"] = statuses
state["kitten_independence"] = statuses[0]
state[key] = True
return self._ask_next(state)
kitten_count = 1 + len(state.get("extra_kittens", ()))
if state.get("skill") == "ЛУ" and kitten_count > 1:
values = [part.strip() for part in text.split(",") if part.strip()]
@@ -1488,7 +1528,7 @@ class BelkiDialog:
state[key] = int(value) if value.is_integer() else value
elif key in ("minutes_per_session", "kitten_count"):
from .domain import MAX_GOAL_KITTENS, MAX_GOAL_MINUTES_PER_SESSION
maximum = MAX_GOAL_MINUTES_PER_SESSION if key == "minutes_per_session" else MAX_GOAL_KITTENS
maximum = 3 if state["mode"] == "points_coaching" and key == "kitten_count" else (MAX_GOAL_MINUTES_PER_SESSION if key == "minutes_per_session" else MAX_GOAL_KITTENS)
if not re.fullmatch(r"\d+", text) or not 0 < int(text) <= maximum:
label = "длительность захода" if key == "minutes_per_session" else "количество котят"
return f"Укажите {label}: целое число от 1 до {maximum}."
@@ -188,6 +188,8 @@
## 9. Отдельный калькулятор заработанных баллов
**Статус:** выполнено в текущей очереди исправлений.
**Источник:** сообщение пользователя от 25.08.2026.
**Идея:** добавить ещё один самостоятельный калькулятор — для прямого расчёта количества уже заработанных баллов по параметрам выполненной прокачки. По смыслу он использует те же правила, что и генератор отчёта, но не является формой отчёта.
+1
View File
@@ -63,6 +63,7 @@
- 2026-08-25: fixed separator-free bulk parsing around time ranges, scoped web quick input to coaching, changed web inspection resources to `+N name`, corrected Russian inspection-count grammar, enabled VK image mirroring fallback, and added the standalone goal calculator mode/API.
- 2026-08-25: added the goal calculator to the VK menu as `/цель` and `/калькулятор`; the bot now runs the same goal calculation interactively with step prompts, choice buttons, and confirmation without report attachments.
- 2026-08-25: hardened the public goal calculator: point values must be finite, one session is limited to 1–1440 minutes, and one calculation to 1–50 kittens. The same validation is applied by the domain, JSON API, and VK dialogue, with regression tests for `NaN`, infinity, and excessive values.
- 2026-08-25: added the separate `points` calculator mode for earned points. It reuses the domain formulas without report identities or attachments; web and VK cover coaching, training, and inspections, with coaching results split between curator and up to three kittens.
- 2026-08-25: hardened public JSON and screenshot uploads. The web handler caps encoded JSON at 20 MiB before parsing, decodes at most 15 MiB of image bytes, accepts only PNG/JPEG/WebP signatures, rejects MIME mismatches, and strips path components from upload names. The public UI advertises the same supported formats.
- 2026-08-25: removed unused public web-profile endpoints and made `/api/resolve-identity` stateless for submitted pairs. A browser can fill its current inspection form, but cannot overwrite the persistent identity directory shared with VK users.
- 2026-08-25: persistent identity and profile pairs now require a non-empty name up to 100 characters and a positive integer ID. VK input and public identity lookup reject zero, negative, and boolean IDs before lookup or persistence.
+14
View File
@@ -44,6 +44,20 @@ class ApiTests(unittest.TestCase):
self.assertEqual(response["result"]["total_hours"], 2)
self.assertIn("Осталось добрать: 24", response["message"])
def test_points_calculator_returns_separate_coach_and_kittens(self):
response = calculate_payload({
"mode": "points", "activity": "coaching", "skill": "ЛУ", "start": "11:00", "end": "11:20",
"kitten_statuses": ["самостоятельно", "несамостоятельно"],
})
self.assertEqual(response["result"], {"minutes": 20, "curator_points": 8, "kitten_points": [4, 4]})
def test_points_calculator_supports_training_and_inspection(self):
self.assertEqual(calculate_payload({"mode": "points", "activity": "training"})["result"]["kitten_points"], 25)
self.assertEqual(calculate_payload({
"mode": "points", "activity": "inspection", "place": "дупло", "inspections": 2,
"resources": [["паук", 1]],
})["result"]["points"], 5)
def test_goal_calculator_rejects_non_finite_json_number(self):
with self.assertRaisesRegex(ApiError, "конечным числом"):
calculate_payload({
+12
View File
@@ -27,6 +27,18 @@ class VkConversationTests(unittest.TestCase):
dialog.handle(110, "10")
self.assertIn("от 1 до 1440", dialog.handle(110, "1441"))
def test_calculator_replaces_goal_with_points_dialog(self):
dialog = BelkiDialog()
self.assertIn("прокачку", dialog.handle(111, "/калькулятор").lower())
self.assertIn("навык", dialog.handle(111, "прокачка").lower())
dialog.handle(111, "ЛУ")
dialog.handle(111, "11:00")
dialog.handle(111, "11:20")
dialog.handle(111, "2")
response = dialog.handle(111, "сам, несам")
self.assertIn("Куратор: 8", response)
self.assertIn("Бельчонок 2: 4", response)
def test_step_by_step_coaching_dialog(self):
dialog = BelkiDialog()
self.assertIn("дат", dialog.handle(77, "/лу").lower())
+57 -2
View File
@@ -73,6 +73,7 @@
<button data-mode="training">Тренировка</button>
<button data-mode="inspection">Осмотры</button>
<button data-mode="goal">Калькулятор цели</button>
<button data-mode="points">Калькулятор баллов</button>
</div>
<section class="panel">
@@ -131,9 +132,25 @@
<label>Количество котят<input name="kitten_count" type="number" min="1" value="1"></label>
</div>
<div id="points" class="grid mode hidden">
<p class="wide muted">Выберите занятие и его условия — без данных отчёта. Калькулятор покажет начисленные баллы.</p>
<label>Занятие<select name="activity" id="pointsActivity"><option value="coaching">Прокачка ЛУ/ЗУ</option><option value="training">Тренировка</option><option value="inspection">Осмотр</option></select></label>
<div id="pointsCoaching" class="wide grid">
<label>Навык<select name="skill"><option>ЛУ</option><option>ЗУ</option></select></label>
<label>Начало<input name="start" type="time" value="11:00"></label><label>Конец<input name="end" type="time" value="11:20"></label>
<label>Бельчонков<select name="kitten_count"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select></label>
<label>Бельчонок 1<select name="kitten_status"><option value="самостоятельно">самостоятельный</option><option value="несамостоятельно">несамостоятельный</option></select></label>
<label class="points-extra hidden">Бельчонок 2<select name="kitten_status"><option value="самостоятельно">самостоятельный</option><option value="несамостоятельно">несамостоятельный</option></select></label>
<label class="points-extra hidden">Бельчонок 3<select name="kitten_status"><option value="самостоятельно">самостоятельный</option><option value="несамостоятельно">несамостоятельный</option></select></label>
</div>
<div id="pointsInspection" class="wide grid hidden"><label>Место<select name="place"><option>дупло</option><option>расщелина</option></select></label><label>Количество осмотров<input name="inspections" type="number" min="0" value="0"></label><label class="wide">Ресурсы, по одному на строку: +количество название<textarea name="resources" placeholder="+2 вьюнок&#10;+1 паук"></textarea></label></div>
<p id="pointsTraining" class="wide muted hidden">За тренировку бельчонок получает 25 баллов.</p>
</div>
<label id="reportAttachments" class="wide">Скриншоты отчёта<input id="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple><span class="muted">Можно выбрать несколько изображений PNG, JPEG или WebP. Они будут загружены на img.nyan404.ru.</span></label>
<div id="reportActions" class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div>
<div id="goalActions" class="actions hidden"><button class="primary" type="submit">Рассчитать цель</button><button type="button" id="goalCopy" disabled>Скопировать</button></div>
<div id="pointsActions" class="actions hidden"><button class="primary" type="submit">Рассчитать баллы</button></div>
</form>
<div id="profileSection" class="panel hidden" style="margin-top: 16px;">
<strong>Ваш профиль</strong>
@@ -158,6 +175,7 @@
</dialog>
<div class="result hidden" id="result"><h2>Сообщение</h2><textarea id="message" readonly></textarea></div>
<div class="result hidden" id="pointsResult" aria-live="polite"><h2>Заработанные баллы</h2><div id="pointsSummary"></div></div>
<p class="error" id="error"></p>
</section>
</section>
@@ -207,6 +225,10 @@
const reportAttachments = document.querySelector('#reportAttachments');
const reportActions = document.querySelector('#reportActions');
const goalActions = document.querySelector('#goalActions');
const pointsActions = document.querySelector('#pointsActions');
const pointsResult = document.querySelector('#pointsResult');
const pointsSummary = document.querySelector('#pointsSummary');
const pointsActivity = document.querySelector('#pointsActivity');
const bulkText = document.querySelector('#bulkText');
const bulkStatus = document.querySelector('#bulkStatus');
const bulk = document.querySelector('.bulk');
@@ -262,13 +284,24 @@
document.querySelectorAll('.mode').forEach(panel => panel.classList.toggle('hidden', panel.id !== mode));
document.querySelectorAll('.mode').forEach(panel => panel.querySelectorAll('input, select, textarea').forEach(field => { field.disabled = panel.id !== mode; }));
bulk.classList.toggle('hidden', mode !== 'coaching');
reportAttachments.classList.toggle('hidden', mode === 'goal');
reportActions.classList.toggle('hidden', mode === 'goal');
reportAttachments.classList.toggle('hidden', mode === 'goal' || mode === 'points');
reportActions.classList.toggle('hidden', mode === 'goal' || mode === 'points');
goalActions.classList.toggle('hidden', mode !== 'goal');
pointsActions.classList.toggle('hidden', mode !== 'points');
if (mode !== 'coaching') bulkStatus.textContent = '';
error.textContent = '';
}
document.querySelectorAll('[data-mode]').forEach(button => button.addEventListener('click', () => selectMode(button.dataset.mode)));
function updatePointsFields() {
const activity = pointsActivity.value;
document.querySelector('#pointsCoaching').classList.toggle('hidden', activity !== 'coaching');
document.querySelector('#pointsInspection').classList.toggle('hidden', activity !== 'inspection');
document.querySelector('#pointsTraining').classList.toggle('hidden', activity !== 'training');
const count = Number(document.querySelector('#points [name="kitten_count"]').value);
document.querySelectorAll('.points-extra').forEach((field, index) => field.classList.toggle('hidden', activity !== 'coaching' || index >= count - 1));
}
pointsActivity.addEventListener('change', updatePointsFields);
document.querySelector('#points [name="kitten_count"]').addEventListener('change', updatePointsFields);
document.querySelector('#coaching [name="skill"]').addEventListener('change', updateStatusRules);
document.querySelector('#coaching [name="kitten_independence"]').addEventListener('change', updateStatusRules);
// Writes a value into a named field inside a calculator panel.
@@ -335,6 +368,22 @@
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
// Serializes the active calculator form into the API payload shape.
function payload() {
if (mode === 'points') {
const activity = pointsActivity.value;
const data = {mode, activity};
if (activity === 'coaching') {
data.skill = document.querySelector('#pointsCoaching [name="skill"]').value;
data.start = document.querySelector('#pointsCoaching [name="start"]').value;
data.end = document.querySelector('#pointsCoaching [name="end"]').value;
const count = Number(document.querySelector('#points [name="kitten_count"]').value);
data.kitten_statuses = [...document.querySelectorAll('#pointsCoaching [name="kitten_status"]')].slice(0, count).map(field => field.value);
} else if (activity === 'inspection') {
data.place = document.querySelector('#pointsInspection [name="place"]').value;
data.inspections = Number(document.querySelector('#pointsInspection [name="inspections"]').value);
data.resources = [...document.querySelector('#pointsInspection [name="resources"]').value.matchAll(/^\+\s*(\d+)\s+(.+)$/gm)].map(match => [match[2].trim(), Number(match[1])]);
}
return data;
}
const data = {};
document.querySelectorAll(`#${mode} [name]`).forEach(field => { data[field.name] = field.value; });
data.mode = mode;
@@ -380,6 +429,12 @@
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
if (mode === 'points') {
const values = data.result;
const lines = values.kitten_points ? values.kitten_points.map((value, index) => `<p>Бельчонок ${index + 1}: <strong>${value}</strong> баллов</p>`) : [`<p>Баллы осмотра: <strong>${values.points}</strong></p>`];
if (values.curator_points !== undefined) lines.unshift(`<p>Куратор: <strong>${values.curator_points}</strong> баллов</p>`);
pointsSummary.innerHTML = lines.join(''); pointsResult.classList.remove('hidden'); return;
}
message.value = data.message;
result.classList.remove('hidden');
copy.disabled = mode === 'goal';