Spaces:
Running
Running
File size: 2,280 Bytes
8c9362b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
"""
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())
|