from typing import Any from fastapi import UploadFile from sqlalchemy.ext.asyncio import AsyncSession from app.core.base_schema import AuthSchema, PageResultSchema, ImportResultSchema from app.core.exceptions import CustomException from app.core.logger import logger from app.utils.common_util import search_to_dict from app.utils.excel_util import ExcelUtil from .crud import BreedingRootstockCRUD from .schema import ( RootstockCreateSchema, RootstockOutSchema, RootstockQueryParam, RootstockUpdateSchema, ) def _is_blank(v: Any) -> bool: return v is None or (isinstance(v, str) and v.strip() == "") def _none_if_blank(v: Any) -> Any: if _is_blank(v): return None return str(v).strip() if isinstance(v, str) else v class RootstockService: """砧木管理 模块服务层""" def __init__(self, auth: AuthSchema, db: AsyncSession) -> None: self.auth = auth self.db = db async def detail(self, id: int) -> RootstockOutSchema: obj = await BreedingRootstockCRUD(self.auth, self.db).get(id=id) if not obj: raise CustomException(msg="该砧木不存在") return RootstockOutSchema.model_validate(obj) async def get_list( self, search: RootstockQueryParam | None = None, order_by: list[dict[str, str]] | None = None, ) -> list[RootstockOutSchema]: obj_list = await BreedingRootstockCRUD(self.auth, self.db).get_list( search=search_to_dict(search), order_by=order_by ) return [RootstockOutSchema.model_validate(obj) for obj in obj_list] async def page( self, page_no: int, page_size: int, search: RootstockQueryParam | None = None, order_by: list[dict[str, str]] | None = None, ) -> PageResultSchema[RootstockOutSchema]: offset = (page_no - 1) * page_size return await BreedingRootstockCRUD(self.auth, self.db).page( offset=offset, limit=page_size, order_by=order_by or [{"id": "asc"}], search=search_to_dict(search, {}), out_schema=RootstockOutSchema, ) async def create(self, data: RootstockCreateSchema) -> RootstockOutSchema: if _is_blank(data.rootstock_name): raise CustomException(msg="砧木名称不能为空") obj = await BreedingRootstockCRUD(self.auth, self.db).create(data=data) return RootstockOutSchema.model_validate(obj) async def update(self, id: int, data: RootstockUpdateSchema) -> RootstockOutSchema: obj = await BreedingRootstockCRUD(self.auth, self.db).get(id=id) if not obj: raise CustomException(msg="更新失败,该砧木不存在") obj = await BreedingRootstockCRUD(self.auth, self.db).update(id=id, data=data) return RootstockOutSchema.model_validate(obj) async def delete(self, ids: list[int]) -> None: if not ids: raise CustomException(msg="删除失败,删除对象不能为空") objs = await BreedingRootstockCRUD(self.auth, self.db).get_list(search={"id": ("in", ids)}) obj_map = {o.id: o for o in objs} for id_ in ids: if id_ not in obj_map: raise CustomException(msg="删除失败,该砧木不存在") await BreedingRootstockCRUD(self.auth, self.db).delete(ids=ids) async def list_options(self) -> list[dict[str, Any]]: """供前端下拉选择使用:返回 [{value, label}]。""" obj_list = await BreedingRootstockCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}]) return [{"value": o.id, "label": o.rootstock_name} for o in obj_list] @staticmethod def batch_export(obj_list: list[dict[str, Any]]) -> bytes: mapping_dict = { "rootstock_code": "砧木编号", "rootstock_name": "砧木名称", "dwarf_class": "矮化类", "compatibility": "砧穗亲和性", "remark": "备注", "created_time": "创建时间", "created_by": "创建者", } data = [dict(item) for item in obj_list] for item in data: creator = item.get("created_by") item["created_by"] = creator.get("name", "未知") if isinstance(creator, dict) else "未知" return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict) async def batch_import(self, file: UploadFile, update_support: bool = False) -> ImportResultSchema: header_dict = { "砧木编号": "rootstock_code", "砧木名称": "rootstock_name", "矮化类": "dwarf_class", "砧穗亲和性": "compatibility", "备注": "remark", } try: contents = await file.read() rows = ExcelUtil.read_excel_to_dicts(contents) await file.close() if not rows: raise CustomException(msg="导入文件为空") missing_headers = [h for h in header_dict if h not in rows[0]] if missing_headers: raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}") error_msgs: list[str] = [] success_count = 0 crud = BreedingRootstockCRUD(self.auth, self.db) for i, row in enumerate(rows, start=1): try: fields = { "rootstock_code": _none_if_blank(row.get("rootstock_code")), "rootstock_name": _none_if_blank(row.get("rootstock_name")), "dwarf_class": _none_if_blank(row.get("dwarf_class")), "compatibility": _none_if_blank(row.get("compatibility")), "remark": _none_if_blank(row.get("remark")), } create_data = RootstockCreateSchema(**fields) await crud.create(data=create_data) success_count += 1 except Exception as e: error_msgs.append(f"第{i}行: {e!s}") continue return ImportResultSchema( valid_count=success_count, invalid_count=len(error_msgs), message_list=error_msgs, ) except Exception as e: logger.error(f"批量导入砧木管理失败: {e!s}") raise CustomException(msg=f"导入失败: {e!s}") @staticmethod def import_template_download() -> bytes: header_list = [ "砧木编号", "砧木名称", "矮化类", "砧穗亲和性", "备注", ] return ExcelUtil.get_excel_template( header_list=header_list, selector_header_list=["矮化类", "砧穗亲和性"], option_list=[ {"矮化类": ["矮化", "半矮化", "乔化", "柱状", "其他"]}, {"砧穗亲和性": ["强", "中", "弱"]}, ], )