Spaces:
Running

axeronis commited on
Commit
33256ac
·
1 Parent(s): 9e8e3d1

feat: Backend Media Reply logic & UI Sidebar fixes

Browse files
backend/app/api/webhook.py CHANGED
@@ -193,7 +193,7 @@ async def send_product_images_if_mentioned(
193
  chat_id: str,
194
  ai_text: str,
195
  conversation_id: UUID = None # NEW: to save messages in DB
196
- ):
197
  """
198
  Detect product names mentioned in AI response and send ALL their images.
199
  Also saves image messages to database so they appear in chat UI.
@@ -211,9 +211,10 @@ async def send_product_images_if_mentioned(
211
  products = result.scalars().all()
212
 
213
  if not products:
214
- return
215
 
216
  ai_text_lower = ai_text.lower()
 
217
 
218
  for product in products:
219
  # Check if product name is mentioned in AI response
@@ -237,16 +238,18 @@ async def send_product_images_if_mentioned(
237
 
238
  try:
239
  # Send all photos as a media group (album)
240
- await telegram_service.send_media_group(
241
  token=bot_token,
242
  chat_id=chat_id,
243
  photo_urls=all_image_urls,
244
  caption=caption
245
  )
246
- logger.info(f"📷 Auto-sent {len(all_image_urls)} images as album for product: {product.name}")
 
 
247
 
248
  # Save one message for the album in database
249
- if conversation_id:
250
  image_message = Message(
251
  conversation_id=conversation_id,
252
  tenant_id=tenant_id,
@@ -264,6 +267,8 @@ async def send_product_images_if_mentioned(
264
  # Commit all image messages if any were added
265
  if conversation_id:
266
  await session.commit()
 
 
267
 
268
 
269
  async def send_media_files(
@@ -275,7 +280,7 @@ async def send_media_files(
275
  media_ids: list,
276
  conversation_id: UUID = None,
277
  user_message: str = "" # For context in Reply
278
- ):
279
  """
280
  Send media files from MediaLibrary when AI uses [SEND_MEDIA:ID] tag.
281
  Records progress to prevent duplicate sends.
@@ -289,6 +294,8 @@ async def send_media_files(
289
  from app.services.llm_client import get_llm_client
290
  from datetime import datetime
291
 
 
 
292
  for media_id_short in media_ids:
293
  try:
294
  # Find media file by ID prefix (we use first 8 chars in prompt)
@@ -371,14 +378,14 @@ async def send_media_files(
371
  caption=caption
372
  )
373
  elif media_file.file_type == 'video':
374
- await telegram_service.send_video(
375
  token=bot_token,
376
  chat_id=chat_id,
377
  video_url=file_url,
378
  caption=caption
379
  )
380
  elif media_file.file_type == 'document':
381
- await telegram_service.send_document(
382
  token=bot_token,
383
  chat_id=chat_id,
384
  document_url=file_url,
@@ -386,6 +393,8 @@ async def send_media_files(
386
  )
387
  elif media_file.file_type in ['link']:
388
  # Send as text message with link
 
 
389
  send_result = await telegram_service.send_message(
390
  token=bot_token,
391
  chat_id=chat_id,
@@ -393,13 +402,16 @@ async def send_media_files(
393
  )
394
  else:
395
  # Default: send as document
396
- await telegram_service.send_document(
397
  token=bot_token,
398
  chat_id=chat_id,
399
  document_url=file_url,
400
  caption=caption
401
  )
402
 
 
 
 
403
  # Store message_id in MediaTracker for Reply feature
404
  if send_result.get("message_id"):
405
  media_tracker.mark_sent(lead_id_str, media_id_str, str(send_result["message_id"]))
@@ -933,7 +945,8 @@ async def get_or_create_conversation(
933
  async def send_telegram_message(
934
  bot_token: str,
935
  chat_id: str,
936
- text: str
 
937
  ) -> bool:
938
  """Send message via Telegram Bot API (Text or Photo)."""
939
  import re
@@ -975,6 +988,9 @@ async def send_telegram_message(
975
  "text": clean_text,
976
  "parse_mode": "Markdown"
977
  }
 
 
 
978
 
979
  try:
980
  # Attempt 1: Markdown
@@ -1635,6 +1651,35 @@ async def process_ai_response_background(
1635
 
1636
  try:
1637
  if channel == 'telegram':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1638
  # Count AI messages to detect first message
1639
  ai_msg_count = len([m for m in conversation_history if getattr(m, 'sender_type', None) == 'ai'])
1640
  is_first_message = ai_msg_count == 0
@@ -1804,11 +1849,14 @@ Answer with ONE word:
1804
  logger.warning(f"⚠️ AI voice upload to Supabase failed: {upload_err}")
1805
 
1806
  # Send voice message to Telegram
1807
- send_success = await telegram_service.send_voice(
 
1808
  token=tenant.telegram_bot_token,
1809
  chat_id=chat_id,
1810
- audio_bytes=audio_bytes
 
1811
  )
 
1812
 
1813
  if send_success:
1814
  logger.info(f"🎤 Voice response sent to chat {chat_id}")
@@ -1837,7 +1885,8 @@ Answer with ONE word:
1837
  await send_telegram_message(
1838
  bot_token=tenant.telegram_bot_token,
1839
  chat_id=chat_id,
1840
- text=extracted_text
 
1841
  )
1842
  else:
1843
  # Fallback to text if voice fails
@@ -1845,45 +1894,25 @@ Answer with ONE word:
1845
  send_success = await send_telegram_message(
1846
  bot_token=tenant.telegram_bot_token,
1847
  chat_id=chat_id,
1848
- text=ai_response["text"]
 
1849
  )
1850
  except Exception as voice_err:
1851
  logger.error(f"❌ Voice generation failed: {voice_err}, falling back to text")
1852
  send_success = await send_telegram_message(
1853
  bot_token=tenant.telegram_bot_token,
1854
  chat_id=chat_id,
1855
- text=ai_response["text"]
 
1856
  )
1857
  else:
1858
  # Standard text response
1859
  send_success = await send_telegram_message(
1860
  bot_token=tenant.telegram_bot_token,
1861
  chat_id=chat_id,
1862
- text=ai_response["text"]
1863
- )
1864
-
1865
- # Auto-send product images if mentioned in response
1866
- if send_success:
1867
- await send_product_images_if_mentioned(
1868
- session=session,
1869
- tenant_id=tenant.id,
1870
- bot_token=tenant.telegram_bot_token,
1871
- chat_id=chat_id,
1872
- ai_text=ai_response["text"],
1873
- conversation_id=conversation.id # Save images to DB for chat UI
1874
  )
1875
-
1876
- # Send media files from MediaLibrary if AI requested
1877
- if media_ids_to_send:
1878
- await send_media_files(
1879
- session=session,
1880
- tenant_id=tenant.id,
1881
- lead_id=lead_id,
1882
- bot_token=tenant.telegram_bot_token,
1883
- chat_id=chat_id,
1884
- media_ids=media_ids_to_send,
1885
- conversation_id=conversation.id
1886
- )
1887
  elif channel == 'linkedin':
1888
  from app.services.linkedin_service import linkedin_service
1889
  if lead.linkedin_urn:
 
193
  chat_id: str,
194
  ai_text: str,
195
  conversation_id: UUID = None # NEW: to save messages in DB
196
+ ) -> Optional[int]:
197
  """
198
  Detect product names mentioned in AI response and send ALL their images.
199
  Also saves image messages to database so they appear in chat UI.
 
211
  products = result.scalars().all()
212
 
213
  if not products:
214
+ return None
215
 
216
  ai_text_lower = ai_text.lower()
217
+ last_message_id = None
218
 
219
  for product in products:
220
  # Check if product name is mentioned in AI response
 
238
 
239
  try:
240
  # Send all photos as a media group (album)
241
+ result = await telegram_service.send_media_group(
242
  token=bot_token,
243
  chat_id=chat_id,
244
  photo_urls=all_image_urls,
245
  caption=caption
246
  )
247
+ if result["success"]:
248
+ last_message_id = result["message_id"]
249
+ logger.info(f"📷 Auto-sent {len(all_image_urls)} images as album for product: {product.name} (msg_id: {last_message_id})")
250
 
251
  # Save one message for the album in database
252
+ if conversation_id and result["success"]:
253
  image_message = Message(
254
  conversation_id=conversation_id,
255
  tenant_id=tenant_id,
 
267
  # Commit all image messages if any were added
268
  if conversation_id:
269
  await session.commit()
270
+
271
+ return last_message_id
272
 
273
 
274
  async def send_media_files(
 
280
  media_ids: list,
281
  conversation_id: UUID = None,
282
  user_message: str = "" # For context in Reply
283
+ ) -> Optional[int]:
284
  """
285
  Send media files from MediaLibrary when AI uses [SEND_MEDIA:ID] tag.
286
  Records progress to prevent duplicate sends.
 
294
  from app.services.llm_client import get_llm_client
295
  from datetime import datetime
296
 
297
+ last_sent_message_id = None
298
+
299
  for media_id_short in media_ids:
300
  try:
301
  # Find media file by ID prefix (we use first 8 chars in prompt)
 
378
  caption=caption
379
  )
380
  elif media_file.file_type == 'video':
381
+ send_result = await telegram_service.send_video(
382
  token=bot_token,
383
  chat_id=chat_id,
384
  video_url=file_url,
385
  caption=caption
386
  )
387
  elif media_file.file_type == 'document':
388
+ send_result = await telegram_service.send_document(
389
  token=bot_token,
390
  chat_id=chat_id,
391
  document_url=file_url,
 
393
  )
394
  elif media_file.file_type in ['link']:
395
  # Send as text message with link
396
+ # send_message returns dict with message_id in recent update (not yet, send_message returns dict? No, check telegram_service)
397
+ # Ah, send_message in telegram_service returns dict!
398
  send_result = await telegram_service.send_message(
399
  token=bot_token,
400
  chat_id=chat_id,
 
402
  )
403
  else:
404
  # Default: send as document
405
+ send_result = await telegram_service.send_document(
406
  token=bot_token,
407
  chat_id=chat_id,
408
  document_url=file_url,
409
  caption=caption
410
  )
411
 
412
+ if send_result.get("success"):
413
+ last_sent_message_id = send_result.get("message_id")
414
+
415
  # Store message_id in MediaTracker for Reply feature
416
  if send_result.get("message_id"):
417
  media_tracker.mark_sent(lead_id_str, media_id_str, str(send_result["message_id"]))
 
945
  async def send_telegram_message(
946
  bot_token: str,
947
  chat_id: str,
948
+ text: str,
949
+ reply_to_message_id: int = None
950
  ) -> bool:
951
  """Send message via Telegram Bot API (Text or Photo)."""
952
  import re
 
988
  "text": clean_text,
989
  "parse_mode": "Markdown"
990
  }
991
+ if reply_to_message_id:
992
+ payload["reply_to_message_id"] = reply_to_message_id
993
+
994
 
995
  try:
996
  # Attempt 1: Markdown
 
1651
 
1652
  try:
1653
  if channel == 'telegram':
1654
+ # Pre-send Media (Images / Files) so we can reply to them
1655
+ media_reply_id = None
1656
+
1657
+ # 1. Product Images
1658
+ prod_msg_id = await send_product_images_if_mentioned(
1659
+ session=session,
1660
+ tenant_id=tenant.id,
1661
+ bot_token=tenant.telegram_bot_token,
1662
+ chat_id=chat_id,
1663
+ ai_text=ai_response["text"],
1664
+ conversation_id=conversation.id
1665
+ )
1666
+ if prod_msg_id:
1667
+ media_reply_id = prod_msg_id
1668
+
1669
+ # 2. Media Files ([SEND_MEDIA:ID])
1670
+ if media_ids_to_send:
1671
+ media_msg_id = await send_media_files(
1672
+ session=session,
1673
+ tenant_id=tenant.id,
1674
+ lead_id=lead_id,
1675
+ bot_token=tenant.telegram_bot_token,
1676
+ chat_id=chat_id,
1677
+ media_ids=media_ids_to_send,
1678
+ conversation_id=conversation.id
1679
+ )
1680
+ if media_msg_id:
1681
+ media_reply_id = media_msg_id # Prioritize explicit media for reply
1682
+
1683
  # Count AI messages to detect first message
1684
  ai_msg_count = len([m for m in conversation_history if getattr(m, 'sender_type', None) == 'ai'])
1685
  is_first_message = ai_msg_count == 0
 
1849
  logger.warning(f"⚠️ AI voice upload to Supabase failed: {upload_err}")
1850
 
1851
  # Send voice message to Telegram
1852
+ # Use dict return and reply_to_message_id
1853
+ voice_result = await telegram_service.send_voice(
1854
  token=tenant.telegram_bot_token,
1855
  chat_id=chat_id,
1856
+ audio_bytes=audio_bytes,
1857
+ reply_to_message_id=media_reply_id
1858
  )
1859
+ send_success = voice_result.get("success", False)
1860
 
1861
  if send_success:
1862
  logger.info(f"🎤 Voice response sent to chat {chat_id}")
 
1885
  await send_telegram_message(
1886
  bot_token=tenant.telegram_bot_token,
1887
  chat_id=chat_id,
1888
+ text=extracted_text,
1889
+ reply_to_message_id=media_reply_id
1890
  )
1891
  else:
1892
  # Fallback to text if voice fails
 
1894
  send_success = await send_telegram_message(
1895
  bot_token=tenant.telegram_bot_token,
1896
  chat_id=chat_id,
1897
+ text=ai_response["text"],
1898
+ reply_to_message_id=media_reply_id
1899
  )
1900
  except Exception as voice_err:
1901
  logger.error(f"❌ Voice generation failed: {voice_err}, falling back to text")
1902
  send_success = await send_telegram_message(
1903
  bot_token=tenant.telegram_bot_token,
1904
  chat_id=chat_id,
1905
+ text=ai_response["text"],
1906
+ reply_to_message_id=media_reply_id
1907
  )
1908
  else:
1909
  # Standard text response
1910
  send_success = await send_telegram_message(
1911
  bot_token=tenant.telegram_bot_token,
1912
  chat_id=chat_id,
1913
+ text=ai_response["text"],
1914
+ reply_to_message_id=media_reply_id
 
 
 
 
 
 
 
 
 
 
1915
  )
 
 
 
 
 
 
 
 
 
 
 
 
1916
  elif channel == 'linkedin':
1917
  from app.services.linkedin_service import linkedin_service
1918
  if lead.linkedin_urn:
backend/app/services/telegram_service.py CHANGED
@@ -106,7 +106,7 @@ class TelegramService:
106
  logger.error(f"Telegram sendPhoto error: {e}")
107
  return {"success": False, "message_id": None}
108
 
109
- async def send_media_group(self, token: str, chat_id: str, photo_urls: list, caption: str = None) -> bool:
110
  """
111
  Send multiple photos as a media group (album) to Telegram chat.
112
  All photos appear grouped together in a single message.
@@ -116,13 +116,16 @@ class TelegramService:
116
  chat_id: Chat ID to send to
117
  photo_urls: List of photo URLs (max 10)
118
  caption: Optional caption (only shown on first photo)
 
 
 
119
  """
120
  if not token:
121
  logger.error("Telegram token not provided")
122
- return False
123
 
124
  if not photo_urls:
125
- return False
126
 
127
  # Telegram allows max 10 items in media group
128
  photo_urls = photo_urls[:10]
@@ -157,18 +160,25 @@ class TelegramService:
157
  response = await client.post(url, data=payload)
158
 
159
  if response.status_code == 200:
160
- logger.info(f"📷 Media group ({len(photo_urls)} photos) sent to chat {chat_id}")
161
- return True
 
 
 
 
162
  else:
163
  logger.error(f"Telegram sendMediaGroup failed: {response.text}")
164
  # Fallback: send photos individually
 
165
  for idx, photo_url in enumerate(photo_urls):
166
  cap = caption if idx == 0 else None
167
- await self.send_photo(token, chat_id, photo_url, cap)
168
- return True
 
 
169
  except Exception as e:
170
  logger.error(f"Telegram sendMediaGroup error: {e}")
171
- return False
172
 
173
  async def set_webhook(self, token: str, webhook_url: str) -> bool:
174
  """
@@ -185,13 +195,13 @@ class TelegramService:
185
  logger.error(f"Telegram setWebhook error: {e}")
186
  return False
187
 
188
- async def send_video(self, token: str, chat_id: str, video_url: str, caption: str = None) -> bool:
189
  """
190
  Send video to Telegram chat via URL.
191
  """
192
  if not token:
193
  logger.error("Telegram token not provided")
194
- return False
195
 
196
  url = self._get_url(token, "sendVideo")
197
  payload = {
@@ -208,22 +218,24 @@ class TelegramService:
208
  response = await client.post(url, json=payload)
209
 
210
  if response.status_code == 200:
 
 
211
  logger.info(f"🎬 Video sent to chat {chat_id}")
212
- return True
213
  else:
214
  logger.error(f"Telegram sendVideo failed: {response.text}")
215
- return False
216
  except Exception as e:
217
  logger.error(f"Telegram sendVideo error: {e}")
218
- return False
219
 
220
- async def send_document(self, token: str, chat_id: str, document_url: str, caption: str = None) -> bool:
221
  """
222
  Send document (PDF, etc) to Telegram chat via URL.
223
  """
224
  if not token:
225
  logger.error("Telegram token not provided")
226
- return False
227
 
228
  url = self._get_url(token, "sendDocument")
229
  payload = {
@@ -240,16 +252,18 @@ class TelegramService:
240
  response = await client.post(url, json=payload)
241
 
242
  if response.status_code == 200:
 
 
243
  logger.info(f"📄 Document sent to chat {chat_id}")
244
- return True
245
  else:
246
  logger.error(f"Telegram sendDocument failed: {response.text}")
247
- return False
248
  except Exception as e:
249
  logger.error(f"Telegram sendDocument error: {e}")
250
- return False
251
 
252
- async def send_voice(self, token: str, chat_id: str, audio_bytes: bytes, caption: str = None) -> bool:
253
  """
254
  Send voice message to Telegram chat.
255
 
@@ -260,10 +274,11 @@ class TelegramService:
260
  chat_id: Chat ID to send to
261
  audio_bytes: Audio file bytes (MP3 format from Edge TTS)
262
  caption: Optional caption for the voice message
 
263
  """
264
  if not token:
265
  logger.error("Telegram token not provided")
266
- return False
267
 
268
  try:
269
  # Convert MP3 to OGG for proper Telegram voice message
@@ -283,7 +298,7 @@ class TelegramService:
283
  except Exception as conv_err:
284
  logger.warning(f"⚠️ OGG conversion failed: {conv_err}, trying MP3 directly")
285
  # Fallback: try sending MP3 as audio
286
- return await self._send_audio_fallback(token, chat_id, audio_bytes)
287
 
288
  url = self._get_url(token, "sendVoice")
289
 
@@ -296,33 +311,44 @@ class TelegramService:
296
  if caption:
297
  data["caption"] = caption[:1024]
298
 
 
 
 
299
  response = await client.post(url, files=files, data=data)
300
 
301
  if response.status_code == 200:
 
 
302
  logger.info(f"🎤 Voice message sent to chat {chat_id}")
303
- return True
304
  else:
305
  logger.error(f"Telegram sendVoice failed: {response.text}")
306
  # Fallback to audio
307
- return await self._send_audio_fallback(token, chat_id, audio_bytes)
308
  except Exception as e:
309
  logger.error(f"Telegram sendVoice error: {e}")
310
- return False
311
 
312
- async def _send_audio_fallback(self, token: str, chat_id: str, audio_bytes: bytes) -> bool:
313
  """Fallback: send as audio file if voice fails."""
314
  url = self._get_url(token, "sendAudio")
315
  try:
316
  async with httpx.AsyncClient(timeout=30.0) as client:
317
  files = {"audio": ("voice.mp3", audio_bytes, "audio/mpeg")}
318
  data = {"chat_id": chat_id}
 
 
 
319
  response = await client.post(url, files=files, data=data)
 
320
  if response.status_code == 200:
 
 
321
  logger.info(f"🎵 Audio fallback sent to chat {chat_id}")
322
- return True
323
- return False
324
  except:
325
- return False
326
 
327
  # Singleton
328
  telegram_service = TelegramService()
 
106
  logger.error(f"Telegram sendPhoto error: {e}")
107
  return {"success": False, "message_id": None}
108
 
109
+ async def send_media_group(self, token: str, chat_id: str, photo_urls: list, caption: str = None) -> dict:
110
  """
111
  Send multiple photos as a media group (album) to Telegram chat.
112
  All photos appear grouped together in a single message.
 
116
  chat_id: Chat ID to send to
117
  photo_urls: List of photo URLs (max 10)
118
  caption: Optional caption (only shown on first photo)
119
+
120
+ Returns:
121
+ dict with 'success' (bool), 'message_id' (int or None - of the first message)
122
  """
123
  if not token:
124
  logger.error("Telegram token not provided")
125
+ return {"success": False, "message_id": None}
126
 
127
  if not photo_urls:
128
+ return {"success": False, "message_id": None}
129
 
130
  # Telegram allows max 10 items in media group
131
  photo_urls = photo_urls[:10]
 
160
  response = await client.post(url, data=payload)
161
 
162
  if response.status_code == 200:
163
+ data = response.json()
164
+ # Result is array of messages. Take the first one.
165
+ messages = data.get("result", [])
166
+ message_id = messages[0].get("message_id") if messages else None
167
+ logger.info(f"📷 Media group ({len(photo_urls)} photos) sent to chat {chat_id}, first msg_id: {message_id}")
168
+ return {"success": True, "message_id": message_id}
169
  else:
170
  logger.error(f"Telegram sendMediaGroup failed: {response.text}")
171
  # Fallback: send photos individually
172
+ last_msg_id = None
173
  for idx, photo_url in enumerate(photo_urls):
174
  cap = caption if idx == 0 else None
175
+ res = await self.send_photo(token, chat_id, photo_url, cap)
176
+ if res["success"]:
177
+ last_msg_id = res["message_id"]
178
+ return {"success": True, "message_id": last_msg_id}
179
  except Exception as e:
180
  logger.error(f"Telegram sendMediaGroup error: {e}")
181
+ return {"success": False, "message_id": None}
182
 
183
  async def set_webhook(self, token: str, webhook_url: str) -> bool:
184
  """
 
195
  logger.error(f"Telegram setWebhook error: {e}")
196
  return False
197
 
198
+ async def send_video(self, token: str, chat_id: str, video_url: str, caption: str = None) -> dict:
199
  """
200
  Send video to Telegram chat via URL.
201
  """
202
  if not token:
203
  logger.error("Telegram token not provided")
204
+ return {"success": False, "message_id": None}
205
 
206
  url = self._get_url(token, "sendVideo")
207
  payload = {
 
218
  response = await client.post(url, json=payload)
219
 
220
  if response.status_code == 200:
221
+ data = response.json()
222
+ message_id = data.get("result", {}).get("message_id")
223
  logger.info(f"🎬 Video sent to chat {chat_id}")
224
+ return {"success": True, "message_id": message_id}
225
  else:
226
  logger.error(f"Telegram sendVideo failed: {response.text}")
227
+ return {"success": False, "message_id": None}
228
  except Exception as e:
229
  logger.error(f"Telegram sendVideo error: {e}")
230
+ return {"success": False, "message_id": None}
231
 
232
+ async def send_document(self, token: str, chat_id: str, document_url: str, caption: str = None) -> dict:
233
  """
234
  Send document (PDF, etc) to Telegram chat via URL.
235
  """
236
  if not token:
237
  logger.error("Telegram token not provided")
238
+ return {"success": False, "message_id": None}
239
 
240
  url = self._get_url(token, "sendDocument")
241
  payload = {
 
252
  response = await client.post(url, json=payload)
253
 
254
  if response.status_code == 200:
255
+ data = response.json()
256
+ message_id = data.get("result", {}).get("message_id")
257
  logger.info(f"📄 Document sent to chat {chat_id}")
258
+ return {"success": True, "message_id": message_id}
259
  else:
260
  logger.error(f"Telegram sendDocument failed: {response.text}")
261
+ return {"success": False, "message_id": None}
262
  except Exception as e:
263
  logger.error(f"Telegram sendDocument error: {e}")
264
+ return {"success": False, "message_id": None}
265
 
266
+ async def send_voice(self, token: str, chat_id: str, audio_bytes: bytes, caption: str = None, reply_to_message_id: int = None) -> dict:
267
  """
268
  Send voice message to Telegram chat.
269
 
 
274
  chat_id: Chat ID to send to
275
  audio_bytes: Audio file bytes (MP3 format from Edge TTS)
276
  caption: Optional caption for the voice message
277
+ reply_to_message_id: Optional message ID to reply to
278
  """
279
  if not token:
280
  logger.error("Telegram token not provided")
281
+ return {"success": False, "message_id": None}
282
 
283
  try:
284
  # Convert MP3 to OGG for proper Telegram voice message
 
298
  except Exception as conv_err:
299
  logger.warning(f"⚠️ OGG conversion failed: {conv_err}, trying MP3 directly")
300
  # Fallback: try sending MP3 as audio
301
+ return await self._send_audio_fallback(token, chat_id, audio_bytes, reply_to_message_id)
302
 
303
  url = self._get_url(token, "sendVoice")
304
 
 
311
  if caption:
312
  data["caption"] = caption[:1024]
313
 
314
+ if reply_to_message_id:
315
+ data["reply_to_message_id"] = reply_to_message_id
316
+
317
  response = await client.post(url, files=files, data=data)
318
 
319
  if response.status_code == 200:
320
+ data = response.json()
321
+ message_id = data.get("result", {}).get("message_id")
322
  logger.info(f"🎤 Voice message sent to chat {chat_id}")
323
+ return {"success": True, "message_id": message_id}
324
  else:
325
  logger.error(f"Telegram sendVoice failed: {response.text}")
326
  # Fallback to audio
327
+ return await self._send_audio_fallback(token, chat_id, audio_bytes, reply_to_message_id)
328
  except Exception as e:
329
  logger.error(f"Telegram sendVoice error: {e}")
330
+ return {"success": False, "message_id": None}
331
 
332
+ async def _send_audio_fallback(self, token: str, chat_id: str, audio_bytes: bytes, reply_to_message_id: int = None) -> dict:
333
  """Fallback: send as audio file if voice fails."""
334
  url = self._get_url(token, "sendAudio")
335
  try:
336
  async with httpx.AsyncClient(timeout=30.0) as client:
337
  files = {"audio": ("voice.mp3", audio_bytes, "audio/mpeg")}
338
  data = {"chat_id": chat_id}
339
+ if reply_to_message_id:
340
+ data["reply_to_message_id"] = reply_to_message_id
341
+
342
  response = await client.post(url, files=files, data=data)
343
+
344
  if response.status_code == 200:
345
+ data = response.json()
346
+ message_id = data.get("result", {}).get("message_id")
347
  logger.info(f"🎵 Audio fallback sent to chat {chat_id}")
348
+ return {"success": True, "message_id": message_id}
349
+ return {"success": False, "message_id": None}
350
  except:
351
+ return {"success": False, "message_id": None}
352
 
353
  # Singleton
354
  telegram_service = TelegramService()
frontend/app/chats/page.tsx CHANGED
@@ -224,11 +224,11 @@ function ChatsContent() {
224
  <div className="chat-container flex bg-background overflow-hidden relative">
225
  {/* Left Column: Leads List */}
226
  <div className={cn(
227
- "h-full border-r border-white/10 flex flex-col transition-all duration-300 z-10 bg-background",
228
- // Desktop: Responsive widths to fit with sidebar
229
- "md:w-[280px] lg:w-1/4 lg:min-w-[300px] lg:max-w-[380px]",
230
  // Mobile: Full width if no lead selected, else hidden
231
- selectedLead ? "hidden md:flex" : "w-full flex"
232
  )}>
233
  {/* List Container - Let LeadsList handle internal scrolling */}
234
  <div className="flex-1 min-h-0">
@@ -253,7 +253,7 @@ function ChatsContent() {
253
  "flex-1 h-full flex flex-col relative z-10 bg-surface transition-all duration-300",
254
  // Mobile: Show only when lead selected
255
  // Desktop: Always show
256
- selectedLead ? "flex" : "hidden md:flex"
257
  )}>
258
  {selectedLead ? (
259
  <ChatWindow
 
224
  <div className="chat-container flex bg-background overflow-hidden relative">
225
  {/* Left Column: Leads List */}
226
  <div className={cn(
227
+ "h-full border-r border-white/10 flex flex-col transition-all duration-300 z-10 bg-background shrink-0",
228
+ // Desktop: Fixed width on large screens
229
+ "lg:w-[320px] xl:w-[380px]",
230
  // Mobile: Full width if no lead selected, else hidden
231
+ selectedLead ? "hidden lg:flex" : "w-full flex"
232
  )}>
233
  {/* List Container - Let LeadsList handle internal scrolling */}
234
  <div className="flex-1 min-h-0">
 
253
  "flex-1 h-full flex flex-col relative z-10 bg-surface transition-all duration-300",
254
  // Mobile: Show only when lead selected
255
  // Desktop: Always show
256
+ selectedLead ? "flex" : "hidden lg:flex"
257
  )}>
258
  {selectedLead ? (
259
  <ChatWindow
frontend/app/layout.tsx CHANGED
@@ -67,7 +67,7 @@ export default function RootLayout({
67
  <ProtectedLayout>
68
  <div className="flex h-screen relative text-white">
69
  {/* Desktop Sidebar */}
70
- <div className="hidden md:flex h-full relative z-20">
71
  <Sidebar />
72
  </div>
73
 
@@ -82,13 +82,13 @@ export default function RootLayout({
82
  <Header />
83
 
84
  {/* Mobile Header - FIXED at top */}
85
- <div className="md:hidden fixed top-0 left-0 right-0 z-[60]">
86
  <MobileHeader />
87
  </div>
88
 
89
  {/* Main Content - with padding for fixed header (64px) and nav (56px) */}
90
  <main className={cn(
91
- "flex-1 w-full pt-16 pb-14 md:pt-0 md:pb-0 overflow-x-hidden",
92
  // Disable global scroll on chats page to fix layout issues
93
  pathname?.startsWith('/chats') ? "overflow-y-hidden" : "overflow-y-auto"
94
  )}>
@@ -96,7 +96,7 @@ export default function RootLayout({
96
  </main>
97
 
98
  {/* Mobile Bottom Navigation - FIXED at bottom */}
99
- <div className="md:hidden fixed bottom-0 left-0 right-0 z-40">
100
  <MobileBottomNav />
101
  </div>
102
  </div>
 
67
  <ProtectedLayout>
68
  <div className="flex h-screen relative text-white">
69
  {/* Desktop Sidebar */}
70
+ <div className="hidden lg:flex h-full relative z-20 w-72 shrink-0">
71
  <Sidebar />
72
  </div>
73
 
 
82
  <Header />
83
 
84
  {/* Mobile Header - FIXED at top */}
85
+ <div className="lg:hidden fixed top-0 left-0 right-0 z-[60]">
86
  <MobileHeader />
87
  </div>
88
 
89
  {/* Main Content - with padding for fixed header (64px) and nav (56px) */}
90
  <main className={cn(
91
+ "flex-1 w-full pt-16 pb-14 lg:pt-0 lg:pb-0 overflow-x-hidden",
92
  // Disable global scroll on chats page to fix layout issues
93
  pathname?.startsWith('/chats') ? "overflow-y-hidden" : "overflow-y-auto"
94
  )}>
 
96
  </main>
97
 
98
  {/* Mobile Bottom Navigation - FIXED at bottom */}
99
+ <div className="lg:hidden fixed bottom-0 left-0 right-0 z-40">
100
  <MobileBottomNav />
101
  </div>
102
  </div>
frontend/components/Header.tsx CHANGED
@@ -55,7 +55,7 @@ export function Header() {
55
  }
56
 
57
  return (
58
- <header className="hidden md:flex h-16 border-b border-white/10 bg-[#050510] items-center justify-end px-6 sticky top-0 z-30">
59
  <div className="flex items-center gap-4">
60
 
61
  {/* User Profile with Dropdown */}
 
55
  }
56
 
57
  return (
58
+ <header className="hidden lg:flex h-16 border-b border-white/10 bg-[#050510] items-center justify-end px-6 sticky top-0 z-30">
59
  <div className="flex items-center gap-4">
60
 
61
  {/* User Profile with Dropdown */}
frontend/components/MobileNav.tsx CHANGED
@@ -53,9 +53,14 @@ export function MobileHeader({ onOpen }: { onOpen?: () => void }) {
53
  return (
54
  <div className="flex items-center justify-between px-4 h-16 bg-gradient-to-b from-black/80 to-black/60 backdrop-blur-xl text-white relative z-[60]">
55
  {/* Left: Logo + Brand Name */}
56
- <Link href="/dashboard" className="flex items-center gap-2">
57
- <img src="/logo-v2.png" alt="Logo" className="w-8 h-8 object-contain" />
58
- <span className="font-bold text-xl tracking-tight text-white">MicroFunnel</span>
 
 
 
 
 
59
  </Link>
60
 
61
  {/* Right: Hub */}
@@ -123,11 +128,18 @@ export function MobileSidebarWrapper({ children }: { children: React.ReactNode }
123
  useEffect(() => {
124
  if (isOpen) {
125
  document.body.style.overflow = 'hidden'
 
 
 
126
  } else {
127
  document.body.style.overflow = ''
 
 
128
  }
129
  return () => {
130
  document.body.style.overflow = ''
 
 
131
  }
132
  }, [isOpen])
133
 
@@ -143,7 +155,7 @@ export function MobileSidebarWrapper({ children }: { children: React.ReactNode }
143
  }
144
 
145
  return (
146
- <div className="md:hidden">
147
  <AnimatePresence>
148
  {isOpen && (
149
  <>
@@ -162,9 +174,19 @@ export function MobileSidebarWrapper({ children }: { children: React.ReactNode }
162
  animate={{ x: 0 }}
163
  exit={{ x: '-100%' }}
164
  transition={{ type: 'spring', damping: 25, stiffness: 200 }}
165
- className="fixed left-0 top-16 bottom-0 w-72 bg-gradient-to-r from-black/80 to-black/60 backdrop-blur-2xl z-50 shadow-2xl overflow-hidden border-r border-white/5"
 
 
 
166
  >
167
- {children}
 
 
 
 
 
 
 
168
  </motion.div>
169
  </>
170
  )}
 
53
  return (
54
  <div className="flex items-center justify-between px-4 h-16 bg-gradient-to-b from-black/80 to-black/60 backdrop-blur-xl text-white relative z-[60]">
55
  {/* Left: Logo + Brand Name */}
56
+ <Link href="/dashboard" className="flex items-center gap-3">
57
+ <div className="w-8 h-8 relative">
58
+ <div className="absolute inset-0 bg-gradient-to-tr from-indigo-500 to-purple-500 rounded-lg opacity-30 blur-sm" />
59
+ <img src="/logo-v2.png" alt="Logo" className="w-full h-full object-contain relative z-10" />
60
+ </div>
61
+ <span className="font-black text-xl tracking-widest uppercase bg-gradient-to-r from-indigo-400 via-purple-400 to-pink-400 bg-clip-text text-transparent">
62
+ MicroFunnel
63
+ </span>
64
  </Link>
65
 
66
  {/* Right: Hub */}
 
128
  useEffect(() => {
129
  if (isOpen) {
130
  document.body.style.overflow = 'hidden'
131
+ // Also try to lock the main content if possible
132
+ const mainContent = document.querySelector('main')
133
+ if (mainContent) mainContent.style.overflow = 'hidden'
134
  } else {
135
  document.body.style.overflow = ''
136
+ const mainContent = document.querySelector('main')
137
+ if (mainContent) mainContent.style.overflow = ''
138
  }
139
  return () => {
140
  document.body.style.overflow = ''
141
+ const mainContent = document.querySelector('main')
142
+ if (mainContent) mainContent.style.overflow = ''
143
  }
144
  }, [isOpen])
145
 
 
155
  }
156
 
157
  return (
158
+ <div className="lg:hidden">
159
  <AnimatePresence>
160
  {isOpen && (
161
  <>
 
174
  animate={{ x: 0 }}
175
  exit={{ x: '-100%' }}
176
  transition={{ type: 'spring', damping: 25, stiffness: 200 }}
177
+ className="fixed left-0 top-16 bottom-0 w-72 backdrop-blur-2xl z-50 shadow-2xl overflow-hidden border-r border-white/10"
178
+ style={{
179
+ background: 'linear-gradient(180deg, rgba(5, 5, 16, 0.95) 0%, rgba(13, 14, 24, 0.9) 100%)',
180
+ }}
181
  >
182
+ {/* Aurora Effect Background */}
183
+ <div className="absolute inset-0 overflow-hidden pointer-events-none z-0">
184
+ <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[30%] rounded-full bg-indigo-500/10 blur-[60px]" />
185
+ <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[30%] rounded-full bg-purple-500/10 blur-[60px]" />
186
+ </div>
187
+ <div className="relative z-10 h-full">
188
+ {children}
189
+ </div>
190
  </motion.div>
191
  </>
192
  )}
frontend/components/Sidebar.tsx CHANGED
@@ -146,19 +146,38 @@ export function Sidebar() {
146
  initial="hidden"
147
  animate="visible"
148
  variants={sidebarVariants}
149
- className="w-72 md:bg-background bg-transparent flex flex-col relative shrink-0 h-screen sticky top-0 pb-14 md:pb-0"
 
 
 
 
 
 
 
150
  >
 
 
 
 
 
 
151
  {/* Logo Section - Hidden on Mobile (already in main header) */}
152
- < div className="hidden md:block p-6 relative z-50" >
153
  <Link href="/dashboard" className="flex items-center gap-3 group">
154
- <div className="w-12 h-12 flex items-center justify-center">
155
- <img src="/logo-v2.png" alt="MicroFunnel Logo" className="w-full h-full object-contain" />
 
156
  </div>
157
- <h1 className="text-xl font-black text-md-on-surface tracking-widest group-hover:text-md-primary transition-colors uppercase">
158
- MicroFunnel
 
 
 
 
 
159
  </h1>
160
  </Link>
161
- </div >
162
 
163
  {/* Loading State */}
164
  {
 
146
  initial="hidden"
147
  animate="visible"
148
  variants={sidebarVariants}
149
+ className="w-72 flex flex-col relative shrink-0 h-screen sticky top-0 pb-14 lg:pb-0 border-r border-white/10 z-20"
150
+ style={{
151
+ background: 'linear-gradient(135deg, rgba(19, 17, 28, 0.4) 0%, rgba(30, 27, 75, 0.2) 100%)',
152
+ backdropFilter: 'blur(16px)',
153
+ WebkitBackdropFilter: 'blur(16px)',
154
+ boxShadow: '0 4px 30px rgba(0, 0, 0, 0.1)',
155
+ borderRight: '1px solid rgba(255, 255, 255, 0.05)'
156
+ }}
157
  >
158
+ {/* Aurora Effect Background - Enhanced */}
159
+ <div className="absolute inset-0 overflow-hidden pointer-events-none z-0">
160
+ <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[30%] rounded-full bg-indigo-500/10 blur-[80px]" />
161
+ <div className="absolute bottom-[20%] right-[-10%] w-[50%] h-[40%] rounded-full bg-purple-600/10 blur-[90px]" />
162
+ </div>
163
+
164
  {/* Logo Section - Hidden on Mobile (already in main header) */}
165
+ <div className="hidden lg:block p-6 relative z-50">
166
  <Link href="/dashboard" className="flex items-center gap-3 group">
167
+ <div className="w-12 h-12 flex items-center justify-center relative">
168
+ <div className="absolute inset-0 bg-gradient-to-tr from-indigo-500 to-purple-500 rounded-xl opacity-20 group-hover:opacity-40 transition-opacity blur-md" />
169
+ <img src="/logo-v2.png" alt="MicroFunnel Logo" className="w-full h-full object-contain relative z-10 drop-shadow-lg" />
170
  </div>
171
+ <h1 className="text-xl font-black tracking-widest uppercase relative">
172
+ <span className="absolute inset-0 blur-sm bg-gradient-to-r from-indigo-400 via-purple-400 to-pink-400 bg-clip-text text-transparent opacity-50">
173
+ MicroFunnel
174
+ </span>
175
+ <span className="bg-gradient-to-r from-indigo-400 via-purple-400 to-pink-400 bg-clip-text text-transparent">
176
+ MicroFunnel
177
+ </span>
178
  </h1>
179
  </Link>
180
+ </div>
181
 
182
  {/* Loading State */}
183
  {