"""会话用例。""" from __future__ import annotations import uuid from datetime import datetime from domain.models import Actor, Session, SessionStatus from domain.ports import SessionRepository class SessionService: def __init__(self, sessions: SessionRepository) -> None: self._sessions = sessions async def create(self, actor: Actor, title: str | None = None) -> Session: now = datetime.utcnow() session = Session( thread_id=str(uuid.uuid4()), company_id=actor.company_id, user_id=actor.user_id, title=(title or "新对话").strip() or "新对话", status=SessionStatus.ACTIVE, created_at=now, updated_at=now, ) return await self._sessions.create(session) async def list_mine(self, actor: Actor) -> list[Session]: return await self._sessions.list_active(actor.company_id, actor.user_id) async def require_owned(self, actor: Actor, thread_id: str) -> Session: session = await self._sessions.get(actor.company_id, actor.user_id, thread_id) if session is None or session.status == SessionStatus.DELETED: raise LookupError("会话不存在") return session async def rename(self, actor: Actor, thread_id: str, title: str) -> Session: session = await self.require_owned(actor, thread_id) session.title = title.strip() or session.title return await self._sessions.update(session) async def archive(self, actor: Actor, thread_id: str) -> Session: session = await self.require_owned(actor, thread_id) session.status = SessionStatus.ARCHIVED return await self._sessions.update(session)