from app.api.v1.module_rule.rule.crud import RuleCRUD from app.core.base_schema import AuthSchema from app.core.exceptions import CustomException from .crud import ChapterCRUD from .schema import ChapterOutSchema, ChapterQueryParam, ChapterCreateSchema, ChapterUpdateSchema class ChapterService: """能源报告章节服务。""" def __init__(self, auth: AuthSchema) -> None: self.auth = auth async def detail(self, id: int) -> ChapterOutSchema: chapter = await ChapterCRUD(self.auth).get_or_404(id=id) return self._to_out_schema(chapter) async def list_by_template(self, template_id: int) -> list[ChapterOutSchema]: chapters = await ChapterCRUD(self.auth).get_list( search={"template_id": template_id}, order_by=[{"chapter_order": "asc"}, {"id": "asc"}], ) return [self._to_out_schema(chapter) for chapter in chapters] async def page( self, page_no: int, page_size: int, search: ChapterQueryParam | None = None, order_by: list[dict[str, str]] | None = None, ) -> dict: offset = (page_no - 1) * page_size page_result = await ChapterCRUD(self.auth).page( offset=offset, limit=page_size, order_by=order_by or [{"chapter_order": "asc"}, {"id": "asc"}], search=vars(search) if search else None, out_schema=ChapterOutSchema, ) for item in page_result.items: rule_info = item.get("rule") or {} item["rule_name"] = rule_info.get("name") return page_result async def create(self, data: ChapterCreateSchema) -> ChapterOutSchema: await self._validate_rule(rule_id=data.rule_id) chapter = await ChapterCRUD(self.auth).create(data=data) return self._to_out_schema(chapter) async def update(self, id: int, data: ChapterUpdateSchema) -> ChapterOutSchema: await ChapterCRUD(self.auth).get_or_404(id=id, msg="更新失败,章节标注不存在") await self._validate_rule(rule_id=data.rule_id) chapter = await ChapterCRUD(self.auth).update(id=id, data=data) return self._to_out_schema(chapter) async def delete(self, ids: list[int]) -> None: if len(ids) < 1: raise CustomException(msg="删除失败,删除对象不能为空") chapters = await ChapterCRUD(self.auth).get_list(search={"id": ("in", ids)}) chapter_map = {chapter.id: chapter for chapter in chapters} for chapter_id in ids: if chapter_id not in chapter_map: raise CustomException(msg="删除失败,章节标注不存在") await ChapterCRUD(self.auth).delete(ids=ids) def _to_out_schema(self, chapter) -> ChapterOutSchema: chapter_out = ChapterOutSchema.model_validate(chapter) if hasattr(chapter, "rule") and chapter.rule: chapter_out.rule_name = chapter.rule.name return chapter_out async def _validate_rule(self, rule_id: int) -> None: rule = await RuleCRUD(self.auth).get(id=rule_id) if not rule: raise CustomException(msg="关联规则不存在")