Spaces:
Running
Running
axeronis commited on
Commit ·
df97a07
1
Parent(s): 6db5d1b
fix(ai): add SEND_PAYMENT_QR tag support for QR codes
Browse files
backend/app/api/webhook.py
CHANGED
|
@@ -271,6 +271,67 @@ async def send_product_images_if_mentioned(
|
|
| 271 |
return last_message_id
|
| 272 |
|
| 273 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
async def send_media_files(
|
| 275 |
session,
|
| 276 |
tenant_id: UUID,
|
|
@@ -1605,6 +1666,16 @@ async def process_ai_response_background(
|
|
| 1605 |
# Clean tags from response
|
| 1606 |
ai_response["text"] = re.sub(media_pattern, '', ai_response["text"]).strip()
|
| 1607 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1608 |
ai_message = Message(
|
| 1609 |
tenant_id=tenant.id,
|
| 1610 |
conversation_id=conversation.id,
|
|
@@ -1675,6 +1746,19 @@ async def process_ai_response_background(
|
|
| 1675 |
)
|
| 1676 |
if media_msg_id:
|
| 1677 |
media_reply_id = media_msg_id # Prioritize explicit media for reply
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1678 |
|
| 1679 |
# Count AI messages to detect first message
|
| 1680 |
ai_msg_count = len([m for m in conversation_history if getattr(m, 'sender_type', None) == 'ai'])
|
|
|
|
| 271 |
return last_message_id
|
| 272 |
|
| 273 |
|
| 274 |
+
async def send_payment_qr_codes(
|
| 275 |
+
session,
|
| 276 |
+
tenant_id: UUID,
|
| 277 |
+
bot_token: str,
|
| 278 |
+
chat_id: str,
|
| 279 |
+
payment_qr_ids: list,
|
| 280 |
+
conversation_id: UUID = None
|
| 281 |
+
) -> Optional[int]:
|
| 282 |
+
"""
|
| 283 |
+
Send payment QR codes from PaymentMethod when AI uses [SEND_PAYMENT_QR:ID] tag.
|
| 284 |
+
"""
|
| 285 |
+
from app.models.knowledge import PaymentMethod
|
| 286 |
+
from app.services.telegram_service import telegram_service
|
| 287 |
+
|
| 288 |
+
last_sent_message_id = None
|
| 289 |
+
|
| 290 |
+
for qr_id_short in payment_qr_ids:
|
| 291 |
+
try:
|
| 292 |
+
# Find payment method by ID prefix (first 8 chars)
|
| 293 |
+
stmt = select(PaymentMethod).where(
|
| 294 |
+
PaymentMethod.tenant_id == tenant_id,
|
| 295 |
+
PaymentMethod.is_active == True
|
| 296 |
+
)
|
| 297 |
+
result = await session.execute(stmt)
|
| 298 |
+
all_payments = result.scalars().all()
|
| 299 |
+
|
| 300 |
+
# Find matching payment by ID prefix
|
| 301 |
+
payment = None
|
| 302 |
+
for pm in all_payments:
|
| 303 |
+
if str(pm.id).startswith(qr_id_short):
|
| 304 |
+
payment = pm
|
| 305 |
+
break
|
| 306 |
+
|
| 307 |
+
if not payment:
|
| 308 |
+
logger.warning(f"⚠️ Payment method not found: {qr_id_short}")
|
| 309 |
+
continue
|
| 310 |
+
|
| 311 |
+
if not payment.image_url:
|
| 312 |
+
logger.warning(f"⚠️ Payment method {payment.name} has no QR image")
|
| 313 |
+
continue
|
| 314 |
+
|
| 315 |
+
# Send QR code image
|
| 316 |
+
try:
|
| 317 |
+
result = await telegram_service.send_photo(
|
| 318 |
+
token=bot_token,
|
| 319 |
+
chat_id=chat_id,
|
| 320 |
+
photo_url=payment.image_url,
|
| 321 |
+
caption=f"💳 {payment.name}"
|
| 322 |
+
)
|
| 323 |
+
if result and result.get("message_id"):
|
| 324 |
+
last_sent_message_id = result["message_id"]
|
| 325 |
+
logger.info(f"📱 Payment QR sent: {payment.name}, message_id: {last_sent_message_id}")
|
| 326 |
+
except Exception as e:
|
| 327 |
+
logger.error(f"❌ Failed to send payment QR {payment.name}: {e}")
|
| 328 |
+
|
| 329 |
+
except Exception as e:
|
| 330 |
+
logger.error(f"❌ Failed to process payment QR {qr_id_short}: {e}")
|
| 331 |
+
|
| 332 |
+
return last_sent_message_id
|
| 333 |
+
|
| 334 |
+
|
| 335 |
async def send_media_files(
|
| 336 |
session,
|
| 337 |
tenant_id: UUID,
|
|
|
|
| 1666 |
# Clean tags from response
|
| 1667 |
ai_response["text"] = re.sub(media_pattern, '', ai_response["text"]).strip()
|
| 1668 |
|
| 1669 |
+
# Process [SEND_PAYMENT_QR:ID] tags - extract payment QR IDs to send
|
| 1670 |
+
payment_qr_ids_to_send = []
|
| 1671 |
+
payment_qr_pattern = r'\[SEND_PAYMENT_QR:([a-f0-9-]+)\]'
|
| 1672 |
+
payment_qr_matches = re.findall(payment_qr_pattern, ai_response["text"], re.IGNORECASE)
|
| 1673 |
+
if payment_qr_matches:
|
| 1674 |
+
payment_qr_ids_to_send = list(set(payment_qr_matches)) # Unique IDs
|
| 1675 |
+
logger.info(f"📱 AI wants to send {len(payment_qr_ids_to_send)} payment QR codes: {payment_qr_ids_to_send}")
|
| 1676 |
+
# Clean tags from response
|
| 1677 |
+
ai_response["text"] = re.sub(payment_qr_pattern, '', ai_response["text"]).strip()
|
| 1678 |
+
|
| 1679 |
ai_message = Message(
|
| 1680 |
tenant_id=tenant.id,
|
| 1681 |
conversation_id=conversation.id,
|
|
|
|
| 1746 |
)
|
| 1747 |
if media_msg_id:
|
| 1748 |
media_reply_id = media_msg_id # Prioritize explicit media for reply
|
| 1749 |
+
|
| 1750 |
+
# 3. Payment QR Codes ([SEND_PAYMENT_QR:ID])
|
| 1751 |
+
if payment_qr_ids_to_send:
|
| 1752 |
+
qr_msg_id = await send_payment_qr_codes(
|
| 1753 |
+
session=session,
|
| 1754 |
+
tenant_id=tenant.id,
|
| 1755 |
+
bot_token=tenant.telegram_bot_token,
|
| 1756 |
+
chat_id=chat_id,
|
| 1757 |
+
payment_qr_ids=payment_qr_ids_to_send,
|
| 1758 |
+
conversation_id=conversation.id
|
| 1759 |
+
)
|
| 1760 |
+
if qr_msg_id:
|
| 1761 |
+
media_reply_id = qr_msg_id
|
| 1762 |
|
| 1763 |
# Count AI messages to detect first message
|
| 1764 |
ai_msg_count = len([m for m in conversation_history if getattr(m, 'sender_type', None) == 'ai'])
|
backend/app/services/ai_memory_manager.py
CHANGED
|
@@ -779,6 +779,11 @@ class AIMemoryManager:
|
|
| 779 |
- "После согласия" → отправляй когда клиент говорит "да, хочу купить" или "оформляю"
|
| 780 |
- "Всегда" → упоминай в конце любого предложения о товаре/услуге
|
| 781 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 782 |
"""
|
| 783 |
for pm in payment_methods:
|
| 784 |
condition_text = {
|
|
@@ -787,13 +792,13 @@ class AIMemoryManager:
|
|
| 787 |
"always": "Всегда показывать"
|
| 788 |
}.get(pm.send_condition, pm.send_condition)
|
| 789 |
|
| 790 |
-
context += f"• {pm.name} [{condition_text}]\n"
|
| 791 |
if pm.payment_type == "requisites" and pm.requisites_text:
|
| 792 |
context += f" Реквизиты: {pm.requisites_text}\n"
|
| 793 |
elif pm.payment_type == "link" and pm.payment_link:
|
| 794 |
context += f" Ссылка: {pm.payment_link}\n"
|
| 795 |
-
|
| 796 |
-
context += f"
|
| 797 |
if pm.ai_instruction:
|
| 798 |
context += f" ⚠️ Инструкция: {pm.ai_instruction}\n"
|
| 799 |
context += "\n"
|
|
|
|
| 779 |
- "После согласия" → отправляй когда клиент говорит "да, хочу купить" или "оформляю"
|
| 780 |
- "Всегда" → упоминай в конце любого предложения о товаре/услуге
|
| 781 |
|
| 782 |
+
⚠️ ПРИОРИТЕТ СПОСОБОВ ОПЛАТЫ:
|
| 783 |
+
- Если клиент просит "QR" или "кьюар" → используй способ с QR-кодом
|
| 784 |
+
- Если клиент просит "карту" или "реквизиты" → используй реквизиты карты
|
| 785 |
+
- Для отправки QR-изображения используй тег: [SEND_PAYMENT_QR:ID]
|
| 786 |
+
|
| 787 |
"""
|
| 788 |
for pm in payment_methods:
|
| 789 |
condition_text = {
|
|
|
|
| 792 |
"always": "Всегда показывать"
|
| 793 |
}.get(pm.send_condition, pm.send_condition)
|
| 794 |
|
| 795 |
+
context += f"• [ID:{str(pm.id)[:8]}] {pm.name} [{condition_text}]\n"
|
| 796 |
if pm.payment_type == "requisites" and pm.requisites_text:
|
| 797 |
context += f" Реквизиты: {pm.requisites_text}\n"
|
| 798 |
elif pm.payment_type == "link" and pm.payment_link:
|
| 799 |
context += f" Ссылка: {pm.payment_link}\n"
|
| 800 |
+
if pm.image_url:
|
| 801 |
+
context += f" 📱 QR-код доступен → для отправки: [SEND_PAYMENT_QR:{str(pm.id)[:8]}]\n"
|
| 802 |
if pm.ai_instruction:
|
| 803 |
context += f" ⚠️ Инструкция: {pm.ai_instruction}\n"
|
| 804 |
context += "\n"
|