supply_demand_content.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import json
  2. from typing import Any
  3. from sqlalchemy import text
  4. from app.core.config import settings
  5. from app.db.supply_mysql import SupplySessionLocal
  6. from app.strategies.config_store import _safe_identifier
  7. def _parse_ext_data(raw: object) -> dict[str, Any]:
  8. if raw is None:
  9. return {}
  10. if isinstance(raw, dict):
  11. return raw
  12. if isinstance(raw, (bytes, bytearray)):
  13. raw = raw.decode("utf-8")
  14. if isinstance(raw, str):
  15. text_value = raw.strip()
  16. if not text_value:
  17. return {}
  18. return json.loads(text_value)
  19. return {}
  20. def fetch_demand_content_by_dt(dt: str) -> list[dict[str, Any]]:
  21. table = _safe_identifier(settings.supply_demand_content_table)
  22. query = text(
  23. f"""
  24. SELECT
  25. merge_leve2,
  26. name,
  27. reason,
  28. suggestion,
  29. ext_data,
  30. score,
  31. dt
  32. FROM {table}
  33. WHERE dt = :dt
  34. AND name IS NOT NULL
  35. AND TRIM(name) <> ''
  36. ORDER BY score DESC, name ASC
  37. """
  38. )
  39. with SupplySessionLocal() as session:
  40. rows = session.execute(query, {"dt": dt}).mappings().all()
  41. results: list[dict[str, Any]] = []
  42. for row in rows:
  43. ext_data = _parse_ext_data(row["ext_data"])
  44. results.append(
  45. {
  46. "merge_leve2": row.get("merge_leve2"),
  47. "name": str(row["name"]).strip(),
  48. "reason": row.get("reason"),
  49. "suggestion": row.get("suggestion"),
  50. "ext_data": ext_data,
  51. "demand_type": ext_data.get("type"),
  52. "score": row.get("score"),
  53. "dt": str(row.get("dt") or dt).strip(),
  54. }
  55. )
  56. return results