Skip to content

Commit

Permalink
Merge pull request #110 from bomzheg/feature/#71
Browse files Browse the repository at this point in the history
feature/#71
  • Loading branch information
bomzheg authored Oct 8, 2024
2 parents 965632d + 97056e7 commit 58623ce
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 29 deletions.
2 changes: 1 addition & 1 deletion shvatka/common/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def create_telegraph(self, bot_config: BotConfig) -> Telegraph:


REQUIRED_GAME_RECIPES = [
loader(HintsList, lambda x: HintsList(x), Chain.LAST),
loader(HintsList, lambda x: HintsList.parse(x), Chain.LAST),
ABCProxy(HintsList, list[TimeHint]), # internal class, can be broken in next version adaptix
dumper(set, lambda x: tuple(x)),
]
Expand Down
27 changes: 21 additions & 6 deletions shvatka/core/models/dto/scn/level.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,21 @@ def normalize(hints: list[TimeHint]) -> list[TimeHint]:

@staticmethod
def verify(hints: Iterable[TimeHint]) -> None:
current_time = -1
times: set[int] = set()
for hint in hints:
if hint.time in times:
raise exceptions.LevelError(
text=f"Contains multiple times hints for time {hint.time}"
)
if hint.time <= current_time:
raise exceptions.LevelError(text="hints are not sorted")
current_time = hint.time
times.add(hint.time)
if not hint.hint:
raise exceptions.LevelError(text=f"There is no hint for time {hint.time}")
if 0 not in times:
raise exceptions.LevelError(text="There is no hint for 0 min")

def get_hint_by_time(self, time: timedelta) -> EnumeratedTimeHint:
hint = self.hints[0]
Expand All @@ -72,6 +78,20 @@ def get_hints_for_timedelta(self, delta: timedelta) -> list[TimeHint]:
return [th for th in self.hints if th.time <= minutes]

def replace(self, old: TimeHint, new: TimeHint) -> "HintsList":
old_index = self._index(old)
result = self.hints[0:old_index] + self.hints[old_index + 1 :] + [new]
return self.__class__(self.normalize(result))

def delete(self, old: TimeHint) -> "HintsList":
old_index = self._index(old)
result = self.hints[0:old_index] + self.hints[old_index + 1 :]
return self.__class__(self.normalize(result))

@property
def hints_count(self) -> int:
return sum(time_hint.hints_count for time_hint in self.hints)

def _index(self, old: TimeHint) -> int:
for i, hint in enumerate(self.hints):
if hint.time == old.time:
old_index = i
Expand All @@ -82,12 +102,7 @@ def replace(self, old: TimeHint, new: TimeHint) -> "HintsList":
raise exceptions.LevelError(
text=f"can't replace, there is no hints for time {old.time}"
)
result = self.hints[0:old_index] + self.hints[old_index + 1 :] + [new]
return self.__class__(self.normalize(result))

@property
def hints_count(self) -> int:
return sum(time_hint.hints_count for time_hint in self.hints)
return old_index

@overload
def __getitem__(self, index: int) -> TimeHint:
Expand Down
6 changes: 5 additions & 1 deletion shvatka/core/models/dto/scn/time_hint.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@ def hints_count(self) -> int:
return len(self.hint)

def update_time(self, new_time: int) -> None:
if self.time == new_time:
return
if not self.can_update_time():
raise exceptions.LevelError(text="Невозможно отредактировать загадку уровня")
raise exceptions.LevelError(
text="Невозможно отредактировать время выхода загадку уровня"
)
if new_time == 0:
raise exceptions.LevelError(text="Нельзя заменить таким способом загадку уровня")
self.time = new_time
Expand Down
4 changes: 2 additions & 2 deletions shvatka/infrastructure/db/models/level.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import typing
from typing import Any

from adaptix import Retort, dumper
from adaptix import Retort
from sqlalchemy import Integer, Text, ForeignKey, JSON, TypeDecorator, UniqueConstraint
from sqlalchemy.engine import Dialect
from sqlalchemy.orm import relationship, mapped_column, Mapped
Expand All @@ -20,7 +20,7 @@ class ScenarioField(TypeDecorator):
impl = JSON
cache_ok = True
retort = Retort(
recipe=[*REQUIRED_GAME_RECIPES, dumper(set, lambda x: list(x))],
recipe=REQUIRED_GAME_RECIPES,
)

def coerce_compared_value(self, op: Any, value: Any):
Expand Down
4 changes: 2 additions & 2 deletions shvatka/tgbot/dialogs/level_scn/dialogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@
Button(Const("💰Бонусные ключи"), id="bonus_keys", on_click=start_bonus_keys),
Button(Const("💡Подсказки"), id="hints", on_click=start_hints),
Button(
Const("Готово, сохранить"),
Const("💾Готово, сохранить"),
id="save",
on_click=save_level,
when=F["dialog_data"]["keys"] & F["dialog_data"]["time_hints"],
Expand Down Expand Up @@ -200,7 +200,7 @@
),
Button(Const("➕Добавить подсказку"), id="add_time_hint", on_click=start_add_time_hint),
Button(
Const("👌Достаточно подсказок"),
Const("✅Готово"),
id="save",
on_click=save_hints,
when=F["dialog_data"]["time_hints"].len() > 1,
Expand Down
9 changes: 6 additions & 3 deletions shvatka/tgbot/dialogs/level_scn/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,12 @@ async def process_time_hint_result(start_data: Data, result: Any, manager: Dialo
return
retort: Retort = manager.middleware_data["retort"]
hints_list = retort.load(manager.dialog_data.get("time_hints", []), scn.HintsList)
edited_list = hints_list.replace(
retort.load(old_hint, scn.TimeHint), retort.load(edited_hint, scn.TimeHint)
)
if edited_hint.get("__deleted__") == "__deleted_true__":
edited_list = hints_list.delete(retort.load(old_hint, scn.TimeHint))
else:
edited_list = hints_list.replace(
retort.load(old_hint, scn.TimeHint), retort.load(edited_hint, scn.TimeHint)
)
manager.dialog_data["time_hints"] = retort.dump(edited_list)


Expand Down
22 changes: 15 additions & 7 deletions shvatka/tgbot/dialogs/time_hint/dialogs.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from aiogram import F
from aiogram_dialog import Dialog, Window
from aiogram_dialog.widgets.input import MessageInput
from aiogram_dialog.widgets.kbd import (
Expand Down Expand Up @@ -25,6 +26,7 @@
edit_single_hint,
save_edited_time_hint,
delete_single_hint,
delete_whole_time_hint,
)
from shvatka.tgbot.dialogs.preview_data import TIMES_PRESET, PreviewSwitchTo

Expand Down Expand Up @@ -63,12 +65,12 @@
),
MessageInput(func=process_hint),
Button(
Const("К следующей подсказке"),
Const("К следующей подсказке"),
id="to_next_hint",
when=lambda data, *args: data["has_hints"],
when=F["has_hints"],
on_click=on_finish,
),
Back(text=Const("Изменить время")),
Back(text=Const("⏱️Изменить время")),
getter=get_hints,
state=states.TimeHintSG.hint,
preview_data={"has_hints": True},
Expand All @@ -81,7 +83,7 @@
Window(
Jinja("Подсказка выходящая в {{time}}:" "{{hints | hints}}"),
SwitchTo(
Const("Изменить время"),
Const("⏱️Изменить время"),
id="change_time",
state=states.TimeHintEditSG.time,
),
Expand All @@ -105,13 +107,19 @@
width=2,
height=10,
),
SwitchTo(Const("Добавить"), state=states.TimeHintEditSG.add_part, id="to_add_part"),
SwitchTo(Const("📝Добавить"), state=states.TimeHintEditSG.add_part, id="to_add_part"),
Button(
text=Const("Сохранить изменения"),
text=Const("🗑Удалить подсказку целиком"),
id="delete_time_hint",
on_click=delete_whole_time_hint,
when=~F["time"].is_(0),
),
Button(
text=Const("✅Сохранить"),
id="save_time_hint",
on_click=save_edited_time_hint,
),
Cancel(text=Const("Вернуться, ничего не менять")),
Cancel(text=Const("🔙Вернуться, ничего не менять")),
getter=get_hints,
state=states.TimeHintEditSG.details,
),
Expand Down
11 changes: 5 additions & 6 deletions shvatka/tgbot/dialogs/time_hint/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ async def process_time_message(m: Message, dialog_: Any, manager: DialogManager)
except ValueError:
await m.answer("Некорректный формат времени. Пожалуйста введите время в формате ЧЧ:ММ")
return
try:
await set_time(time_, manager)
except ValueError:
await m.answer("Время выхода данной подсказки должно быть больше, чем предыдущей")
await set_time(time_, manager)


async def edit_single_hint(c: CallbackQuery, widget: Any, manager: DialogManager):
Expand All @@ -73,6 +70,10 @@ async def delete_single_hint(c: CallbackQuery, widget: Any, manager: DialogManag
manager.dialog_data["hints"] = retort.dump(hints, list[AnyHint])


async def delete_whole_time_hint(c: CallbackQuery, widget: Any, manager: DialogManager):
await manager.done({"edited_time_hint": {"__deleted__": "__deleted_true__"}})


async def save_edited_time_hint(c: CallbackQuery, widget: Any, manager: DialogManager):
dishka: AsyncContainer = manager.middleware_data[CONTAINER_NAME]
retort = await dishka.get(Retort)
Expand All @@ -88,8 +89,6 @@ async def save_edited_time_hint(c: CallbackQuery, widget: Any, manager: DialogMa


async def set_time(time_minutes: int, manager: DialogManager):
if time_minutes <= int(manager.start_data["previous_time"]):
raise ValueError("Время меньше предыдущего")
data = manager.dialog_data
if not isinstance(data, dict):
data = {}
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/bot_full/test_level_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ async def test_write_level(
message_manager.reset_history()
callback_id = await author_client.click(
new_message,
InlineButtonTextLocator(".*Достаточно подсказок"),
InlineButtonTextLocator(".*Готово"),
)
message_manager.assert_answered(callback_id)
msg = message_manager.one_message()
Expand Down

0 comments on commit 58623ce

Please sign in to comment.