Spaces:
Sleeping

axeronis commited on
Commit
a5a659b
·
1 Parent(s): 400a0b9

fix: Robust product tracking (DB), Regex matching, Google Auth

Browse files
Files changed (1) hide show
  1. backend/app/api/webhook.py +43 -22
backend/app/api/webhook.py CHANGED
@@ -216,34 +216,48 @@ async def send_product_images_if_mentioned(
216
  if not products:
217
  return None
218
 
 
 
 
 
 
 
 
 
219
  ai_text_lower = ai_text.lower()
220
  last_message_id = None
221
 
 
 
 
 
 
 
 
222
  for product in products:
223
- # Check if product name is mentioned in AI response
224
- product_name_lower = product.name.lower()
225
- if product_name_lower in ai_text_lower:
 
 
226
  product_id_str = str(product.id)
227
  lead_id_str = str(lead_id)
228
 
229
- # CHECK TRACKER: Already sent?
230
- if not media_tracker.should_send_product_media(lead_id_str, product_id_str):
231
- # Already sent! Get cached message_id to Reply instead
232
- cached_msg_id = media_tracker.get_message_id_for_product(lead_id_str, product_id_str)
233
- if cached_msg_id:
234
- logger.info(f"♻️ Product {product.name} already sent. Using cached msg_id {cached_msg_id} for reply.")
235
- try:
236
- last_message_id = int(cached_msg_id)
237
- # We found the product reference to reply to.
238
- # Stop searching (or continue if we want to support multiple? AI usually replies to one)
239
- # Let's break to reply to the first found product
240
- return last_message_id
241
- except:
242
- pass
243
- # If no cached ID (e.g. from previous session), we might skip or re-send.
244
- # To be safe and avoid duplicates without context, we skip.
245
- # BUT if user asked for it specifically?
246
- # Let's rely on should_send_product_media returning False.
247
  continue
248
 
249
  # Collect all image URLs
@@ -274,12 +288,19 @@ async def send_product_images_if_mentioned(
274
  last_message_id = result["message_id"]
275
  logger.info(f"📷 Auto-sent {len(all_image_urls)} images as album for product: {product.name} (msg_id: {last_message_id})")
276
 
277
- # TRACK SENT STATUS
278
  media_tracker.mark_product_sent(
279
  lead_id_str,
280
  product_id_str,
281
  message_id=str(last_message_id)
282
  )
 
 
 
 
 
 
 
283
 
284
  # Save one message for the album in database
285
  if conversation_id and result["success"]:
 
216
  if not products:
217
  return None
218
 
219
+ import re
220
+
221
+ # Fetch lead to access/update DB persistence
222
+ from app.models.lead import Lead
223
+ lead = await session.get(Lead, lead_id)
224
+ if not lead:
225
+ return None
226
+
227
  ai_text_lower = ai_text.lower()
228
  last_message_id = None
229
 
230
+ # Load persistent sent products: { "product_id": "message_id" }
231
+ summary = lead.ai_summary_json or {}
232
+ sent_products_db = summary.get("sent_products", {})
233
+ # Ensure it's a dict (migration from older list format if any)
234
+ if isinstance(sent_products_db, list):
235
+ sent_products_db = {pid: None for pid in sent_products_db}
236
+
237
  for product in products:
238
+ # Strict Regex Match (Word Boundary) to avoid "Start" matching "Start your day"
239
+ # Escape special chars in product name
240
+ pattern = r'(?<!\w)' + re.escape(product.name.lower()) + r'(?!\w)'
241
+
242
+ if re.search(pattern, ai_text_lower):
243
  product_id_str = str(product.id)
244
  lead_id_str = str(lead_id)
245
 
246
+ # 1. Check DB Persistence (Primary)
247
+ cached_msg_id_db = sent_products_db.get(product_id_str)
248
+
249
+ # 2. Check RAM Persistence (Secondary/Fallback)
250
+ cached_msg_id_ram = media_tracker.get_message_id_for_product(lead_id_str, product_id_str)
251
+
252
+ cached_msg_id = cached_msg_id_db or cached_msg_id_ram
253
+
254
+ if cached_msg_id:
255
+ logger.info(f"♻️ Product {product.name} already sent (DB/RAM cache). Using msg_id {cached_msg_id} for reply.")
256
+ try:
257
+ last_message_id = int(cached_msg_id)
258
+ return last_message_id
259
+ except:
260
+ pass
 
 
 
261
  continue
262
 
263
  # Collect all image URLs
 
288
  last_message_id = result["message_id"]
289
  logger.info(f"📷 Auto-sent {len(all_image_urls)} images as album for product: {product.name} (msg_id: {last_message_id})")
290
 
291
+ # TRACK SENT STATUS (RAM)
292
  media_tracker.mark_product_sent(
293
  lead_id_str,
294
  product_id_str,
295
  message_id=str(last_message_id)
296
  )
297
+
298
+ # TRACK SENT STATUS (DB)
299
+ sent_products_db[product_id_str] = str(last_message_id)
300
+ summary["sent_products"] = sent_products_db
301
+ lead.ai_summary_json = summary
302
+ session.add(lead)
303
+ await session.commit()
304
 
305
  # Save one message for the album in database
306
  if conversation_id and result["success"]: