273 lines
12 KiB
Python
273 lines
12 KiB
Python
from typing import Any
|
|
|
|
from fastapi import UploadFile
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.base_schema import AuthSchema, PageResultSchema, ImportResultSchema
|
|
from app.core.base_crud import assert_parents_exist
|
|
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 BreedingCloneCRUD
|
|
from .model import CloneModel
|
|
from .schema import (
|
|
CloneCreateSchema,
|
|
CloneOutSchema,
|
|
CloneQueryParam,
|
|
CloneUpdateSchema,
|
|
)
|
|
from app.api.v1.module_bre.cross_combination.model import CrossCombinationModel
|
|
from app.api.v1.module_bre.cross_combination.crud import BreedingCrossCombinationCRUD
|
|
from app.api.v1.module_bre.germplasm.model import BreedingGermplasmModel
|
|
from app.api.v1.module_bre.germplasm.crud import BreedingGermplasmCRUD
|
|
|
|
|
|
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 CloneService:
|
|
"""无性系管理 模块服务层"""
|
|
|
|
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
|
self.auth = auth
|
|
self.db = db
|
|
|
|
async def _check_code(self, code: str, exclude_id: int | None = None) -> None:
|
|
if _is_blank(code):
|
|
raise CustomException(msg="无性系编号不能为空")
|
|
conditions = [CloneModel.clone_code == code.strip(), CloneModel.is_deleted.is_(False)]
|
|
if exclude_id is not None:
|
|
conditions.append(CloneModel.id != exclude_id)
|
|
result = await self.db.execute(select(func.count()).select_from(CloneModel).where(*conditions))
|
|
if result.scalar() or 0:
|
|
raise CustomException(msg=f"无性系编号 {code} 已存在", status_code=409)
|
|
|
|
async def _check_parents(self, data: CloneCreateSchema | CloneUpdateSchema) -> None:
|
|
checks: list[tuple[Any, Any, str]] = [
|
|
(CrossCombinationModel, data.combination_id, '杂交组合'),
|
|
]
|
|
if getattr(data, "female_parent_id", None):
|
|
checks.append((BreedingGermplasmModel, data.female_parent_id, '母本种质'))
|
|
if getattr(data, "male_parent_id", None):
|
|
checks.append((BreedingGermplasmModel, data.male_parent_id, '父本种质'))
|
|
await assert_parents_exist(self.db, checks)
|
|
|
|
async def _attach_fk_labels(self, items: list[CloneOutSchema]) -> None:
|
|
if not items:
|
|
return
|
|
crud = BreedingCloneCRUD(self.auth, self.db)
|
|
combination_ids = {getattr(it, "combination_id") for it in items if getattr(it, "combination_id")}
|
|
if combination_ids:
|
|
refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(search={"id": ("in", list(combination_ids))})
|
|
ref_map = {r.id: getattr(r, "combination_code") for r in refs}
|
|
for it in items:
|
|
it.combination_name = ref_map.get(getattr(it, "combination_id"))
|
|
germ_ids = {
|
|
g for it in items
|
|
for g in (getattr(it, "female_parent_id"), getattr(it, "male_parent_id"))
|
|
if g
|
|
}
|
|
if germ_ids:
|
|
germ_map = {
|
|
r.id: getattr(r, "cultivar_name")
|
|
for r in await BreedingGermplasmCRUD(self.auth, self.db).get_list(search={"id": ("in", list(germ_ids))})
|
|
}
|
|
for it in items:
|
|
it.female_parent_name = germ_map.get(getattr(it, "female_parent_id"))
|
|
it.male_parent_name = germ_map.get(getattr(it, "male_parent_id"))
|
|
|
|
async def detail(self, id: int) -> CloneOutSchema:
|
|
obj = await BreedingCloneCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="该无性系不存在")
|
|
out = CloneOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def get_list(
|
|
self,
|
|
search: CloneQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> list[CloneOutSchema]:
|
|
obj_list = await BreedingCloneCRUD(self.auth, self.db).get_list(
|
|
search=search_to_dict(search), order_by=order_by
|
|
)
|
|
outs = [CloneOutSchema.model_validate(obj) for obj in obj_list]
|
|
await self._attach_fk_labels(outs)
|
|
return outs
|
|
|
|
async def page(
|
|
self,
|
|
page_no: int,
|
|
page_size: int,
|
|
search: CloneQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> PageResultSchema[CloneOutSchema]:
|
|
offset = (page_no - 1) * page_size
|
|
result = await BreedingCloneCRUD(self.auth, self.db).page(
|
|
offset=offset,
|
|
limit=page_size,
|
|
order_by=order_by or [{"id": "asc"}],
|
|
search=search_to_dict(search, {}),
|
|
out_schema=CloneOutSchema,
|
|
)
|
|
await self._attach_fk_labels(result.items)
|
|
return result
|
|
|
|
async def create(self, data: CloneCreateSchema) -> CloneOutSchema:
|
|
await self._check_code(data.clone_code)
|
|
await self._check_parents(data)
|
|
obj = await BreedingCloneCRUD(self.auth, self.db).create(data=data)
|
|
out = CloneOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def update(self, id: int, data: CloneUpdateSchema) -> CloneOutSchema:
|
|
obj = await BreedingCloneCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="更新失败,该无性系不存在")
|
|
if not _is_blank(data.clone_code):
|
|
await self._check_code(data.clone_code, exclude_id=id)
|
|
await self._check_parents(data)
|
|
obj = await BreedingCloneCRUD(self.auth, self.db).update(id=id, data=data)
|
|
out = CloneOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def delete(self, ids: list[int]) -> None:
|
|
if not ids:
|
|
raise CustomException(msg="删除失败,删除对象不能为空")
|
|
objs = await BreedingCloneCRUD(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 BreedingCloneCRUD(self.auth, self.db).delete(ids=ids)
|
|
|
|
async def list_options(self) -> list[dict[str, Any]]:
|
|
"""供前端下拉选择使用:返回 [{value, label}]。"""
|
|
obj_list = await BreedingCloneCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
return [{"value": o.id, "label": o.clone_code} for o in obj_list]
|
|
|
|
@staticmethod
|
|
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
|
|
mapping_dict = {
|
|
"combination_name": "来源杂交组合",
|
|
"clone_code": "无性系编号",
|
|
"female_parent_name": "母本种质",
|
|
"male_parent_name": "父本种质",
|
|
"planting_year": "定植年份",
|
|
"generation": "世代",
|
|
"status": "状态",
|
|
"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 = {
|
|
"来源杂交组合": "combination_id",
|
|
"无性系编号": "clone_code",
|
|
"母本种质": "female_parent_id",
|
|
"父本种质": "male_parent_id",
|
|
"定植年份": "planting_year",
|
|
"世代": "generation",
|
|
"状态": "status",
|
|
"备注": "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)}")
|
|
combination_id_refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
combination_id_map = {getattr(r, "combination_code"): r.id for r in combination_id_refs}
|
|
germ_refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
germ_map = {getattr(r, "cultivar_name"): r.id for r in germ_refs}
|
|
mapped_rows = []
|
|
for row in rows:
|
|
mapped_rows.append({en: row.get(ch) for ch, en in header_dict.items()})
|
|
required_fields = ["combination_id", "clone_code"]
|
|
errors = []
|
|
for field in required_fields:
|
|
missing_indices = [i + 1 for i, r in enumerate(mapped_rows) if _is_blank(r.get(field))]
|
|
if missing_indices:
|
|
field_name = next(k for k, v in header_dict.items() if v == field)
|
|
rows_str = "、".join(str(i) for i in missing_indices)
|
|
errors.append(f"{field_name}不能为空,第{rows_str}行")
|
|
if errors:
|
|
raise CustomException(msg=f"导入失败,以下行缺少必要字段:\n{'; '.join(errors)}")
|
|
error_msgs: list[str] = []
|
|
success_count = 0
|
|
crud = BreedingCloneCRUD(self.auth, self.db)
|
|
for i, row in enumerate(mapped_rows, start=1):
|
|
try:
|
|
combination_id_val = combination_id_map.get(str(row.get("combination_id")).strip()) if not _is_blank(row.get("combination_id")) else None
|
|
female_val = germ_map.get(str(row.get("female_parent_id")).strip()) if not _is_blank(row.get("female_parent_id")) else None
|
|
male_val = germ_map.get(str(row.get("male_parent_id")).strip()) if not _is_blank(row.get("male_parent_id")) else None
|
|
fields = {
|
|
"combination_id": combination_id_val,
|
|
"clone_code": _none_if_blank(row.get("clone_code")),
|
|
"female_parent_id": female_val,
|
|
"male_parent_id": male_val,
|
|
"planting_year": _none_if_blank(row.get("planting_year")),
|
|
"generation": _none_if_blank(row.get("generation")),
|
|
"status": _none_if_blank(row.get("status")) or "1",
|
|
"remark": _none_if_blank(row.get("remark")),
|
|
}
|
|
create_data = CloneCreateSchema(**fields)
|
|
await self._check_code(create_data.clone_code)
|
|
await self._check_parents(create_data)
|
|
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 = [
|
|
"来源杂交组合",
|
|
"无性系编号",
|
|
"母本种质",
|
|
"父本种质",
|
|
"定植年份",
|
|
"世代",
|
|
"状态",
|
|
"备注",
|
|
]
|
|
selector_header_list = []
|
|
option_list = []
|
|
return ExcelUtil.get_excel_template(
|
|
header_list=header_list,
|
|
selector_header_list=selector_header_list,
|
|
option_list=option_list,
|
|
)
|