flpolprojects commited on
Commit
2e8fce9
·
verified ·
1 Parent(s): 3e50d1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -8
app.py CHANGED
@@ -127,7 +127,7 @@ async def show_products(message: types.Message):
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 'photo' in product else None
131
  caption = f"🏷 {product['name']} - {product['price']} руб.\nОписание: {product['description']}\n/id: {product['id']}"
132
  if photo_url:
133
  try:
@@ -141,7 +141,7 @@ async def show_products(message: types.Message):
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['completed']), None)
145
  if not cart or not cart['items']:
146
  await message.answer("Ваша корзина пуста.")
147
  return
@@ -162,9 +162,9 @@ async def add_to_cart(callback_query: types.CallbackQuery):
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['completed']), None)
166
  if not cart:
167
- cart = {'user_id': user_id, 'items': [], 'completed': False, 'date': datetime.now().isoformat()}
168
  data['orders'].append(cart)
169
  cart['items'].append({'product_id': product_id, 'quantity': 1})
170
  save_data(data)
@@ -172,10 +172,11 @@ async def add_to_cart(callback_query: types.CallbackQuery):
172
  else:
173
  await bot.answer_callback_query(callback_query.id, "Товар не найден.")
174
 
 
175
  @dp.callback_query(F.data.startswith("complete_"))
176
  async def complete_order(callback_query: types.CallbackQuery):
177
  user_id = int(callback_query.data.split('_')[1])
178
- cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o['completed']), None)
179
  if cart and cart['items']:
180
  total = 0
181
  cart_text = "Привет, я хочу сделать заказ:\n"
@@ -187,16 +188,20 @@ async def complete_order(callback_query: types.CallbackQuery):
187
  cart_text += f"\nИтого: {total} руб."
188
  encoded_text = urllib.parse.quote(cart_text)
189
  whatsapp_link = f"https://wa.me/996500398754?text={encoded_text}"
190
- cart['completed'] = True
 
191
  save_data(data)
192
- await bot.answer_callback_query(callback_query.id, url=whatsapp_link)
 
 
193
  else:
194
  await bot.answer_callback_query(callback_query.id, "Корзина пуста или заказ уже оформлен.")
195
 
196
  @dp.message(F.text == "📦 Заказы")
197
  async def show_orders(message: types.Message):
198
  user_id = message.from_user.id
199
- user_orders = [o for o in data['orders'] if o['user_id'] == user_id and o['completed']]
 
200
  if not user_orders:
201
  await message.answer("У вас нет оформленных заказов.")
202
  return
 
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"
 
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