announcement_service.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """
  2. 公告服务
  3. """
  4. from typing import Tuple, List, Dict, Any
  5. from sqlalchemy.orm import Session
  6. from app.models.announcement import Announcement
  7. from datetime import datetime
  8. from app.core.logger import logger
  9. class AnnouncementService:
  10. """公告服务"""
  11. def __init__(self, db: Session):
  12. self.db = db
  13. def get_announcements(self, page: int = 1, page_size: int = 10,
  14. include_inactive: bool = False) -> Tuple[bool, str, dict]:
  15. """
  16. 获取公告列表
  17. Args:
  18. page: 页码(从1开始)
  19. page_size: 每页数量
  20. include_inactive: 是否包含未启用的公告
  21. Returns:
  22. (success, message, data)
  23. """
  24. try:
  25. # 构建查询
  26. query = self.db.query(Announcement).filter(
  27. Announcement.is_deleted == 0
  28. )
  29. if not include_inactive:
  30. query = query.filter(Announcement.is_active == 1)
  31. # 统计总数
  32. total = query.count()
  33. # 分页查询:重要公告在前(priority 降序),同优先级按创建时间最新在前(created_at 降序)
  34. offset = (page - 1) * page_size
  35. announcements = query.order_by(
  36. Announcement.priority.desc(),
  37. Announcement.created_at.desc()
  38. ).offset(offset).limit(page_size).all()
  39. # 构建响应
  40. announcement_list = []
  41. for ann in announcements:
  42. announcement_list.append({
  43. "id": ann.id,
  44. "title": ann.title,
  45. "content": ann.content,
  46. "priority": ann.priority,
  47. "publish_time": ann.publish_time.isoformat() if ann.publish_time else None,
  48. "created_at": ann.created_at.isoformat() if ann.created_at else None
  49. })
  50. return True, "成功", {
  51. "announcements": announcement_list,
  52. "total": total,
  53. "page": page,
  54. "page_size": page_size
  55. }
  56. except Exception as e:
  57. logger.exception(f"获取公告列表失败: {e}")
  58. return False, f"获取公告失败: {str(e)}", {}
  59. def get_latest_announcement(self) -> Tuple[bool, str, dict]:
  60. """获取最新公告"""
  61. try:
  62. announcement = self.db.query(Announcement).filter(
  63. Announcement.is_deleted == 0,
  64. Announcement.is_active == 1
  65. ).order_by(
  66. Announcement.priority.desc(),
  67. Announcement.created_at.desc()
  68. ).first()
  69. if not announcement:
  70. return False, "暂无公告", {}
  71. return True, "成功", {
  72. "id": announcement.id,
  73. "title": announcement.title,
  74. "content": announcement.content,
  75. "priority": announcement.priority,
  76. "publish_time": announcement.publish_time.isoformat() if announcement.publish_time else None
  77. }
  78. except Exception as e:
  79. logger.exception(f"获取最新公告失败: {e}")
  80. return False, f"获取公告失败: {str(e)}", {}