""" One-time script to sync users.totalListings with actual listing counts. Run this once to fix existing user counters. Usage: python scripts/sync_total_listings.py """ import asyncio from motor.motor_asyncio import AsyncIOMotorClient from bson import ObjectId import os from dotenv import load_dotenv load_dotenv() MONGO_URI = os.getenv("MONGO_URI") or os.getenv("DATABASE_URL") async def sync_total_listings(): """Count actual listings per user and update their totalListings field.""" print("šŸ”„ Connecting to MongoDB...") client = AsyncIOMotorClient(MONGO_URI) # Get DB name from env or fallback DB_NAME = os.getenv("MONGODB_DATABASE", "lojiz_db") print(f"šŸ“‚ Using Database: {DB_NAME}") db = client[DB_NAME] print("šŸ“Š Aggregating listing counts per user...") # Step 1: Aggregate listing counts by user_id pipeline = [ {"$match": {"status": "active"}}, # Only count active listings {"$group": { "_id": "$user_id", "count": {"$sum": 1} }} ] listing_counts = {} async for doc in db.listings.aggregate(pipeline): user_id = doc["_id"] count = doc["count"] listing_counts[user_id] = count print(f"šŸ“‹ Found {len(listing_counts)} users with listings") # Step 2: Get all users users_cursor = db.users.find({}, {"_id": 1, "email": 1, "totalListings": 1}) updated_count = 0 async for user in users_cursor: user_id = str(user["_id"]) current_total = user.get("totalListings", 0) actual_count = listing_counts.get(user_id, 0) if current_total != actual_count: # Update the user's totalListings await db.users.update_one( {"_id": user["_id"]}, {"$set": {"totalListings": actual_count}} ) print(f"āœ… Updated {user.get('email', user_id)}: {current_total} → {actual_count}") updated_count += 1 else: print(f"ā­ļø Skipped {user.get('email', user_id)}: already correct ({actual_count})") print(f"\nšŸŽ‰ Done! Updated {updated_count} users.") client.close() if __name__ == "__main__": asyncio.run(sync_total_listings())