301 lines
14 KiB
Plaintext
301 lines
14 KiB
Plaintext
from typing import Any
|
|
|
|
from fastapi import UploadFile
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.base_schema import AuthSchema, PageResultSchema
|
|
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 BreedingTreeCRUD
|
|
from .schema import (
|
|
TreeCreateSchema,
|
|
TreeOutSchema,
|
|
TreeQueryParam,
|
|
TreeUpdateSchema,
|
|
)
|
|
from app.api.v1.module_bre.cross_combination.crud import BreedingCrossCombinationCRUD
|
|
from app.api.v1.module_bre.site.crud import BreedingPlotCRUD
|
|
from app.api.v1.module_bre.personnel.crud import BreedingPersonnelCRUD
|
|
from app.api.v1.module_bre.planting.crud import BreedingPlantingCRUD
|
|
|
|
|
|
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
|
|
|
|
|
|
def _to_float(v: Any) -> float | None:
|
|
if _is_blank(v):
|
|
return None
|
|
try:
|
|
return float(v)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _to_int(v: Any) -> int | None:
|
|
if _is_blank(v):
|
|
return None
|
|
try:
|
|
return int(float(v))
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
class TreeService:
|
|
"""育种单株 模块服务层"""
|
|
|
|
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
|
self.auth = auth
|
|
self.db = db
|
|
|
|
async def _attach_fk_labels(self, items: list[TreeOutSchema]) -> None:
|
|
if not items:
|
|
return
|
|
crud = BreedingTreeCRUD(self.auth, self.db)
|
|
combination_id_ids = {getattr(it, "combination_id") for it in items if getattr(it, "combination_id")}
|
|
if combination_id_ids:
|
|
refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(search={"id": ("in", list(combination_id_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"))
|
|
plot_id_ids = {getattr(it, "plot_id") for it in items if getattr(it, "plot_id")}
|
|
if plot_id_ids:
|
|
refs = await BreedingPlotCRUD(self.auth, self.db).get_list(search={"id": ("in", list(plot_id_ids))})
|
|
ref_map = {r.id: getattr(r, "plot_code") for r in refs}
|
|
for it in items:
|
|
it.plot_name = ref_map.get(getattr(it, "plot_id"))
|
|
bre_personnel_id_ids = {getattr(it, "bre_personnel_id") for it in items if getattr(it, "bre_personnel_id")}
|
|
if bre_personnel_id_ids:
|
|
refs = await BreedingPersonnelCRUD(self.auth, self.db).get_list(search={"id": ("in", list(bre_personnel_id_ids))})
|
|
ref_map = {r.id: getattr(r, "name") for r in refs}
|
|
for it in items:
|
|
it.bre_personnel_name = ref_map.get(getattr(it, "bre_personnel_id"))
|
|
planting_id_ids = {getattr(it, "planting_id") for it in items if getattr(it, "planting_id")}
|
|
if planting_id_ids:
|
|
refs = await BreedingPlantingCRUD(self.auth, self.db).get_list(search={"id": ("in", list(planting_id_ids))})
|
|
ref_map = {r.id: (getattr(r, "batch_no") or getattr(r, "sowing_date") or f"定植#{r.id}") for r in refs}
|
|
for it in items:
|
|
it.planting_name = ref_map.get(getattr(it, "planting_id"))
|
|
|
|
async def detail(self, id: int) -> TreeOutSchema:
|
|
obj = await BreedingTreeCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="该育种单株不存在")
|
|
out = TreeOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def get_list(
|
|
self,
|
|
search: TreeQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> list[TreeOutSchema]:
|
|
obj_list = await BreedingTreeCRUD(self.auth, self.db).get_list(
|
|
search=search_to_dict(search), order_by=order_by
|
|
)
|
|
outs = [TreeOutSchema.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: TreeQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> PageResultSchema[TreeOutSchema]:
|
|
offset = (page_no - 1) * page_size
|
|
result = await BreedingTreeCRUD(self.auth, self.db).page(
|
|
offset=offset,
|
|
limit=page_size,
|
|
order_by=order_by or [{"id": "asc"}],
|
|
search=search_to_dict(search, {}),
|
|
out_schema=TreeOutSchema,
|
|
)
|
|
await self._attach_fk_labels(result.items)
|
|
return result
|
|
|
|
async def create(self, data: TreeCreateSchema) -> TreeOutSchema:
|
|
exist_obj = await BreedingTreeCRUD(self.auth, self.db).get(tree_no=data.tree_no)
|
|
if exist_obj:
|
|
raise CustomException(msg="创建失败,单株编号已存在")
|
|
obj = await BreedingTreeCRUD(self.auth, self.db).create(data=data)
|
|
out = TreeOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def update(self, id: int, data: TreeUpdateSchema) -> TreeOutSchema:
|
|
obj = await BreedingTreeCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="更新失败,该育种单株不存在")
|
|
if data.tree_no is not None:
|
|
exist_obj = await BreedingTreeCRUD(self.auth, self.db).get(tree_no=data.tree_no)
|
|
if exist_obj and exist_obj.id != id:
|
|
raise CustomException(msg="更新失败,单株编号重复")
|
|
obj = await BreedingTreeCRUD(self.auth, self.db).update(id=id, data=data)
|
|
out = TreeOutSchema.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 BreedingTreeCRUD(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 BreedingTreeCRUD(self.auth, self.db).delete(ids=ids)
|
|
|
|
async def list_options(self) -> list[dict[str, Any]]:
|
|
"""供前端下拉选择使用:返回 [{value, label}]。"""
|
|
obj_list = await BreedingTreeCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
return [{"value": o.id, "label": o.tree_no} for o in obj_list]
|
|
|
|
@staticmethod
|
|
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
|
|
mapping_dict = {
|
|
"combination_name": "杂交组合",
|
|
"plot_name": "试验地块/位置",
|
|
"planting_name": "来源定植批次",
|
|
"tree_no": "单株编号",
|
|
"row_orientation": "行向",
|
|
"row_no": "行数",
|
|
"col_no": "列数",
|
|
"planted_date": "定植时间",
|
|
"bre_personnel_name": "责任人",
|
|
"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) -> str:
|
|
header_dict = {
|
|
"杂交组合": "combination_id",
|
|
"试验地块/位置": "plot_id",
|
|
"来源定植批次": "planting_id",
|
|
"单株编号": "tree_no",
|
|
"行向": "row_orientation",
|
|
"行数": "row_no",
|
|
"列数": "col_no",
|
|
"定植时间": "planted_date",
|
|
"责任人": "bre_personnel_id",
|
|
"状态": "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}
|
|
plot_id_refs = await BreedingPlotCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
plot_id_map = {getattr(r, "plot_code"): r.id for r in plot_id_refs}
|
|
bre_personnel_id_refs = await BreedingPersonnelCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
bre_personnel_id_map = {getattr(r, "name"): r.id for r in bre_personnel_id_refs}
|
|
planting_id_refs = await BreedingPlantingCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
planting_id_map = {str(getattr(r, "batch_no") or getattr(r, "sowing_date") or r.id): r.id for r in planting_id_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", "tree_no"]
|
|
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 = BreedingTreeCRUD(self.auth, self.db)
|
|
for i, row in enumerate(mapped_rows, start=1):
|
|
try:
|
|
combination_id_val = combination_id_map.get(str(row.get("杂交组合")).strip()) if not _is_blank(row.get("杂交组合")) else None
|
|
plot_id_val = plot_id_map.get(str(row.get("试验地块/位置")).strip()) if not _is_blank(row.get("试验地块/位置")) else None
|
|
planting_id_val = planting_id_map.get(str(row.get("来源定植批次")).strip()) if not _is_blank(row.get("来源定植批次")) else None
|
|
bre_personnel_id_val = bre_personnel_id_map.get(str(row.get("责任人")).strip()) if not _is_blank(row.get("责任人")) else None
|
|
fields = {
|
|
"combination_id": combination_id_val,
|
|
"plot_id": plot_id_val,
|
|
"planting_id": planting_id_val,
|
|
"tree_no": _none_if_blank(row.get("tree_no")),
|
|
"row_orientation": _none_if_blank(row.get("row_orientation")),
|
|
"row_no": _to_int(row.get("row_no")),
|
|
"col_no": _to_int(row.get("col_no")),
|
|
"planted_date": _none_if_blank(row.get("planted_date")),
|
|
"bre_personnel_id": bre_personnel_id_val,
|
|
"status": _none_if_blank(row.get("status")),
|
|
"remark": _none_if_blank(row.get("remark")),
|
|
}
|
|
unique_kwargs = {"tree_no": fields["tree_no"]}
|
|
create_data = TreeCreateSchema(**fields)
|
|
exist_obj = await crud.get(**unique_kwargs)
|
|
if exist_obj:
|
|
if update_support:
|
|
await crud.update(id=exist_obj.id, data=TreeUpdateSchema(**fields))
|
|
success_count += 1
|
|
else:
|
|
error_msgs.append(f"第{i}行: 单株编号 {fields['tree_no']} 已存在")
|
|
else:
|
|
await crud.create(data=create_data)
|
|
success_count += 1
|
|
except Exception as e:
|
|
error_msgs.append(f"第{i}行: {e!s}")
|
|
continue
|
|
result = f"成功导入 {success_count} 条数据"
|
|
if error_msgs:
|
|
result += "\n错误信息:\n" + "\n".join(error_msgs)
|
|
return result
|
|
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,
|
|
)
|