"""Character profile service.""" from __future__ import annotations from typing import Any from uuid import uuid4 from backend.dto.common import ApiError, ErrorCode from backend.dto.profile_dto import CharacterProfile, ProfileListResult from core.audit_service import AuditService from core.identity import RequestContext from core.security import can_access_owned_resource from database.repositories.profile_repository import ProfileRepository VISUAL_PROFILE_FIELDS = { "base_prompt", "appearance_prompt", "style_prompt", "negative_prompt", "avatar_image_uri", } class ProfileService: def __init__( self, repository: ProfileRepository, audit_service: AuditService, ): self.repository = repository self.audit_service = audit_service def create_profile(self, payload: dict[str, Any], ctx: RequestContext) -> CharacterProfile: self._validate_create_payload(payload) # Ownership comes from the authenticated caller. Accepting an # arbitrary owner_user_id would allow cross-tenant profile creation. owner_user_id = ctx.actor_id if not owner_user_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "缺少角色档案归属用户", {"field": "owner_user_id"}, ) profile_payload = { "profile_id": payload.get("profile_id") or new_profile_id(), "name": payload["name"].strip(), "description": payload.get("description"), "base_prompt": payload.get("base_prompt"), "appearance_prompt": payload.get("appearance_prompt"), "style_prompt": payload.get("style_prompt"), "negative_prompt": payload.get("negative_prompt"), "default_model_route": payload.get("default_model_route"), "owner_platform": payload.get("owner_platform") or ctx.platform, "owner_context_id": payload.get("owner_context_id"), "owner_user_id": owner_user_id, "owner_session_key": payload.get("owner_session_key") or ctx.session_key, "avatar_image_uri": payload.get("avatar_image_uri"), "status": payload.get("status", "active"), "metadata": payload.get("metadata") or {}, } profile = self.repository.create(profile_payload) self.audit_service.record( ctx=ctx, action="create_profile", target_type="character_profile", target_id=profile.profile_id, after_snapshot=profile.to_dict(), ) return profile def get_profile(self, profile_id: str, ctx: RequestContext | None = None) -> CharacterProfile: profile = self.repository.get(profile_id) if profile is None or profile.status == "deleted": raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "角色档案不存在", {"profile_id": profile_id}, ) if ctx is not None: self._require_owner(profile, ctx) return profile def list_profiles( self, *, ctx: RequestContext, keyword: str | None = None, status: str | None = "active", page: int = 1, page_size: int = 30, ) -> ProfileListResult: return self.repository.list( owner_user_id=ctx.actor_id, keyword=keyword, status=status, page=max(page, 1), page_size=min(max(page_size, 1), 100), ) def update_profile( self, profile_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> CharacterProfile: before = self.get_profile(profile_id, ctx) if "name" in payload and not str(payload["name"]).strip(): raise ApiError(ErrorCode.VALIDATION_FAILED, "角色名称不能为空", {"field": "name"}) update_payload = dict(payload) if before.profile_category == "profile_card" or bool((before.metadata or {}).get("visual_identity_locked")): blocked = sorted(VISUAL_PROFILE_FIELDS.intersection(update_payload)) if blocked: raise ApiError( ErrorCode.FORBIDDEN, "sealed profile cards only allow non-visual persona edits", {"blocked_fields": blocked, "profile_id": profile_id}, ) if "name" in update_payload: update_payload["name"] = str(update_payload["name"]).strip() after = self.repository.update(profile_id, update_payload) if after is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "角色档案不存在", {"profile_id": profile_id}, ) self.audit_service.record( ctx=ctx, action="update_profile", target_type="character_profile", target_id=profile_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) return after def archive_profile(self, profile_id: str, ctx: RequestContext) -> CharacterProfile: """Retire a profile without destroying it. Archiving deliberately keeps the row readable through ``get_profile`` so the action stays reversible (flip ``status`` back to ``active``); the default ``list_profiles`` filter is ``active``, so an archived profile still leaves the library view. Writing ``status`` through the repository rather than ``update_profile`` avoids the sealed-card visual field guard, which has no bearing on retiring a profile. """ before = self.get_profile(profile_id, ctx) after = self.repository.update(profile_id, {"status": "archived"}) if after is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "角色档案不存在", {"profile_id": profile_id}, ) self.audit_service.record( ctx=ctx, action="archive_profile", target_type="character_profile", target_id=profile_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) return after def delete_profile(self, profile_id: str, ctx: RequestContext) -> CharacterProfile: before = self.get_profile(profile_id, ctx) after = self.repository.soft_delete(profile_id) if after is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "角色档案不存在", {"profile_id": profile_id}, ) self.audit_service.record( ctx=ctx, action="delete_profile", target_type="character_profile", target_id=profile_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) return after def _validate_create_payload(self, payload: dict[str, Any]) -> None: name = str(payload.get("name") or "").strip() if not name: raise ApiError(ErrorCode.VALIDATION_FAILED, "角色名称不能为空", {"field": "name"}) def _require_owner(self, profile: CharacterProfile, ctx: RequestContext) -> None: # Delegates to the shared predicate so this path honours # ``can_manage_all_profiles`` exactly like ResourceAccessService does; # the two used to disagree about administrators. if can_access_owned_resource(profile.owner_user_id, ctx): return # Use not-found semantics so guessed resource IDs cannot enumerate # another user's profiles. raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "角色档案不存在", {"profile_id": profile.profile_id}, ) def new_profile_id() -> str: return f"profile_{uuid4().hex}"