diff --git a/MEMORY.md b/MEMORY.md index 96a118a..36fae46 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -114,3 +114,7 @@ Inspection results persist the base score for the number of inspections and each # 2026-10-07: entered report state `app/belki/history.py` persists an administrative `entered` boolean with an idempotent SQLite/PostgreSQL schema migration. `/api/admin/calculations/{id}/entered` is session-protected and updates one report. `web/admin.html` defaults report history to the calendar current month, prepends an accessible checkbox/checkmark column, and dims rows after entry; sorting remains unchanged. + +# 2026-10-13: persistent cat-name changes + +`IdentityDirectory.rename_existing()` is the only write path for the user-facing rename feature. It requires an existing character ID, updates `identities` and denormalized `profiles` names in PostgreSQL/SQLite, removes the stale old-name index entry, and refreshes cached profiles. The VK dialog starts from the `Изменить имя кота` menu button and asks for ID then a new name. The web `/belki` `Имя кота` tab looks up the current name and submits `/api/rename-identity`; `/api/resolve-identity` remains stateless for report form completion. diff --git a/app/belki/api.py b/app/belki/api.py index 3cba89d..b8360f2 100644 --- a/app/belki/api.py +++ b/app/belki/api.py @@ -112,6 +112,33 @@ def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]: } +def rename_identity_payload(payload: dict[str, Any]) -> dict[str, Any]: + """Переименовывает существующую связку ID персонажа.""" + if not isinstance(payload, dict): + raise ApiError("Ожидался JSON-объект") + raw_id = payload.get("character_id") + if isinstance(raw_id, bool): + raise ApiError("ID персонажа должен быть числом") + try: + character_id = int(raw_id) + except (TypeError, ValueError) as exc: + raise ApiError("ID персонажа должен быть числом") from exc + if character_id <= 0: + raise ApiError("ID персонажа должен быть положительным") + new_name = str(payload.get("new_name", "")).strip() + if not new_name: + raise ApiError("Укажите новое имя персонажа") + directory = _identity_directory() + current = directory.resolve(character_id=character_id) + if current is None: + raise ApiError(f"Связка для ID {character_id} не найдена") + try: + old, updated = directory.rename_existing(character_id=character_id, new_name=new_name) + except (KeyError, ValueError) as exc: + raise ApiError(str(exc)) from exc + return {"status": "updated", "character_id": updated.character_id, "old_name": old.name, "name": updated.name} + + def _required(payload: dict[str, Any], key: str) -> Any: """Проверяет наличие обязательного поля в пейлоаде.""" if key not in payload: diff --git a/app/belki/identity.py b/app/belki/identity.py index de6c546..42ef1d8 100644 --- a/app/belki/identity.py +++ b/app/belki/identity.py @@ -156,6 +156,41 @@ class IdentityDirectory: self._index(identity) return identity + def rename_existing(self, *, character_id: int, new_name: str) -> tuple[Identity, Identity]: + """Переименовывает только уже существующую связку и её профили.""" + current = self.resolve(character_id=character_id) + if current is None: + raise KeyError(f"Связка для ID {character_id} не найдена") + updated = Identity(name=new_name, character_id=character_id) + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + connection.execute( + "UPDATE identities SET name = %s WHERE character_id = %s", + (updated.name, updated.character_id), + ) + connection.execute( + "UPDATE profiles SET name = %s WHERE character_id = %s", + (updated.name, updated.character_id), + ) + elif self.db_path: + with sqlite3.connect(self.db_path) as connection: + connection.execute( + "UPDATE identities SET name = ? WHERE character_id = ?", + (updated.name, updated.character_id), + ) + connection.execute( + "UPDATE profiles SET name = ? WHERE character_id = ?", + (updated.name, updated.character_id), + ) + old_key = current.name.casefold() + if self._by_name.get(old_key) == current: + self._by_name.pop(old_key, None) + self._index(updated) + for actor_id, profile in tuple(self._profiles.items()): + if profile.character_id == character_id: + self._profiles[actor_id] = updated + return current, updated + def remember_profile(self, *, actor_id: int, name: str, character_id: int) -> Identity: """ Сохраняет профиль пользователя (кто — кто). diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index 5b9b32f..f48a10f 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -955,7 +955,7 @@ class BelkiBot: value = payload.get("command") if isinstance(payload, dict) else payload return { "menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок", - "menu:inspection": "/осмотр", "menu:goal": "/цель", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка", + "menu:inspection": "/осмотр", "menu:goal": "/цель", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка", "menu:rename": "/изменить-имя", "points:coaching": "прокачка", "points:training": "тренировка", "points:inspection": "осмотр", "application:feathers": "/перо", "application:kitten": "/бельчонок", "application:flying": "/летяга", "application:curator": "/куратор", @@ -1043,6 +1043,7 @@ class BelkiDialog: "points_coaching": (("skill", "Какой навык считать: ЛУ или ЗУ?"), ("start", "Укажите время начала в формате HH:MM."), ("end", "Укажите время конца в формате HH:MM."), ("kitten_count", "Сколько бельчат участвует (от 1 до 3)?"), ("independence", "Укажите статус каждого бельчонка через запятую: сам или несам.")), "points_inspection": (("place", "Укажите место: дупло или расщелина."), ("inspections", "Сколько было осмотров?"), ("resources", "Перечислите ресурсы, например: +1 вьюнок, +3 паук — или напишите «без ресурсов».")), "points_training": (), + "rename_identity": (("character_id", "Укажите ID кота, имя которого уже есть в справочнике."), ("new_name", "Введите новое имя кота.")), } def __init__(self, identity_directory: IdentityDirectory | None = None, *, onboarding: bool = False, @@ -1230,6 +1231,7 @@ class BelkiDialog: [self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")], [self._button("Калькулятор баллов", "menu:goal", "secondary")], [self._button("Подать заявку", "menu:application", "secondary")], + [self._button("Изменить имя кота", "menu:rename", "secondary")], [self._button("Помощь", "menu:help", "secondary")], ], } @@ -1447,6 +1449,9 @@ class BelkiDialog: if command.lower() in ("/цель", "/калькулятор"): self._states[peer_id] = {"mode": "points_choice"} return self._ask_next(self._states[peer_id]) + if command.lower() in ("/изменить-имя", "/переименовать", "/имя"): + self._states[peer_id] = {"mode": "rename_identity"} + return self._ask_next(self._states[peer_id]) if command.lower().startswith(("/урок ", "/тренировка ", "/осмотр ", "/осмотры ")): try: parsed = parse_text_command(command) @@ -1474,7 +1479,7 @@ class BelkiDialog: state["character_name"] = profile.name state["character_id"] = profile.character_id - def _consume_field(self, state: dict[str, Any], text: str) -> str: + def _consume_field(self, state: dict[str, Any], text: str, *, actor_id: int | None = None) -> str: """ Заполняет следующее незаполненное поле в состоянии диалога. @@ -1482,6 +1487,24 @@ class BelkiDialog: Возвращает сообщение-ответ для пользователя. """ key = next((key for key, _ in self._ORDERS[state["mode"]] if not self._has_field(state, key)), None) + if state["mode"] == "rename_identity" and key == "character_id": + if not re.fullmatch(r"\d+", text.strip()) or int(text) <= 0: + return "ID кота должен быть положительным целым числом." + identity = self.identity_directory.resolve(character_id=int(text)) + if identity is None: + return f"Связка для ID {int(text)} не найдена. Укажите ID, который уже есть в справочнике." + state["character_id"] = int(text) + state["current_name"] = identity.name + return f"Сейчас у ID {identity.character_id} имя «{identity.name}». Введите новое имя кота." + if state["mode"] == "rename_identity" and key == "new_name": + try: + old, updated = self.identity_directory.rename_existing( + character_id=int(state["character_id"]), new_name=text, + ) + except (KeyError, ValueError) as exc: + return str(exc) + self._reset(actor_id or state.get("character_id")) + return f"Имя кота [{updated.character_id}] обновлено: «{old.name}» → «{updated.name}»." if state["mode"] == "points_choice" and key == "activity": activity = text.strip().lower() if activity in ("прокачка", "прокачку", "лу", "зу"): @@ -1765,7 +1788,7 @@ class BelkiDialog: return response return "Начните с /лу или /зу. Для списка команд отправьте /help." try: - return self._consume_field(state, text) + return self._consume_field(state, text, actor_id=actor_id) except (ApiError, ValueError) as exc: return str(exc) diff --git a/app/main.py b/app/main.py index 2838d0c..9cbc7ad 100644 --- a/app/main.py +++ b/app/main.py @@ -14,7 +14,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import parse_qs, unquote, urlparse -from .belki.api import ApiError, calculate_and_store, calculate_payload, inspect_bulk_payload, resolve_identity_payload +from .belki.api import ApiError, calculate_and_store, calculate_payload, inspect_bulk_payload, rename_identity_payload, resolve_identity_payload from .belki.history import CalculationStore from .belki.applications import ApplicationError, ApplicationStore, validate_application from .belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds @@ -531,7 +531,7 @@ class Handler(BaseHTTPRequestHandler): parsed = urlparse(self.path) is_sudoku_create = parsed.path == "/api/sudoku/games" is_sudoku_regenerate = parsed.path.startswith("/api/sudoku/games/") and parsed.path.endswith("/regenerate") - if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/reports", "/api/inspect-bulk", "/api/resolve-identity", + if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/reports", "/api/inspect-bulk", "/api/resolve-identity", "/api/rename-identity", "/api/applications", "/api/admin/vk/templates", "/api/admin/vk/schedules") and not is_sudoku_create and not is_sudoku_regenerate: self._json(404, {"error": "Не найдено"}) return @@ -589,6 +589,8 @@ class Handler(BaseHTTPRequestHandler): self._json(200, inspect_bulk_payload(payload)) elif self.path == "/api/resolve-identity": self._json(200, resolve_identity_payload(payload)) + elif self.path == "/api/rename-identity": + self._json(200, rename_identity_payload(payload)) elif self.path == "/api/applications": payload["attachments"] = validate_web_report_attachments(payload) application = validate_application(payload) diff --git a/project_mind_map.md b/project_mind_map.md index 5a3442e..531a2ff 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -19,6 +19,7 @@ mindmap calculate inspect bulk resolve identity + rename existing identity applications Upload boundary PNG JPEG WebP @@ -38,6 +39,7 @@ mindmap Reports Goal calculator Applications + Cat-name update tab web/admin.html Review and accept Report entered checkbox @@ -54,6 +56,7 @@ mindmap Step dialogs durable vk_dialog_states checkpoint Natural one-line parser + Existing cat-name rename flow Mentor and student labels Per-ward self-sufficiency labels Flexible punctuation and ID normalization diff --git a/structure_and_data.md b/structure_and_data.md index 13b4584..fa23360 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -135,6 +135,7 @@ - 2026-09-21: `InspectionResult` now keeps the base inspection score and per-resource score entries alongside the total. The `/admin` report table renders these values in a dedicated `Баллы` column; older history rows still show their stored total when detailed fields are absent. The public report message remains unchanged. - 2026-09-26: inspection scoring now has an explicit `EDIBLE_CATCHES` catalogue in `app/belki/domain.py`; `Ящерица` and `Летучая мышь` are documented as one-point catches and covered by regression tests. - 2026-10-10: VK input migrated from Long Poll to Callback API. `app/belki/vk_bot.py` now serves `/api/vk/callback` on port 8081, validates the callback secret and group ID, handles `message_new`/`message_event`, and keeps scheduler/notifier threads in the bot process. `vk_callback_events` deduplicates callback event IDs for seven days and releases failed claims for VK retry. `deploy/k8s/*` adds the `belki-bot` ClusterIP Service and callback probes; `nginx.conf` routes only the exact callback path to the bot while other `/api/` requests remain on `belki-web`. Public registration and live VK confirmation are still a deployment-stage action. +- 2026-10-13: added persistent cat-name changes. `IdentityDirectory.rename_existing()` updates the existing `identities` row, all `profiles` rows for that character, and both in-memory indexes; unknown IDs are rejected. VK exposes the separate `Изменить имя кота` menu flow, while `/belki` adds the `Имя кота` tab backed by `/api/rename-identity` after a current-name lookup through `/api/resolve-identity`. # Обновление 2026-08-16: несколько котят Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. diff --git a/tests/test_api.py b/tests/test_api.py index 3e4821c..a17de4c 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -4,7 +4,7 @@ from tempfile import TemporaryDirectory from unittest.mock import patch from app.belki import api -from app.belki.api import ApiError, calculate_payload, inspect_bulk_payload, resolve_identity_payload +from app.belki.api import ApiError, calculate_payload, inspect_bulk_payload, rename_identity_payload, resolve_identity_payload from app.belki.history import CalculationStore from app.belki.identity import IdentityDirectory @@ -131,6 +131,18 @@ class ApiTests(unittest.TestCase): with self.subTest(character_id=character_id), self.assertRaises(ApiError): resolve_identity_payload({"character_id": character_id}) + def test_identity_rename_requires_existing_mapping_and_updates_profiles(self): + with TemporaryDirectory() as directory: + identities = IdentityDirectory(db_path=f"{directory}/identities.sqlite3") + identities.remember_profile(actor_id=7, name="Серолап", character_id=1617140) + with patch.object(api, "_IDENTITY_DIRECTORY", identities): + response = rename_identity_payload({"character_id": 1617140, "new_name": "Новый Лап"}) + self.assertEqual(response["old_name"], "Серолап") + self.assertEqual(identities.resolve(character_id=1617140).name, "Новый Лап") + self.assertEqual(identities.profile(actor_id=7).name, "Новый Лап") + with self.assertRaises(ApiError): + rename_identity_payload({"character_id": 999999, "new_name": "Кто-то"}) + def test_calculation_store_persists_full_record(self): with TemporaryDirectory() as directory: path = f"{directory}/history.sqlite3" diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index 0ed0d05..6d755cb 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -458,6 +458,16 @@ class VkConversationTests(unittest.TestCase): dialog.handle(901, "1") self.assertIn("Куратор: 4", dialog.handle(901, "сам")) + def test_identity_rename_has_menu_button_and_updates_existing_mapping(self): + identities = IdentityDirectory([Identity("Серолап", 1617140)]) + dialog = BelkiDialog(identities) + labels = [button["action"]["label"] for row in dialog.keyboard_for(902)["buttons"] for button in row] + self.assertIn("Изменить имя кота", labels) + self.assertIn("Укажите ID кота", dialog.handle(902, "/изменить-имя")) + self.assertIn("Серолап", dialog.handle(902, "1617140")) + self.assertIn("Серолап", dialog.handle(902, "Новый Лап")) + self.assertEqual(identities.resolve(character_id=1617140).name, "Новый Лап") + if __name__ == "__main__": unittest.main() diff --git a/web/calculator.html b/web/calculator.html index e311e0a..65ff744 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -103,6 +103,7 @@
@@ -248,6 +249,26 @@
+ @@ -527,6 +548,7 @@ const reportsSection = document.querySelector('#reportsSection'); const applicationsSection = document.querySelector('#applicationsSection'); + const identitySection = document.querySelector('#identitySection'); const sectionTabs = [...document.querySelectorAll('[data-section]')]; const applicationForm = document.querySelector('#applicationForm'); const applicationError = document.querySelector('#applicationError'); @@ -534,26 +556,76 @@ const applicationSubmit = document.querySelector('#applicationSubmit'); const applicationFeathers = document.querySelector('#applicationFeathers'); let applicationType = 'feather_donation'; + const renameIdentityForm = document.querySelector('#renameIdentityForm'); + const renameIdentityId = document.querySelector('#renameIdentityId'); + const renameIdentityCurrentName = document.querySelector('#renameIdentityCurrentName'); + const renameIdentityNewName = document.querySelector('#renameIdentityNewName'); + const lookupIdentity = document.querySelector('#lookupIdentity'); + const renameIdentitySubmit = document.querySelector('#renameIdentitySubmit'); + const renameIdentityLookupStatus = document.querySelector('#renameIdentityLookupStatus'); + const renameIdentityError = document.querySelector('#renameIdentityError'); + const renameIdentitySuccess = document.querySelector('#renameIdentitySuccess'); - // Changes between reports and applications while optionally updating the URL. + // Changes between reports, applications, and identity management while optionally updating the URL. function setSection(nextSection, updateUrl = true) { - const isApplications = nextSection === 'applications'; - reportsSection.classList.toggle('hidden', isApplications); - applicationsSection.classList.toggle('hidden', !isApplications); + const selectedSection = ['reports', 'applications', 'identity'].includes(nextSection) ? nextSection : 'reports'; + reportsSection.classList.toggle('hidden', selectedSection !== 'reports'); + applicationsSection.classList.toggle('hidden', selectedSection !== 'applications'); + identitySection.classList.toggle('hidden', selectedSection !== 'identity'); sectionTabs.forEach(tab => { - const selected = tab.dataset.section === nextSection; + const selected = tab.dataset.section === selectedSection; tab.classList.toggle('active', selected); tab.setAttribute('aria-selected', String(selected)); }); if (updateUrl) { const url = new URL(window.location.href); - if (isApplications) url.searchParams.set('section', 'applications'); + if (selectedSection !== 'reports') url.searchParams.set('section', selectedSection); else url.searchParams.delete('section'); window.history.pushState({}, '', url); } } sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section))); - window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section') === 'applications' ? 'applications' : 'reports', false)); + window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section'), false)); + + async function lookupRenameIdentity() { + renameIdentityError.textContent = ''; + renameIdentitySuccess.classList.add('hidden'); + renameIdentityLookupStatus.textContent = ''; + const characterId = renameIdentityId.value.trim(); + if (!characterId) { renameIdentityError.textContent = 'Укажите ID кота.'; return false; } + lookupIdentity.disabled = true; + lookupIdentity.textContent = 'Проверяем…'; + try { + const response = await fetch('/api/resolve-identity', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({character_id: characterId})}); + const data = await response.json(); + if (!response.ok || data.status !== 'found') throw new Error(data.error || data.message || 'Связка с таким ID не найдена.'); + renameIdentityCurrentName.value = data.name; + renameIdentityId.value = data.character_id; + renameIdentityLookupStatus.textContent = `Текущее имя: «${data.name}».`; + return true; + } catch (err) { renameIdentityCurrentName.value = ''; renameIdentityError.textContent = err.message; return false; } + finally { lookupIdentity.disabled = false; lookupIdentity.textContent = 'Проверить ID'; } + } + lookupIdentity.addEventListener('click', lookupRenameIdentity); + renameIdentityForm.addEventListener('submit', async event => { + event.preventDefault(); + renameIdentityError.textContent = ''; + renameIdentitySuccess.classList.add('hidden'); + if (!renameIdentityCurrentName.value && !(await lookupRenameIdentity())) return; + renameIdentitySubmit.disabled = true; + renameIdentitySubmit.textContent = 'Сохраняем…'; + try { + const response = await fetch('/api/rename-identity', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({character_id: renameIdentityId.value, new_name: renameIdentityNewName.value.trim()})}); + const data = await response.json(); + if (!response.ok) throw new Error(data.error || 'Не удалось изменить имя.'); + renameIdentityCurrentName.value = data.name; + renameIdentityNewName.value = ''; + renameIdentityLookupStatus.textContent = `Текущее имя: «${data.name}».`; + renameIdentitySuccess.textContent = `Имя обновлено: «${data.old_name}» → «${data.name}».`; + renameIdentitySuccess.classList.remove('hidden'); + } catch (err) { renameIdentityError.textContent = err.message; } + finally { renameIdentitySubmit.disabled = false; renameIdentitySubmit.textContent = 'Сохранить новое имя'; } + }); // Adds and initializes one feather row in the application form. function addApplicationFeather(values = {}) { @@ -636,7 +708,7 @@ addApplicationFeather(); syncApplicationForm(); selectMode(mode); - setSection(new URLSearchParams(window.location.search).get('section') === 'applications' ? 'applications' : 'reports', false); + setSection(new URLSearchParams(window.location.search).get('section'), false);