ShopBot/handlers/callback/cart.py

76 lines
2.5 KiB
Python
Raw Permalink Normal View History

2022-06-04 22:02:51 +03:00
import io
2022-06-05 15:02:41 +03:00
from aiogram import types
2022-06-04 22:02:51 +03:00
from load import dp, messages
from utils.database.cart import add_to_cart, get_user_cart, del_from_cart
from utils.database.market import Catalog
from keyboard.inline.cart import cart_list
from keyboard.default.main_menu import back_to_main_menu
2022-06-05 15:02:41 +03:00
@dp.callback_query_handler(lambda c: c.data.split("|")[0] == "add_to_cart")
2022-06-04 22:02:51 +03:00
async def add_cart(callback: types.CallbackQuery):
2022-06-05 15:02:41 +03:00
item = int(callback.data.split("|")[1])
item_id = Catalog.get_catalog()[item]["id"]
2022-06-04 22:02:51 +03:00
add_to_cart(callback.from_user.id, item_id)
await callback.answer("Товар добавлен!")
2022-06-05 15:02:41 +03:00
@dp.callback_query_handler(lambda c: c.data.split("|")[0] == "del_from_cart")
2022-06-04 22:02:51 +03:00
async def del_cart(callback: types.CallbackQuery):
c = callback.data.split("|")[1]
item_id = get_user_cart(callback.from_user.id)[int(c)][0]
del_from_cart(callback.from_user.id, item_id)
items = get_user_cart(callback.from_user.id)
if items:
2022-06-05 15:02:41 +03:00
index, count = items[0]
2022-06-04 22:02:51 +03:00
item = Catalog.get_catalog(index)
await callback.message.edit_media(
media=types.InputMediaPhoto(
media=io.BytesIO(item["image"]),
caption=messages.cart_message.format(
name=item["name"],
description=item["description"],
count=count,
2022-06-05 15:02:41 +03:00
price=item['price'] * count
2022-06-04 22:02:51 +03:00
),
parse_mode="Markdown",
),
2022-06-05 15:02:41 +03:00
reply_markup=cart_list(items=len(items) - 1)
2022-06-04 22:02:51 +03:00
)
else:
await callback.message.delete()
await dp.bot.send_message(
callback.message.chat.id,
messages.cart + " пустая!",
reply_markup=back_to_main_menu
)
await callback.answer("Товар удалён!")
@dp.callback_query_handler(lambda c: c.data.split("|")[0] in ["cart_prev", "cart_next"])
async def next_item(callback: types.CallbackQuery):
data = callback.data.split("|")
c = int(data[1])
items = get_user_cart(callback.from_user.id)
index, count = items[c]
item = Catalog.get_catalog(index)
await callback.message.edit_media(
media=types.InputMediaPhoto(
media=io.BytesIO(item["image"]),
caption=messages.cart_message.format(
name=item["name"],
description=item["description"],
count=count,
2022-06-05 15:02:41 +03:00
price=item['price'] * count
2022-06-04 22:02:51 +03:00
),
parse_mode="Markdown",
),
2022-06-05 15:02:41 +03:00
reply_markup=cart_list(c, len(items) - 1)
2022-06-04 22:02:51 +03:00
)