feat: add cat identity rename flow
This commit is contained in:
1 parent
a15c22b4a2
commit
546fa37fce
10 files changed
+203
-14
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
"""
|
||||
Сохраняет профиль пользователя (кто — кто).
|
||||
|
||||
+26
-3
@@ -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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user