history_service.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """
  2. 分析历史记录服务 — 管理各类分析报告的历史存储与查询
  3. """
  4. from datetime import date
  5. from typing import Optional
  6. from sqlalchemy import select, func, delete
  7. from app.models.database import async_session_factory
  8. from app.models.history_models import AnalysisHistory
  9. async def save_analysis(
  10. analysis_type: str,
  11. content: str,
  12. user_id: str = "default",
  13. stock_code: Optional[str] = None,
  14. stock_name: Optional[str] = None,
  15. title: Optional[str] = None,
  16. ) -> dict:
  17. """保存分析报告到历史记录"""
  18. try:
  19. today = date.today().isoformat()
  20. async with async_session_factory() as db:
  21. record = AnalysisHistory(
  22. user_id=user_id,
  23. date=today,
  24. type=analysis_type,
  25. stock_code=stock_code,
  26. stock_name=stock_name,
  27. title=title or f"{analysis_type}_{today}",
  28. content=content,
  29. )
  30. db.add(record)
  31. await db.commit()
  32. await db.refresh(record)
  33. return {"success": True, "id": record.id}
  34. except Exception as e:
  35. return {"success": False, "error": str(e)}
  36. async def get_history_list(
  37. analysis_type: Optional[str] = None,
  38. user_id: str = "default",
  39. limit: int = 20,
  40. ) -> dict:
  41. """获取历史记录列表"""
  42. try:
  43. async with async_session_factory() as db:
  44. conditions = [AnalysisHistory.user_id == user_id]
  45. if analysis_type:
  46. conditions.append(AnalysisHistory.type == analysis_type)
  47. stmt = select(AnalysisHistory).where(*conditions).order_by(
  48. AnalysisHistory.created_at.desc()
  49. ).limit(limit)
  50. result = await db.execute(stmt)
  51. records = result.scalars().all()
  52. count_stmt = select(func.count()).select_from(AnalysisHistory).where(*conditions)
  53. total = (await db.execute(count_stmt)).scalar()
  54. return {
  55. "success": True,
  56. "items": [r.to_dict() for r in records],
  57. "total": total or 0,
  58. }
  59. except Exception as e:
  60. return {"success": False, "items": [], "total": 0, "error": str(e)}
  61. async def get_history_detail(record_id: int) -> dict:
  62. """获取单条历史记录详情"""
  63. try:
  64. async with async_session_factory() as db:
  65. record = await db.get(AnalysisHistory, record_id)
  66. if not record:
  67. return {"success": False, "error": "记录不存在"}
  68. return {"success": True, "record": record.to_dict()}
  69. except Exception as e:
  70. return {"success": False, "error": str(e)}
  71. async def delete_history(record_id: int) -> dict:
  72. """删除单条历史记录"""
  73. try:
  74. async with async_session_factory() as db:
  75. record = await db.get(AnalysisHistory, record_id)
  76. if not record:
  77. return {"success": False, "error": "记录不存在"}
  78. await db.delete(record)
  79. await db.commit()
  80. return {"success": True, "message": "已删除"}
  81. except Exception as e:
  82. return {"success": False, "error": str(e)}
  83. async def clear_today_history(analysis_type: Optional[str] = None) -> dict:
  84. """清空今日历史记录"""
  85. try:
  86. today = date.today().isoformat()
  87. async with async_session_factory() as db:
  88. conditions = [AnalysisHistory.date == today]
  89. if analysis_type:
  90. conditions.append(AnalysisHistory.type == analysis_type)
  91. stmt = delete(AnalysisHistory).where(*conditions)
  92. result = await db.execute(stmt)
  93. await db.commit()
  94. return {"success": True, "count": result.rowcount}
  95. except Exception as e:
  96. return {"success": False, "error": str(e)}