File size: 1,999 Bytes
bd1531f | 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 | """
Loads and caches product catalog and questionnaire config from JSON files.
"""
import json
import logging
from pathlib import Path
from typing import List, Dict, Any, Optional
logger = logging.getLogger(__name__)
_products: Optional[List[Dict]] = None
_questionnaire: Optional[Dict] = None
DATA_DIR = Path(__file__).parent / "data"
def get_products() -> List[Dict]:
global _products
if _products is None:
path = DATA_DIR / "products.json"
try:
with open(path, "r", encoding="utf-8") as f:
raw = json.load(f)
# Assign sequential IDs if not present
_products = [
{**p, "id": p.get("id", i + 1)}
for i, p in enumerate(raw)
]
logger.info("Loaded %d products from %s", len(_products), path)
except FileNotFoundError:
logger.error("products.json not found at %s", path)
_products = []
except json.JSONDecodeError as e:
logger.error("Failed to parse products.json: %s", e)
_products = []
return _products
def get_questionnaire() -> Dict[str, Any]:
global _questionnaire
if _questionnaire is None:
path = DATA_DIR / "questionnaire.json"
try:
with open(path, "r", encoding="utf-8") as f:
_questionnaire = json.load(f)
logger.info("Loaded questionnaire from %s", path)
except FileNotFoundError:
logger.warning("questionnaire.json not found — using empty config")
_questionnaire = {"questions": []}
except json.JSONDecodeError as e:
logger.error("Failed to parse questionnaire.json: %s", e)
_questionnaire = {"questions": []}
return _questionnaire
def reload_data() -> None:
"""Force reload of all cached data (useful in tests)."""
global _products, _questionnaire
_products = None
_questionnaire = None
get_products()
get_questionnaire()
|