Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import asyncio
|
| 2 |
import json
|
| 3 |
import os
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
from aiogram import Bot, Dispatcher, types, F
|
| 6 |
from aiogram.filters import Command
|
|
@@ -126,7 +127,7 @@ async def show_products(message: types.Message):
|
|
| 126 |
await message.answer("Нет доступных товаров.")
|
| 127 |
return
|
| 128 |
for product in data['products']:
|
| 129 |
-
photo_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{product['photo']}" if 'photo'
|
| 130 |
caption = f"🏷 {product['name']} - {product['price']} руб.\nОписание: {product['description']}\n/id: {product['id']}"
|
| 131 |
if photo_url:
|
| 132 |
try:
|
|
@@ -140,7 +141,7 @@ async def show_products(message: types.Message):
|
|
| 140 |
@dp.message(F.text == "🛒 Корзина")
|
| 141 |
async def show_cart(message: types.Message):
|
| 142 |
user_id = message.from_user.id
|
| 143 |
-
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o
|
| 144 |
if not cart or not cart['items']:
|
| 145 |
await message.answer("Ваша корзина пуста.")
|
| 146 |
return
|
|
@@ -161,9 +162,9 @@ async def add_to_cart(callback_query: types.CallbackQuery):
|
|
| 161 |
product = next((p for p in data['products'] if p['id'] == product_id), None)
|
| 162 |
if product:
|
| 163 |
user_id = callback_query.from_user.id
|
| 164 |
-
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o
|
| 165 |
if not cart:
|
| 166 |
-
cart = {'user_id': user_id, 'items': [], '
|
| 167 |
data['orders'].append(cart)
|
| 168 |
cart['items'].append({'product_id': product_id, 'quantity': 1})
|
| 169 |
save_data(data)
|
|
@@ -171,22 +172,36 @@ async def add_to_cart(callback_query: types.CallbackQuery):
|
|
| 171 |
else:
|
| 172 |
await bot.answer_callback_query(callback_query.id, "Товар не найден.")
|
| 173 |
|
|
|
|
| 174 |
@dp.callback_query(F.data.startswith("complete_"))
|
| 175 |
async def complete_order(callback_query: types.CallbackQuery):
|
| 176 |
user_id = int(callback_query.data.split('_')[1])
|
| 177 |
-
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o
|
| 178 |
-
if cart:
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
save_data(data)
|
| 181 |
-
|
| 182 |
-
await bot.send_message(user_id, "
|
|
|
|
| 183 |
else:
|
| 184 |
await bot.answer_callback_query(callback_query.id, "Корзина пуста или заказ уже оформлен.")
|
| 185 |
|
| 186 |
@dp.message(F.text == "📦 Заказы")
|
| 187 |
async def show_orders(message: types.Message):
|
| 188 |
user_id = message.from_user.id
|
| 189 |
-
|
|
|
|
| 190 |
if not user_orders:
|
| 191 |
await message.answer("У вас нет оформленных заказо��.")
|
| 192 |
return
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import json
|
| 3 |
import os
|
| 4 |
+
import urllib.parse
|
| 5 |
from datetime import datetime
|
| 6 |
from aiogram import Bot, Dispatcher, types, F
|
| 7 |
from aiogram.filters import Command
|
|
|
|
| 127 |
await message.answer("Нет доступных товаров.")
|
| 128 |
return
|
| 129 |
for product in data['products']:
|
| 130 |
+
photo_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{product['photo']}" if product.get('photo') else None
|
| 131 |
caption = f"🏷 {product['name']} - {product['price']} руб.\nОписание: {product['description']}\n/id: {product['id']}"
|
| 132 |
if photo_url:
|
| 133 |
try:
|
|
|
|
| 141 |
@dp.message(F.text == "🛒 Корзина")
|
| 142 |
async def show_cart(message: types.Message):
|
| 143 |
user_id = message.from_user.id
|
| 144 |
+
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o.get('completed')), None)
|
| 145 |
if not cart or not cart['items']:
|
| 146 |
await message.answer("Ваша корзина пуста.")
|
| 147 |
return
|
|
|
|
| 162 |
product = next((p for p in data['products'] if p['id'] == product_id), None)
|
| 163 |
if product:
|
| 164 |
user_id = callback_query.from_user.id
|
| 165 |
+
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o.get('completed')), None)
|
| 166 |
if not cart:
|
| 167 |
+
cart = {'user_id': user_id, 'items': [], 'date': datetime.now().isoformat()}
|
| 168 |
data['orders'].append(cart)
|
| 169 |
cart['items'].append({'product_id': product_id, 'quantity': 1})
|
| 170 |
save_data(data)
|
|
|
|
| 172 |
else:
|
| 173 |
await bot.answer_callback_query(callback_query.id, "Товар не найден.")
|
| 174 |
|
| 175 |
+
# Изменённый обработчик "Оформить заказ" – заказ сразу отправляется в WhatsApp и удаляется из корзины
|
| 176 |
@dp.callback_query(F.data.startswith("complete_"))
|
| 177 |
async def complete_order(callback_query: types.CallbackQuery):
|
| 178 |
user_id = int(callback_query.data.split('_')[1])
|
| 179 |
+
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o.get('completed')), None)
|
| 180 |
+
if cart and cart['items']:
|
| 181 |
+
total = 0
|
| 182 |
+
cart_text = "Привет, я хочу сделать заказ:\n"
|
| 183 |
+
for item in cart['items']:
|
| 184 |
+
product = next((p for p in data['products'] if p['id'] == item['product_id']), None)
|
| 185 |
+
if product:
|
| 186 |
+
cart_text += f"{product['name']} - {product['price']} руб. x {item['quantity']}\n"
|
| 187 |
+
total += product['price'] * item['quantity']
|
| 188 |
+
cart_text += f"\nИтого: {total} руб."
|
| 189 |
+
encoded_text = urllib.parse.quote(cart_text)
|
| 190 |
+
whatsapp_link = f"https://wa.me/996500398754?text={encoded_text}"
|
| 191 |
+
# Удаляем корзину, чтобы заказ не попадал в личный кабинет
|
| 192 |
+
data['orders'].remove(cart)
|
| 193 |
save_data(data)
|
| 194 |
+
# Отправляем пользователю сообщение с ссылкой на WhatsApp
|
| 195 |
+
await bot.send_message(user_id, f"Пожалуйста, оформите заказ через WhatsApp, перейдя по ссылке:\n{whatsapp_link}")
|
| 196 |
+
await bot.answer_callback_query(callback_query.id)
|
| 197 |
else:
|
| 198 |
await bot.answer_callback_query(callback_query.id, "Корзина пуста или заказ уже оформлен.")
|
| 199 |
|
| 200 |
@dp.message(F.text == "📦 Заказы")
|
| 201 |
async def show_orders(message: types.Message):
|
| 202 |
user_id = message.from_user.id
|
| 203 |
+
# Поскольку оформленные заказы больше не сохраняются, здесь отображаются только те, которые остались в базе (если вдруг)
|
| 204 |
+
user_orders = [o for o in data['orders'] if o.get('completed')]
|
| 205 |
if not user_orders:
|
| 206 |
await message.answer("У вас нет оформленных заказо��.")
|
| 207 |
return
|