def order_clear(call): cart = Cart.get_or_create_cart(call.from_user.id) Cart.clear_cart(cart) bot.answer_callback_query(call.id, show_alert=True, text="💔 Корзина очищена") bot.send_message(call.from_user.id, START_PAGE, reply_markup=root_kb_mk)
def generate_data(): Category.drop_collection() Cart.drop_collection() CartProduct.drop_collection() Product.drop_collection() recursive_categories_creation(categories_json) cat_id_dict = {} [cat_id_dict.update({cat_name: get_cat_id(cat_name)}) for cat_name in categories_description_dict] for product in products_dict.values(): product['category'] = cat_id_dict[product['category']] Product.objects.create(**product)
def change_qty_prod(call): product_ = Product.objects.get(id=call.data.split('_')[1]) cart = Cart.get_or_create_cart(user_id=call.from_user.id) cart.delete_product_from_cart(product=product_) bot.edit_message_text(text='Товар удален с корзины', chat_id=call.from_user.id, message_id=call.message.message_id)
def order_confirm(call): cart = Cart.get_or_create_cart(user_id=call.from_user.id) order_info = '' if len(cart.get_cart_products()) == 0: bot.send_message(call.from_user.id, text='Вы еще не добавили товары в корзину', reply_markup='') else: products = { str(cart_product.product.id): cart_product.product for cart_product in cart.get_cart_products() } sum_total = 0 for id_pro, cart_pro in products.items(): sum_total += cart.get_count_product( product=cart_pro.id) * cart_pro.get_price() header = f'ООО "Рога и Копыта"\n г.Киев' user_info = f'Покупатель: {cart.user.username}' if cart.user.phone_number is None else \ f'Покупатель: {cart.user.username}\nТел. {cart.user.phone_number}' delimiter = '-' * 40 order_info = f'{header}\n{delimiter}\nСумма заказа: {sum_total}\n' \ f'НДС 20%: {round(sum_total/6,2)}\n{delimiter}\n{user_info}' bot.send_message(call.from_user.id, order_info, reply_markup='') orders_menu = ReplyKeyboardMarkup(row_width=2) orders_menu.add( KeyboardButton(text='🗺️ Самовывоз - ближайший магазин', request_location=True), KeyboardButton(text='☎ Адресная доставка', request_contact=True), KeyboardButton(text=START_KB['start'])) bot.send_message(call.from_user.id, text=f'Выберите способ получения заказа', reply_markup=orders_menu)
def send_cart(self, user_id): cart = Cart.get_or_create_cart(user_id) products = cart.get_cart_products() price = 0 for product in products: kb = types.InlineKeyboardMarkup() price += product.price button = types.InlineKeyboardButton( text=f"Видалити {product.title} з кошика", callback_data="delete" + str(product.id)) kb.add(button) self.send_photo( user_id, photo=product.image, caption= f"{product.title} - {product.price} грн\n{product.description}", reply_markup=kb) if products: kb = types.InlineKeyboardMarkup() button = types.InlineKeyboardButton(text="Оформити замовлення", callback_data="order" + str(user_id)) kb.add(button) self.send_message( user_id, f"{len(products)} {self._get_right_case(len(products))} загальною вартістю {price} грн", reply_markup=kb) else: self.send_message(user_id, "Кошик порожій")
def checkout_step_4(self, user_id, response_email): User.update_user(user_id, email=response_email) User.set_step_checkout(user_id, 4) Cart.archive_cart(user_id) # For Test user = User.get_user(user_id) mes = (f'Вот что ты ввел \n' f'Name: {user.username} \n' f'Phone: {user.phone_number} \n' f'email: {user.email} \n') self.send_message(user_id, 'Заказ оформлен. С вами свяжется наш Менеджер') self.send_message(user_id, mes)
def add_to_card(call): print('Add to Card') prod_id = call.data.split('_')[1] user_id = call.from_user.id cart = Cart.get_cart(str(user_id)) cart.add_product_to_cart(product_id=prod_id) bot.answer_callback_query(call.id, "Добавлено в корзину", show_alert=True)
def del_product_from_cart(self, prod_id, message_id, user_id): user = User.get_user(user_id) cart = Cart.get_cart(user_id) cart.delete_product_from_cart(prod_id) self.answer_callback_query(message_id, "Товар удален", show_alert=True) self.send_message(user_id, 'Ваша корзина') self.show_cart(user_id)
def make_order(call): cart = Cart.get_or_create_cart(user_id=call.from_user.id) products = cart.get_cart_products() if products: bot.send_message(call.message.chat.id, f"Дякуюємо, {call.from_user.first_name}! Менеджер зв'яжеться з вами для підтвердження доставки.") bot.send_message(chat_id=438422378, text=f"{call.from_user.first_name} {call.from_user.last_name} зробив замовлення:") for product in products: bot.send_message(chat_id=438422378, text=product.title) cart.archive_product(product) else: bot.send_message(call.message.chat.id, "Кошик порожній!")
def user_contact(message): phone_usr = message.contact.phone_number User.upsert_user(telegram_id=message.from_user.id, phone_number=phone_usr) cart = Cart.get_cart(message.from_user.id) cart.confirmed_cart(is_archived=True, type_delivery='Адресная доставка', confirmed_date=datetime.datetime.now()) bot.send_message( message.from_user.id, text= f"В ближайшее время с Вами свяжется наш менеджер для принятия заказа", reply_markup=root_kb_mk)
def get_cart_by_user(user, archived_id=None): if archived_id: # query_res = Cart.objects(user=user, id=archived_id, is_archived=True) query_res = session.query(Cart).filter_by(user=user.telegram_id, id=archived_id, is_archived=True) return query_res.first() if query_res else None # query_res = Cart.objects(user=user, is_archived=False) query_res = session.query(Cart).filter_by(user=user.telegram_id, is_archived=False).first() # return query_res.first() if query_res else Cart.objects.create(user=user) if query_res: return query_res else: session.add(Cart(user=user.telegram_id)) session.commit() return session.query(Cart).filter_by(user=user.telegram_id, is_archived=False).first()
def get_cart(message): cart = Cart.get_or_create_cart(user_id=message.from_user.id) if len(cart.get_cart_products()) == 0: bot.send_message(message.from_user.id, text='Вы еще не добавили товары в корзину', reply_markup='') else: products = { str(cart_product.product.id): cart_product.product for cart_product in cart.get_cart_products() } sum_total = 0 for id_pro, cart_pro in products.items(): sum_total += cart.get_count_product( product=cart_pro.id) * cart_pro.get_price() product_desc = f"{cart_pro.title}\n" \ f"Кол-во {cart.get_count_product(product=cart_pro.id)} Цена: {cart_pro.get_price()}\n" \ f"Сумма: {cart.get_count_product(product=cart_pro.id)*cart_pro.get_price()}\n" kb = InlineKeyboardMarkup() kb.add( InlineKeyboardButton(text=u'🔻 убрать', callback_data='cartdecrease_' + str(id_pro)), InlineKeyboardButton( text=cart.get_count_product(product=id_pro), callback_data='---'), InlineKeyboardButton(text=u'🔺 добавить', callback_data='cartincrease_' + str(id_pro)), InlineKeyboardButton(text=u'❌ ❗ удалить товар', callback_data='cartdelete_' + str(id_pro))) bot.send_message(message.from_user.id, product_desc, reply_markup=kb) kb1 = InlineKeyboardMarkup(row_width=2) kb1.add( InlineKeyboardButton(text='🆑 Очистить корзину', callback_data='clear_car'), InlineKeyboardButton(text='💚 Оформить заказ', callback_data='confirm_order'), ) bot.send_message(message.from_user.id, text='Желаете оформить заказ?', reply_markup=kb1)
def show_archive_cart(self, user_id, id_cart): cart = Cart.get_archive_cart_by_id(user_id, id_cart) cart_product = cart.get_cart_products() item_f = cart_product.item_frequencies('product') for p_id, s in item_f.items(): pr = Product.get_product(id=p_id) text = ( f'{pr.title} \n{pr.description} \n{pr.category.title} \nCount: {s}' ) self.send_message(user_id, text)
def show_cart(self, user_id, del_product_loockup='del'): user = User.get_user(user_id) cart = Cart.get_cart(user_id) cart_product = cart.get_cart_products() item_f = cart_product.item_frequencies('product') kb2 = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) b2 = [types.KeyboardButton('Оформить заказ')] kb2.add(*b2) if item_f: for p_id, s in item_f.items(): pr = Product.get_product(id=p_id) text = ( f'{pr.title} \n{pr.description} \n{pr.category.title} \nCount: {s}' ) kb = types.InlineKeyboardMarkup(row_width=1) buttons = [ types.InlineKeyboardButton( text='Удалить товар с корзины', callback_data=f'{del_product_loockup}_{pr.id}') ] kb.add(*buttons) self.send_message(user_id, text, reply_markup=kb) self.send_message( user_id, 'Чтобы купить нажмите на кнопку "Оформить заказ"', reply_markup=kb2) else: self.send_message(user_id, 'Ваша корзина пуста')
def story_order(self, user_id, story_order_lookup='story'): cart = Cart.get_archive_cart(user_id) if cart: kb = types.InlineKeyboardMarkup() buttons = [ types.InlineKeyboardButton( text=f'Корзина {i}', callback_data=f'{story_order_lookup}_{str(c.id)}') for i, c in enumerate(cart) ] kb.add(*buttons) self.send_message(user_id, 'Ваша история заказов', reply_markup=kb) else: self.send_message(user_id, 'Ваша история заказов Пуста')
def categories(message): cart = Cart.get_orders(telegram_id=str(message.from_user.id)) for order in cart: products = { str(cart_product.product.id): cart_product.product for cart_product in order.get_cart_products() } sum_total = 0 for id_pro, cart_pro in products.items(): sum_total += order.get_count_product( product=cart_pro.id) * cart_pro.get_price() header = f'ООО "Рога и Копыта"\n г.Киев' date_order = order['confirmed_date'].strftime("%m/%d/%Y, %H:%M:%S") type_deliv = order['type_delivery'] user_info = f'Покупатель: {order.user.username}' if order.user.phone_number is None else \ f'Покупатель: {order.user.username}\nТел. {order.user.phone_number}' delimiter = '-' * 40 order_info = f'{header}\nДата: {date_order}\n{delimiter}\nСумма заказа: {sum_total}\nНДС 20%: {round(sum_total/6,2)}' \ f'\n{delimiter}\n{user_info}\nТип поставки: {type_deliv}' bot.send_message(message.chat.id, order_info, reply_markup='')
def user_location(message): lon = message.location.longitude lat = message.location.latitude distance = [] for m in MAGAZINS: rezult = geodesic((m['latm'], m['lonm']), (lat, lon)).kilometers distance.append(rezult) index = distance.index(min(distance)) bot.send_message(message.chat.id, text='Ближайший к Вам магазин') bot.send_venue(message.chat.id, MAGAZINS[index]['latm'], MAGAZINS[index]['lonm'], MAGAZINS[index]['title'], MAGAZINS[index]['adress']) cart = Cart.get_cart(message.from_user.id) cart.confirmed_cart(is_archived=True, type_delivery='Самовывоз', confirmed_date=datetime.datetime.now()) bot.send_message( message.from_user.id, text= f"Ждем Вас в нашем магазине по адресу:\n{MAGAZINS[index]['adress']}", reply_markup=root_kb_mk)
def start(message): User.create_user(str(message.chat.id)) Cart.get_or_create_cart(str(message.chat.id)) bot.send_start(message.chat.id)
def add_to_cart(call): cart = Cart.get_or_create_cart(user_id=call.message.chat.id) cart.add_product_to_cart(product_id=call.data.split('_')[1]) bot.answer_callback_query()
def add_carts(self, **kwargs): cart = Cart() for key in cart.__table__.columns.keys(): if key in kwargs: setattr(cart, key, kwargs.get(key)) self.session.add(cart)
def change_qty_prod(call): product_ = Product.objects.get(id=call.data.split('_')[1]) cart = Cart.get_or_create_cart(user_id=call.from_user.id) kb = InlineKeyboardMarkup() if call.data.split('_')[0] == 'cartincrease': if product_.get_quantity() > cart.get_count_product(product=product_): cart.add_product_to_cart(product=product_) product_desc = f"{product_.title}\n" \ f"Кол-во {cart.get_count_product(product=product_.id)} Цена: {product_.get_price()}\n" \ f"Сумма: {cart.get_count_product(product=product_.id) * product_.get_price()}\n" kb.add( InlineKeyboardButton(text=u'🔻 убрать', callback_data='cartdecrease_' + str(product_.id)), InlineKeyboardButton( text=cart.get_count_product(product=product_.id), callback_data='---'), InlineKeyboardButton(text=u'🔺 добавить', callback_data='cartincrease_' + str(product_.id)), InlineKeyboardButton(text=u'❌ ❗ удалить товар', callback_data='cartdelete_' + str(product_.id))) bot.edit_message_text(text=product_desc, chat_id=call.from_user.id, message_id=call.message.message_id) bot.edit_message_reply_markup(chat_id=call.from_user.id, message_id=call.message.message_id, reply_markup=kb) else: bot.answer_callback_query( callback_query_id=call.id, show_alert=True, text= 'Извините, это максимальное кол-во товара которое есть на остатке.' ) elif call.data.split('_')[0] == 'cartdecrease': cart.decrease_qty_product_cart(product=product_.id) product_desc = f"{product_.title}\n" \ f"Кол-во {cart.get_count_product(product=product_.id)} Цена: {product_.get_price()}\n" \ f"Сумма: {cart.get_count_product(product=product_.id) * product_.get_price()}\n" kb.add( InlineKeyboardButton(text=u'🔻 убрать', callback_data='cartdecrease_' + str(product_.id)), InlineKeyboardButton( text=cart.get_count_product(product=product_.id), callback_data='---'), InlineKeyboardButton(text=u'🔺 добавить', callback_data='cartincrease_' + str(product_.id)), InlineKeyboardButton(text=u'❌ ❗ удалить товар', callback_data='cartdelete_' + str(product_.id))) bot.edit_message_text(text=product_desc, chat_id=call.from_user.id, message_id=call.message.message_id) bot.edit_message_reply_markup(chat_id=call.from_user.id, message_id=call.message.message_id, reply_markup=kb) if cart.get_count_product(product=product_.id) == 0 and len( cart.get_cart_products()) > 0: cart.delete_product_from_cart(product=product_) bot.edit_message_text(text='Товар удален с корзины', chat_id=call.from_user.id, message_id=call.message.message_id) elif cart.get_count_product(product=product_.id) == 0 > 0: product_desc = f"{product_.title}\n" \ f"Кол-во {cart.get_count_product(product=product_.id)} Цена: {product_.get_price()}\n" \ f"Сумма: {cart.get_count_product(product=product_.id) * product_.get_price()}\n" kb.add( InlineKeyboardButton(text=u'🔻 убрать', callback_data='cartdecrease_' + str(product_.id)), InlineKeyboardButton( text=cart.get_count_product(product=product_.id), callback_data='---'), InlineKeyboardButton(text=u'🔺 добавить', callback_data='cartincrease_' + str(product_.id)), InlineKeyboardButton(text=u'❌ ❗ удалить товар', callback_data='cartdelete_' + str(product_.id))) bot.edit_message_text(text=product_desc, chat_id=call.from_user.id, message_id=call.message.message_id) bot.edit_message_reply_markup(chat_id=call.from_user.id, message_id=call.message.message_id, reply_markup=kb) elif len(cart.get_cart_products()) == 0: Cart.clear_cart(cart) bot.answer_callback_query(call.id, show_alert=True, text="💔 Корзина очищена") bot.send_message(call.from_user.id, START_PAGE, reply_markup=root_kb_mk)
def add_to_car(call): product_ = Product.objects.get(id=call.data.split('_')[1]) cart = Cart.get_or_create_cart(user_id=call.from_user.id) cart.add_product_to_cart(product=product_) bot.answer_callback_query(call.id, text="✅ Товар добавлен в корзину")
def delete_from_cart(call): product = Product.objects.get(id=call.data.replace("delete", "")) cart = Cart.get_or_create_cart(user_id=call.from_user.id) cart.delete_product_from_cart(product) bot.edit_message_caption(caption="Товар видалено з кошика!", chat_id=call.message.chat.id, message_id=call.message.message_id)
def add_to_cart(call): cart = Cart.get_or_create_cart(user_id=call.from_user.id) cart.add_product_to_cart(product_id=call.data.replace("product", "")) bot.send_message(call.from_user.id, "Товар додано в кошик!")
def send_cart_history(self, query): cart = Cart.get_or_create_cart(query.from_user.id) products = cart.get_cart_history() self._show_products(query, products)