init: 初始化 dpb 桃育种系统代码库

前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
This commit is contained in:
34047007@qq.com
2026-08-06 00:17:49 +08:00
commit b95053c52c
1469 changed files with 322298 additions and 0 deletions
@@ -0,0 +1,274 @@
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.dict_util import DictLabelResolver, dict_value_to_label
from app.utils.excel_util import ExcelUtil
from .crud import BreedingTrialStudyCRUD
from .schema import (
TrialStudyCreateSchema,
TrialStudyOutSchema,
TrialStudyQueryParam,
TrialStudyUpdateSchema,
)
from app.api.v1.module_bre.trial.crud import BreedingTrialCRUD
from app.core.base_crud import assert_no_children, assert_parents_exist
from app.api.v1.module_bre.site.model import BreedingSiteModel
from app.api.v1.module_bre.treatment.model import TreatmentModel
from app.api.v1.module_bre.trial.model import TrialModel
from app.api.v1.module_bre.trial_study_entry.model import TrialStudyEntryModel
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 TrialStudyService:
"""试验执行 模块服务层"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
async def _attach_fk_labels(self, items: list[TrialStudyOutSchema]) -> None:
if not items:
return
crud = BreedingTrialStudyCRUD(self.auth, self.db)
trial_id_ids = {getattr(it, "trial_id") for it in items if getattr(it, "trial_id")}
if trial_id_ids:
refs = await BreedingTrialCRUD(self.auth, self.db).get_list(search={"id": ("in", list(trial_id_ids))})
ref_map = {r.id: getattr(r, "trial_name") for r in refs}
for it in items:
it.trial_name = ref_map.get(getattr(it, "trial_id"))
async def detail(self, id: int) -> TrialStudyOutSchema:
obj = await BreedingTrialStudyCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="该试验执行不存在")
out = TrialStudyOutSchema.model_validate(obj)
await self._attach_fk_labels([out])
return out
async def get_list(
self,
search: TrialStudyQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> list[TrialStudyOutSchema]:
obj_list = await BreedingTrialStudyCRUD(self.auth, self.db).get_list(
search=search_to_dict(search), order_by=order_by
)
outs = [TrialStudyOutSchema.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: TrialStudyQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> PageResultSchema[TrialStudyOutSchema]:
offset = (page_no - 1) * page_size
result = await BreedingTrialStudyCRUD(self.auth, self.db).page(
offset=offset,
limit=page_size,
order_by=order_by or [{"id": "asc"}],
search=search_to_dict(search, {}),
out_schema=TrialStudyOutSchema,
)
await self._attach_fk_labels(result.items)
return result
async def create(self, data: TrialStudyCreateSchema) -> TrialStudyOutSchema:
await assert_parents_exist(
self.db,
[
(TrialModel, data.trial_id, '试验项目'),
(BreedingSiteModel, data.site_id, '试验基地'),
],
)
obj = await BreedingTrialStudyCRUD(self.auth, self.db).create(data=data)
out = TrialStudyOutSchema.model_validate(obj)
await self._attach_fk_labels([out])
return out
async def update(self, id: int, data: TrialStudyUpdateSchema) -> TrialStudyOutSchema:
obj = await BreedingTrialStudyCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="更新失败,该试验执行不存在")
await assert_parents_exist(
self.db,
[
(TrialModel, data.trial_id, '试验项目'),
(BreedingSiteModel, data.site_id, '试验基地'),
],
)
obj = await BreedingTrialStudyCRUD(self.auth, self.db).update(id=id, data=data)
out = TrialStudyOutSchema.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 BreedingTrialStudyCRUD(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 assert_no_children(
self.db,
ids,
[
(TrialStudyEntryModel, 'trial_study_id', '试验参试'),
(TreatmentModel, 'trial_study_id', '试验处理'),
],
)
await BreedingTrialStudyCRUD(self.auth, self.db).delete(ids=ids)
async def list_options(self) -> list[dict[str, Any]]:
"""供前端下拉选择使用:返回 [{value, label}]。"""
obj_list = await BreedingTrialStudyCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
return [{"value": o.id, "label": o.study_name} for o in obj_list]
@staticmethod
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
mapping_dict = {
"trial_name": "所属试验",
"study_name": "研究点名称",
"site_id": "基地ID",
"year": "年份",
"block_count": "区组数",
"season": "季节",
"design_type": "设计类型",
"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 "未知"
item["design_type"] = dict_value_to_label("breeding_design_type", item.get("design_type"))
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 = {
"所属试验": "trial_id",
"研究点名称": "study_name",
"基地ID": "site_id",
"年份": "year",
"区组数": "block_count",
"季节": "season",
"设计类型": "design_type",
"备注": "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)}")
trial_id_refs = await BreedingTrialCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
trial_id_map = {getattr(r, "trial_name"): r.id for r in trial_id_refs}
mapped_rows = []
for row in rows:
mapped_rows.append({en: row.get(ch) for ch, en in header_dict.items()})
required_fields = ["trial_id", "study_name"]
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 = BreedingTrialStudyCRUD(self.auth, self.db)
resolver = DictLabelResolver(self.auth, self.db, ["breeding_design_type"])
for i, row in enumerate(mapped_rows, start=1):
try:
trial_id_val = trial_id_map.get(str(row.get("trial_id")).strip()) if not _is_blank(row.get("trial_id")) else None
fields = {
"trial_id": trial_id_val,
"study_name": _none_if_blank(row.get("study_name")),
"site_id": _to_int(row.get("site_id")),
"year": _to_int(row.get("year")),
"block_count": _to_int(row.get("block_count")),
"season": _none_if_blank(row.get("season")),
"design_type": await resolver.resolve("breeding_design_type", row.get("design_type")),
"remark": _none_if_blank(row.get("remark")),
}
create_data = TrialStudyCreateSchema(**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 = [
"所属试验",
"研究点名称",
"基地ID",
"年份",
"区组数",
"季节",
"设计类型",
"备注",
]
selector_header_list = ["设计类型"]
option_list = [
{"设计类型": ["rcbd", "augmented", "contrast", "split_plot", "unreplicated"]},
]
return ExcelUtil.get_excel_template(
header_list=header_list,
selector_header_list=selector_header_list,
option_list=option_list,
)