59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
"""群公告服务"""
|
|
|
|
import uuid
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.group_announcement import GroupAnnouncement
|
|
from app.services.conversation_service import ConversationService
|
|
|
|
|
|
class AnnouncementService:
|
|
def __init__(self, db: AsyncSession):
|
|
self.db = db
|
|
|
|
async def get(self, conversation_id: str) -> dict | None:
|
|
result = await self.db.execute(
|
|
select(GroupAnnouncement).where(
|
|
GroupAnnouncement.conversation_id == conversation_id
|
|
).order_by(GroupAnnouncement.updated_at.desc())
|
|
)
|
|
ann = result.scalars().first()
|
|
if not ann:
|
|
return None
|
|
return self._to_dict(ann)
|
|
|
|
async def upsert(self, conversation_id: str, author_id: str, content: str) -> dict:
|
|
# 校验管理员
|
|
conv_service = ConversationService(self.db)
|
|
await conv_service._get_conv_if_admin(conversation_id, author_id)
|
|
|
|
result = await self.db.execute(
|
|
select(GroupAnnouncement).where(GroupAnnouncement.conversation_id == conversation_id)
|
|
)
|
|
ann = result.scalars().first()
|
|
if ann:
|
|
ann.content = content
|
|
ann.author_id = author_id
|
|
ann.updated_at = datetime.utcnow()
|
|
else:
|
|
ann = GroupAnnouncement(
|
|
id=str(uuid.uuid4()),
|
|
conversation_id=conversation_id,
|
|
author_id=author_id, content=content,
|
|
)
|
|
self.db.add(ann)
|
|
await self.db.flush()
|
|
return self._to_dict(ann)
|
|
|
|
def _to_dict(self, ann: GroupAnnouncement) -> dict:
|
|
return {
|
|
"id": ann.id,
|
|
"conversation_id": ann.conversation_id,
|
|
"author_id": ann.author_id,
|
|
"content": ann.content,
|
|
"updated_at": ann.updated_at.isoformat() if ann.updated_at else None,
|
|
}
|