94 lines
2.9 KiB
Python
94 lines
2.9 KiB
Python
"""
|
||
backend/app/services/admin/announcement_service.py
|
||
|
||
用途:系统公告 CRUD 与活跃公告列表(管理端 + 工作台/登录页只读)。
|
||
依赖:models.Announcement、app.core.errors。
|
||
逻辑:api/admin/announcements.py 管理 CRUD;api/workspace/announcements.py 只读活跃列表。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from app import db
|
||
from app.core.errors import NotFoundError, ValidationError
|
||
from app.models import Announcement
|
||
|
||
|
||
def serialize_announcement(ann: Announcement, *, include_active: bool = False) -> dict:
|
||
"""Announcement ORM → API dict。"""
|
||
row = {
|
||
'id': ann.id,
|
||
'title': ann.title,
|
||
'content': ann.content,
|
||
'created_at': ann.created_at.isoformat() if ann.created_at else None,
|
||
}
|
||
if include_active:
|
||
row['is_active'] = bool(ann.is_active)
|
||
return row
|
||
|
||
|
||
def list_active_announcements() -> list[dict]:
|
||
"""返回已发布(is_active)公告,供工作台/登录页展示。"""
|
||
rows = (
|
||
db.session.query(Announcement)
|
||
.filter(Announcement.is_active.is_(True))
|
||
.order_by(Announcement.created_at.desc())
|
||
.all()
|
||
)
|
||
return [serialize_announcement(a) for a in rows]
|
||
|
||
|
||
def list_announcements() -> list[dict]:
|
||
"""管理端列表:含全部公告及 is_active 字段。"""
|
||
rows = db.session.query(Announcement).order_by(Announcement.created_at.desc()).all()
|
||
return [serialize_announcement(a, include_active=True) for a in rows]
|
||
|
||
|
||
def create_announcement(data: dict[str, Any]) -> dict:
|
||
"""
|
||
创建公告。
|
||
Returns:
|
||
{ id, message }。
|
||
Raises:
|
||
ValidationError: title/content 缺失。
|
||
"""
|
||
if not data.get('title') or not data.get('content'):
|
||
raise ValidationError('Missing fields')
|
||
ann = Announcement(
|
||
title=data['title'],
|
||
content=data['content'],
|
||
is_active=bool(data.get('is_active', True)),
|
||
)
|
||
db.session.add(ann)
|
||
db.session.commit()
|
||
return {'message': 'Created', 'id': ann.id}
|
||
|
||
|
||
def update_announcement(announcement_id: int, data: dict[str, Any]) -> dict:
|
||
"""
|
||
更新公告 title/content(及可选 is_active)。
|
||
Raises:
|
||
NotFoundError: 公告不存在。
|
||
ValidationError: title/content 缺失。
|
||
"""
|
||
if not data.get('title') or not data.get('content'):
|
||
raise ValidationError('Missing fields')
|
||
ann = db.session.get(Announcement, announcement_id)
|
||
if not ann:
|
||
raise NotFoundError('Not found')
|
||
ann.title = data['title']
|
||
ann.content = data['content']
|
||
if 'is_active' in data:
|
||
ann.is_active = bool(data['is_active'])
|
||
db.session.commit()
|
||
return {'message': 'Updated'}
|
||
|
||
|
||
def delete_announcement(announcement_id: int) -> dict:
|
||
"""删除公告(不存在时静默成功)。"""
|
||
ann = db.session.get(Announcement, announcement_id)
|
||
if ann:
|
||
db.session.delete(ann)
|
||
db.session.commit()
|
||
return {'message': 'Deleted'}
|