""" Seed script — populates dashboard_widgets collection in MongoDB. Derives all documents from KPI_WIDGET_REGISTRY (single source of truth). Run from the analytics-ms root: python -m scripts.seed_widget_collection """ import asyncio import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) from app.core.config import settings # noqa: E402 from app.nosql import connect_to_mongo, close_mongo_connection, get_database # noqa: E402 from app.kpi_cache.constants import KPI_WIDGET_REGISTRY # noqa: E402 COLLECTION = "dashboard_widgets" def _build_document(widget_id: str, meta: dict) -> dict: doc = { "widget_id": widget_id, "type": meta.get("widget_type", "kpi"), "title": meta.get("title", widget_id), "category": meta.get("category", ""), "unit": meta.get("unit"), "description": meta.get("description"), "drill_down_url": meta.get("drill_down_url"), "data_config": { "source": "merchant_kpi_stats", "params": { "widget": widget_id, "period_window": "mtd", "unit": meta.get("unit", "count"), }, }, } # Include chart_type for chart widgets if meta.get("chart_type"): doc["chart_type"] = meta["chart_type"] return doc async def seed(): await connect_to_mongo() db = get_database() col = db[COLLECTION] # Ensure unique index on widget_id await col.create_index("widget_id", unique=True, background=True, name="widget_id_unique") docs = [_build_document(wid, meta) for wid, meta in KPI_WIDGET_REGISTRY.items()] upserted = 0 for doc in docs: result = await col.update_one( {"widget_id": doc["widget_id"]}, {"$set": doc}, upsert=True, ) if result.upserted_id or result.modified_count: upserted += 1 print(f"Seeded {upserted}/{len(docs)} widget collection documents into '{COLLECTION}'.") await close_mongo_connection() if __name__ == "__main__": asyncio.run(seed())