Files
shveitechbot/handlers/client/catalogue.py

101 lines
3.0 KiB
Python

from aiogram import Router, F
from aiogram.types import CallbackQuery
from aiogram.fsm.context import FSMContext
from sqlalchemy.ext.asyncio import AsyncSession
from config import PAGE_SIZE
from misc.kb import render_category
from misc.kb.client import (
get_back_to_catalogue,
render_products,
)
from repositories.categories import CategoriesRepository
from repositories.products import ProductRepository
router = Router()
@router.callback_query(F.data.startswith("cat:"))
async def subcatalogue(
cb: CallbackQuery,
state: FSMContext,
session: AsyncSession,
categories_repo: CategoriesRepository,
products_repo: ProductRepository,
):
await state.clear()
cat_id = cb.data.split(":")[1]
if cat_id == "root":
children = await categories_repo.get_categories_by_parent_id(session)
kb = render_category(
children, show_menu=True, category_cb_factory=lambda c: f"cat:{c.id}"
)
await cb.message.edit_text(
"category selection",
reply_markup=kb,
)
return
cat_id = int(cat_id)
children = await categories_repo.get_categories_by_parent_id(session, cat_id)
category = await categories_repo.get_category_by_id(session, cat_id)
parent_id = category.parent_id or "root"
if not children:
products = await products_repo.get_product_by_category(
session, cat_id, limit=PAGE_SIZE + 1, offset=0
)
products_len = len(products)
if not products:
await cb.message.edit_text(
"🍃 Здесь ничего нет...",
reply_markup=get_back_to_catalogue(parent_id),
)
return
if cb.message.photo:
await cb.message.delete()
await cb.message.answer(
"hya",
reply_markup=render_products(
products[:PAGE_SIZE],
product_cb_factory=lambda p: f"product:{p.id}",
back_cb=f"cat:{parent_id}",
next_cb=(
f"products:{cat_id}:{0 + 1}"
if products_len > PAGE_SIZE
else None
),
columns=2,
),
)
return
await cb.message.edit_text(
"hya",
reply_markup=render_products(
products[:PAGE_SIZE],
product_cb_factory=lambda p: f"product:{p.id}",
back_cb=f"cat:{parent_id}",
prev_cb=f"products:{cat_id}:{0 - 1}" if products_len < 0 else None,
next_cb=(
f"products:{cat_id}:{0 + 1}" if products_len > PAGE_SIZE else None
),
columns=2,
),
)
return
kb = render_category(
children, parent_id, category_cb_factory=lambda c: f"cat:{c.id}"
)
await cb.message.edit_text(
"category selection",
reply_markup=kb,
)