import logging from aiogram import Router, F from aiogram.types import Message, CallbackQuery from aiogram.fsm.context import FSMContext from sqlalchemy.ext.asyncio import AsyncSession from dto.control import EditProductContext from misc.filters import IsVerified from misc.kb.admins import back_to_product_kb from misc.states import AdminControlStorage from misc.texts import product_editing_mapping from repositories.products import ProductRepository logger = logging.getLogger(__name__) router = Router() @router.callback_query(IsVerified(), F.data.startswith("edit_product:")) async def edit_product(cb: CallbackQuery, state: FSMContext): await state.clear() data = cb.data.split(":") product_id = data[1] mode = data[2] if cb.message.photo: await cb.message.delete() msg = await cb.message.answer( f"✍️ Введите {product_editing_mapping.get(mode)}", reply_markup=back_to_product_kb( product_id, cb_factory=lambda p: f"product:{p}" ), ) else: msg = cb.message await cb.message.edit_text( f"✍️ Введите {product_editing_mapping.get(mode)}", reply_markup=back_to_product_kb( product_id, cb_factory=lambda p: f"product:{p}" ), ) ctx = EditProductContext(int(product_id), mode, msg) await state.set_state(AdminControlStorage.edit_product) await state.set_data({"ctx": ctx}) @router.message(AdminControlStorage.edit_product) async def edit_product_query( msg: Message, state: FSMContext, session: AsyncSession, products_repo: ProductRepository, ): data = await state.get_data() await state.clear() await msg.delete() ctx: EditProductContext = data.get("ctx", EditProductContext) kb = back_to_product_kb(ctx.product_id, cb_factory=lambda p: f"product:{p}") try: await ctx.msg.edit_text("⏳") if ctx.mode == "name": await products_repo.update_product_name_by_id( session, ctx.product_id, msg.text ) elif ctx.mode == "description": await products_repo.update_product_description_by_id( session, ctx.product_id, msg.text ) elif ctx.mode == "price": if msg.text.isdigit(): await products_repo.update_product_price_by_id( session, ctx.product_id, int(msg.text) ) else: await ctx.msg.edit_text( "❌ Вы ввели не число, попробуйте ещё раз...", reply_markup=kb, ) await state.set_state(AdminControlStorage.edit_product) await state.set_data({"ctx": ctx}) return else: await ctx.msg.edit_text("🍃", reply_markup=kb) return await ctx.msg.edit_text("✅ Изменения применены.", reply_markup=kb) except Exception as e: logger.exception(e) await ctx.msg.edit_text(text="‼️ Что-то пошло не так.", reply_markup=kb)