File size: 2,113 Bytes
88dcd96
194f4c3
88dcd96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194f4c3
88dcd96
194f4c3
88dcd96
 
 
 
 
 
 
 
 
 
 
 
 
 
194f4c3
 
 
 
88dcd96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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())