destinyebuka commited on
Commit
1faae1d
·
1 Parent(s): 0fdf38e
Files changed (1) hide show
  1. scripts/backfill_alerts.py +83 -76
scripts/backfill_alerts.py CHANGED
@@ -29,7 +29,7 @@ from typing import List, Dict, Any
29
  async def run_backfill():
30
  """Main backfill function."""
31
  # Import after path setup
32
- from app.database import get_db
33
  from app.models.search_alert import SearchAlert
34
  from app.services.alert_service import check_listing_matches_alert, notify_user_of_match
35
 
@@ -39,87 +39,94 @@ async def run_backfill():
39
  print(f"Started at: {datetime.now().isoformat()}")
40
  print()
41
 
42
- db = await get_db()
 
43
 
44
- # 1. Fetch all active alerts
45
- print(" Fetching active search alerts...")
46
- alerts_cursor = db.search_alerts.find({"is_active": True})
47
- alerts = [SearchAlert(**doc) async for doc in alerts_cursor]
48
- print(f" Found {len(alerts)} active alerts")
49
-
50
- if not alerts:
51
- print(" No active alerts found. Nothing to backfill.")
52
- return
53
-
54
- # Print alert summary
55
- for alert in alerts:
56
- print(f" - User {alert.user_id}: '{alert.user_query}'")
57
- print()
58
-
59
- # 2. Fetch all published listings
60
- print(" Fetching published listings...")
61
- listings_cursor = db.listings.find({"status": "active"})
62
- listings = await listings_cursor.to_list(length=1000) # Limit for safety
63
- print(f" Found {len(listings)} active listings")
64
- print()
65
-
66
- if not listings:
67
- print(" No active listings found. Nothing to match.")
68
- return
69
-
70
- # 3. Check each listing against each alert
71
- print(" Checking matches...")
72
- matches_found = 0
73
- notifications_sent = 0
74
- skipped_duplicates = 0
75
-
76
- for listing in listings:
77
- listing_id = str(listing["_id"])
78
- listing_title = listing.get("title", "Untitled")
79
- listing_location = listing.get("location", "Unknown")
80
 
 
 
 
 
 
81
  for alert in alerts:
82
- # Check if this alert already received notification for this listing
83
- # (We store notified listing IDs in alert to prevent duplicate notifications)
84
- notified_listings = alert.notified_listing_ids or []
85
- if listing_id in notified_listings:
86
- skipped_duplicates += 1
87
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
- # Check if listing matches alert criteria
90
- if await check_listing_matches_alert(listing, alert):
91
- matches_found += 1
92
- print(f" MATCH: '{listing_title}' ({listing_location}) -> User {alert.user_id}")
 
 
 
93
 
94
- try:
95
- # Send notification
96
- await notify_user_of_match(alert, listing)
97
- notifications_sent += 1
98
-
99
- # Mark listing as notified for this alert (prevent duplicates)
100
- await db.search_alerts.update_one(
101
- {"_id": alert.id},
102
- {"$addToSet": {"notified_listing_ids": listing_id}}
103
- )
104
 
105
- print(f" Notification sent!")
106
-
107
- except Exception as e:
108
- print(f" Failed to notify: {e}")
109
-
110
- # 4. Summary
111
- print()
112
- print("="*60)
113
- print(" BACKFILL SUMMARY")
114
- print("="*60)
115
- print(f" Alerts processed: {len(alerts)}")
116
- print(f" Listings checked: {len(listings)}")
117
- print(f" Matches found: {matches_found}")
118
- print(f" Notifications sent: {notifications_sent}")
119
- print(f" Duplicates skipped: {skipped_duplicates}")
120
- print()
121
- print(f"Completed at: {datetime.now().isoformat()}")
122
- print("="*60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
 
125
  if __name__ == "__main__":
 
29
  async def run_backfill():
30
  """Main backfill function."""
31
  # Import after path setup
32
+ from app.database import get_db, connect_db, disconnect_db
33
  from app.models.search_alert import SearchAlert
34
  from app.services.alert_service import check_listing_matches_alert, notify_user_of_match
35
 
 
39
  print(f"Started at: {datetime.now().isoformat()}")
40
  print()
41
 
42
+ # Initialize DB Connection
43
+ await connect_db()
44
 
45
+ try:
46
+ db = await get_db()
47
+
48
+ # 1. Fetch all active alerts
49
+ print(" Fetching active search alerts...")
50
+ alerts_cursor = db.search_alerts.find({"is_active": True})
51
+ alerts = [SearchAlert(**doc) async for doc in alerts_cursor]
52
+ print(f" Found {len(alerts)} active alerts")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ if not alerts:
55
+ print(" No active alerts found. Nothing to backfill.")
56
+ return
57
+
58
+ # Print alert summary
59
  for alert in alerts:
60
+ print(f" - User {alert.user_id}: '{alert.user_query}'")
61
+ print()
62
+
63
+ # 2. Fetch all published listings
64
+ print(" Fetching published listings...")
65
+ listings_cursor = db.listings.find({"status": "active"})
66
+ listings = await listings_cursor.to_list(length=1000) # Limit for safety
67
+ print(f" Found {len(listings)} active listings")
68
+ print()
69
+
70
+ if not listings:
71
+ print(" No active listings found. Nothing to match.")
72
+ return
73
+
74
+ # 3. Check each listing against each alert
75
+ print(" Checking matches...")
76
+ matches_found = 0
77
+ notifications_sent = 0
78
+ skipped_duplicates = 0
79
+
80
+ for listing in listings:
81
+ listing_id = str(listing["_id"])
82
+ listing_title = listing.get("title", "Untitled")
83
+ listing_location = listing.get("location", "Unknown")
84
 
85
+ for alert in alerts:
86
+ # Check if this alert already received notification for this listing
87
+ # (We store notified listing IDs in alert to prevent duplicate notifications)
88
+ notified_listings = alert.notified_listing_ids or []
89
+ if listing_id in notified_listings:
90
+ skipped_duplicates += 1
91
+ continue
92
 
93
+ # Check if listing matches alert criteria
94
+ if await check_listing_matches_alert(listing, alert):
95
+ matches_found += 1
96
+ print(f" MATCH: '{listing_title}' ({listing_location}) -> User {alert.user_id}")
 
 
 
 
 
 
97
 
98
+ try:
99
+ # Send notification
100
+ await notify_user_of_match(alert, listing)
101
+ notifications_sent += 1
102
+
103
+ # Mark listing as notified for this alert (prevent duplicates)
104
+ await db.search_alerts.update_one(
105
+ {"_id": alert.id},
106
+ {"$addToSet": {"notified_listing_ids": listing_id}}
107
+ )
108
+
109
+ print(f" Notification sent!")
110
+
111
+ except Exception as e:
112
+ print(f" Failed to notify: {e}")
113
+
114
+ # 4. Summary
115
+ print()
116
+ print("="*60)
117
+ print(" BACKFILL SUMMARY")
118
+ print("="*60)
119
+ print(f" Alerts processed: {len(alerts)}")
120
+ print(f" Listings checked: {len(listings)}")
121
+ print(f" Matches found: {matches_found}")
122
+ print(f" Notifications sent: {notifications_sent}")
123
+ print(f" Duplicates skipped: {skipped_duplicates}")
124
+ print()
125
+ print(f"Completed at: {datetime.now().isoformat()}")
126
+ print("="*60)
127
+
128
+ finally:
129
+ await disconnect_db()
130
 
131
 
132
  if __name__ == "__main__":