init: 初始化 dpb 桃育种系统代码库
前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
import urllib.parse
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, File, Path, Query, UploadFile
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.common.response import ResponseSchema, StreamResponse, SuccessResponse
|
||||
from app.core.base_schema import AuthSchema, PageResultSchema, PaginationQueryParam, ImportResultSchema
|
||||
from app.core.dependencies import AuthPermission, db_getter
|
||||
from app.core.router_class import OperationLogRoute
|
||||
from app.utils.common_util import bytes2file_response
|
||||
|
||||
from .schema import (
|
||||
CrossCombinationCreateSchema,
|
||||
CrossCombinationOutSchema,
|
||||
CrossCombinationQueryParam,
|
||||
CrossCombinationUpdateSchema,
|
||||
)
|
||||
from .service import CrossCombinationService
|
||||
|
||||
CrossCombinationRouter = APIRouter(route_class=OperationLogRoute, prefix="/cross_combination", tags=["杂交组合"])
|
||||
|
||||
|
||||
@CrossCombinationRouter.get("/detail/{id}", summary="获取杂交组合详情", response_model=ResponseSchema[CrossCombinationOutSchema])
|
||||
async def get_cross_combination__detail_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:detail"]))],
|
||||
id: Annotated[int, Path(description="杂交组合ID")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
result_dict = await service.detail(id=id)
|
||||
return SuccessResponse(data=result_dict, msg="获取杂交组合详情成功")
|
||||
|
||||
|
||||
@CrossCombinationRouter.get("/list", summary="分页查询杂交组合", response_model=ResponseSchema[PageResultSchema[CrossCombinationOutSchema]])
|
||||
async def get_cross_combination__list_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:query"]))],
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[CrossCombinationQueryParam, Query()],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
result_dict = await service.page(
|
||||
page_no=page.page_no,
|
||||
page_size=page.page_size,
|
||||
search=search,
|
||||
order_by=page.order_by,
|
||||
)
|
||||
return SuccessResponse(data=result_dict, msg="查询杂交组合列表成功")
|
||||
|
||||
|
||||
@CrossCombinationRouter.get("/options", summary="杂交组合下拉选项")
|
||||
async def get_cross_combination__options_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:query"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
options = await service.list_options()
|
||||
return SuccessResponse(data=options, msg="获取杂交组合选项成功")
|
||||
|
||||
|
||||
@CrossCombinationRouter.post("/create", summary="创建杂交组合", response_model=ResponseSchema[CrossCombinationOutSchema])
|
||||
async def create_cross_combination__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:create"]))],
|
||||
data: Annotated[CrossCombinationCreateSchema, Body(description="创建参数")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
result_dict = await service.create(data=data)
|
||||
return SuccessResponse(data=result_dict, msg="创建杂交组合成功")
|
||||
|
||||
|
||||
@CrossCombinationRouter.put("/update/{id}", summary="修改杂交组合", response_model=ResponseSchema[CrossCombinationOutSchema])
|
||||
async def update_cross_combination__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:update"]))],
|
||||
id: Annotated[int, Path(description="杂交组合ID")],
|
||||
data: Annotated[CrossCombinationUpdateSchema, Body(description="修改参数")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
result_dict = await service.update(id=id, data=data)
|
||||
return SuccessResponse(data=result_dict, msg="修改杂交组合成功")
|
||||
|
||||
|
||||
@CrossCombinationRouter.delete("/delete", summary="删除杂交组合", response_model=ResponseSchema[None])
|
||||
async def delete_cross_combination__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:delete"]))],
|
||||
ids: Annotated[list[int], Body(description="ID列表")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
await service.delete(ids=ids)
|
||||
return SuccessResponse(msg="删除杂交组合成功")
|
||||
|
||||
|
||||
@CrossCombinationRouter.post("/export", summary="导出杂交组合")
|
||||
async def export_cross_combination__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:export"]))],
|
||||
search: Annotated[CrossCombinationQueryParam, Query()],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> StreamingResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
result_dict_list = await service.get_list(search=search)
|
||||
export_result = CrossCombinationService.batch_export(obj_list=[item.model_dump() for item in result_dict_list])
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f"attachment; filename={urllib.parse.quote('杂交组合管理.xlsx')}"},
|
||||
)
|
||||
|
||||
|
||||
@CrossCombinationRouter.post("/import", summary="导入杂交组合", response_model=ResponseSchema[ImportResultSchema])
|
||||
async def import_cross_combination__controller(
|
||||
file: Annotated[UploadFile, File(description="导入文件")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:cross_combination:import"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = CrossCombinationService(auth, db)
|
||||
batch_import_result = await service.batch_import(file=file, update_support=True)
|
||||
return SuccessResponse(data=batch_import_result, msg="导入杂交组合成功")
|
||||
|
||||
|
||||
@CrossCombinationRouter.post("/download/template", summary="获取杂交组合导入模板", dependencies=[Depends(AuthPermission(["module_bre:cross_combination:download"]))])
|
||||
async def download_cross_combination__template_controller() -> StreamingResponse:
|
||||
import_template_result = CrossCombinationService.import_template_download()
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(import_template_result),
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename={urllib.parse.quote('杂交组合管理导入模板.xlsx')}",
|
||||
"Access-Control-Expose-Headers": "Content-Disposition",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.base_crud import CRUDBase
|
||||
from app.core.base_schema import AuthSchema
|
||||
|
||||
from .model import CrossCombinationModel
|
||||
|
||||
|
||||
class BreedingCrossCombinationCRUD(CRUDBase[CrossCombinationModel, Any, Any]):
|
||||
"""杂交组合 CRUD —— 直接复用 CRUDBase(已自动注入数据权限过滤)。"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
super().__init__(CrossCombinationModel, auth, db)
|
||||
|
||||
|
||||
cross_combination_crud = BreedingCrossCombinationCRUD
|
||||
@@ -0,0 +1,67 @@
|
||||
"""杂交组合 数据模型"""
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Float, ForeignKey, Index, Integer, String, Text, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.base_model import MappedBase, ModelMixin, UserMixin
|
||||
|
||||
|
||||
class CrossCombinationModel(ModelMixin, UserMixin, MappedBase):
|
||||
"""杂交组合 主数据表。"""
|
||||
|
||||
__tablename__ = "bre_cross_combination"
|
||||
|
||||
combination_code: Mapped[str] = mapped_column(String(100), nullable=False, comment="组合编号")
|
||||
|
||||
cross_year: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="杂交年份", default=None)
|
||||
|
||||
bre_target_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("bre_target.id", ondelete="CASCADE"),
|
||||
index=True, nullable=False, comment="育种目标"
|
||||
)
|
||||
|
||||
female_parent_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("bre_germplasm.id", ondelete="CASCADE"),
|
||||
index=True, nullable=True, comment="母本"
|
||||
)
|
||||
|
||||
male_parent_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("bre_germplasm.id", ondelete="CASCADE"),
|
||||
index=True, nullable=True, comment="父本"
|
||||
)
|
||||
|
||||
cross_method: Mapped[str | None] = mapped_column(String(50), nullable=True, comment="杂交方式", default=None)
|
||||
|
||||
cross_type: Mapped[str | None] = mapped_column(String(16), nullable=True, comment="杂交类型(杂交/自交/开放)", default=None)
|
||||
|
||||
design_type: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default="full_diallel",
|
||||
comment="交配设计(full_diallel完全双列/partial_diallel部分双列/line_tester line×tester NCII/nciii NCIII测交)",
|
||||
)
|
||||
|
||||
parent_combination_id: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("bre_cross_combination.id", ondelete="SET NULL"),
|
||||
index=True, nullable=True, comment="母本组合(自关联)"
|
||||
)
|
||||
|
||||
reason: Mapped[str | None] = mapped_column(String(512), nullable=True, comment="组配理由", default=None)
|
||||
|
||||
stage: Mapped[str | None] = mapped_column(String(32), nullable=True, comment="育种阶段(breeding_stage)", default=None)
|
||||
|
||||
cross_date: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="杂交日期", default=None)
|
||||
|
||||
seed_count: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="获种数", default=None)
|
||||
|
||||
remark: Mapped[str | None] = mapped_column(Text, nullable=True, comment="备注", default=None)
|
||||
|
||||
# 无 status 列:覆盖基类默认 ix_<表>_status_deleted 索引,
|
||||
# 仅保留 (created_time, is_deleted) 复合索引用于数据权限过滤。
|
||||
__table_args__ = (
|
||||
Index("ix_bre_cross_combination_created_deleted", "created_time", "is_deleted"),
|
||||
# 组合编号唯一(仅约束未软删记录,与 service 层查重语义一致)
|
||||
Index(
|
||||
"uniq_bre_cross_combination_code", "combination_code",
|
||||
unique=True, postgresql_where=text("is_deleted = false"),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
from app.core.base_schema import CommonSchema
|
||||
"""杂交组合 —— Pydantic 校验/序列化模型。"""
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class CrossCombinationBaseSchema(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
combination_code: str | None = Field(default=None, description="组合编号(留空自动生成 YY+3位序号)")
|
||||
cross_year: int | None = Field(default=None, description="杂交年份")
|
||||
bre_target_id: int = Field(..., description="育种目标")
|
||||
female_parent_id: int | None = Field(default=None, description="母本")
|
||||
male_parent_id: int | None = Field(default=None, description="父本")
|
||||
cross_method: str | None = Field(default=None, description="杂交方式")
|
||||
cross_type: str | None = Field(default=None, description="杂交类型(杂交/自交/开放)")
|
||||
design_type: str = Field(
|
||||
default="full_diallel",
|
||||
description="交配设计(full_diallel完全双列/partial_diallel部分双列/line_tester line×tester NCII/nciii NCIII测交)",
|
||||
)
|
||||
parent_combination_id: int | None = Field(default=None, description="母本组合(自关联)")
|
||||
reason: str | None = Field(default=None, description="组配理由")
|
||||
stage: str | None = Field(default=None, description="育种阶段(breeding_stage)")
|
||||
cross_date: str | None = Field(default=None, description="杂交日期")
|
||||
seed_count: int | None = Field(default=None, description="获种数")
|
||||
remark: str | None = Field(default=None, description="备注")
|
||||
|
||||
|
||||
class CrossCombinationCreateSchema(CrossCombinationBaseSchema):
|
||||
pass
|
||||
|
||||
|
||||
class CrossCombinationUpdateSchema(CrossCombinationBaseSchema):
|
||||
combination_code: str | None = Field(default=None, description="组合编号")
|
||||
cross_year: int | None = Field(default=None, description="杂交年份")
|
||||
bre_target_id: int | None = Field(default=None, description="育种目标")
|
||||
female_parent_id: int | None = Field(default=None, description="母本")
|
||||
male_parent_id: int | None = Field(default=None, description="父本")
|
||||
cross_method: str | None = Field(default=None, description="杂交方式")
|
||||
cross_type: str | None = Field(default=None, description="杂交类型(杂交/自交/开放)")
|
||||
design_type: str | None = Field(default=None, description="交配设计")
|
||||
parent_combination_id: int | None = Field(default=None, description="母本组合(自关联)")
|
||||
reason: str | None = Field(default=None, description="组配理由")
|
||||
stage: str | None = Field(default=None, description="育种阶段(breeding_stage)")
|
||||
cross_date: str | None = Field(default=None, description="杂交日期")
|
||||
seed_count: int | None = Field(default=None, description="获种数")
|
||||
remark: str | None = Field(default=None, description="备注")
|
||||
|
||||
|
||||
class CrossCombinationOutSchema(CrossCombinationBaseSchema):
|
||||
id: int
|
||||
uuid: str
|
||||
combination_code: str | None = None
|
||||
cross_year: int | None = None
|
||||
bre_target_name: str | None = None # 由 Service 层联表填充
|
||||
female_parent_name: str | None = None # 由 Service 层联表填充
|
||||
male_parent_name: str | None = None # 由 Service 层联表填充
|
||||
parent_combination_code: str | None = None # 由 Service 层联表填充
|
||||
s_compat: str | None = None # 由 Service 层按亲本 S-等位基因计算(完全兼容/半兼容/不相容)
|
||||
cross_method: str | None = None
|
||||
cross_type: str | None = None
|
||||
reason: str | None = None
|
||||
stage: str | None = None
|
||||
cross_date: str | None = None
|
||||
seed_count: int | None = None
|
||||
remark: str | None = None
|
||||
created_time: datetime | None = None
|
||||
updated_time: datetime | None = None
|
||||
created_by: CommonSchema | None = None
|
||||
updated_by: CommonSchema | None = None
|
||||
|
||||
|
||||
class CrossCombinationQueryParam(BaseModel):
|
||||
combination_code: str | None = Field(default=None, description="组合编号", json_schema_extra={"q": "like"})
|
||||
cross_year: int | None = Field(default=None, description="杂交年份", json_schema_extra={"q": "eq"})
|
||||
bre_target_id: int | None = Field(default=None, description="育种目标", json_schema_extra={"q": "eq"})
|
||||
cross_method: str | None = Field(default=None, description="杂交方式", json_schema_extra={"q": "eq"})
|
||||
cross_type: str | None = Field(default=None, description="杂交类型", json_schema_extra={"q": "eq"})
|
||||
design_type: str | None = Field(default=None, description="交配设计", json_schema_extra={"q": "eq"})
|
||||
stage: str | None = Field(default=None, description="育种阶段", json_schema_extra={"q": "eq"})
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
from typing import Any
|
||||
from datetime import datetime
|
||||
|
||||
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 app.utils.dict_util import DictLabelResolver, dict_value_to_label
|
||||
from app.utils.number_gen import NumberGenService
|
||||
|
||||
from .crud import BreedingCrossCombinationCRUD
|
||||
from .model import CrossCombinationModel
|
||||
from .schema import (
|
||||
CrossCombinationCreateSchema,
|
||||
CrossCombinationOutSchema,
|
||||
CrossCombinationQueryParam,
|
||||
CrossCombinationUpdateSchema,
|
||||
)
|
||||
from app.api.v1.module_bre.target.crud import BreedingTargetCRUD
|
||||
from app.api.v1.module_bre.germplasm.crud import BreedingGermplasmCRUD
|
||||
|
||||
|
||||
|
||||
from app.core.base_crud import assert_dict_values, assert_no_children, assert_parents_exist
|
||||
from app.api.v1.module_bre.germplasm.model import BreedingGermplasmModel
|
||||
from app.api.v1.module_bre.pedigree.model import PedigreeModel
|
||||
from app.api.v1.module_bre.planting.model import PlantingModel
|
||||
from app.api.v1.module_bre.pollination.model import PollinationModel
|
||||
from app.api.v1.module_bre.seed_treatment.model import SeedTreatmentModel
|
||||
from app.api.v1.module_bre.seedling.model import SeedlingModel
|
||||
from app.api.v1.module_bre.selection_result.model import SelectionResultModel
|
||||
from app.api.v1.module_bre.target.model import TargetModel
|
||||
from app.api.v1.module_bre.trait_observation.model import TraitObservationModel
|
||||
from app.api.v1.module_bre.tree_evaluation.model import TreeEvaluationModel
|
||||
from app.api.v1.module_bre.tree.model import TreeModel
|
||||
from app.api.v1.module_bre.tree_photo.model import TreePhotoModel
|
||||
|
||||
# 交配设计取值(与统计引擎 combining.solve 分支一致;不入 sys_dict,同 selection_index.method 模式)
|
||||
_COMBINING_DESIGNS = {"full_diallel", "partial_diallel", "line_tester", "nciii"}
|
||||
_DESIGN_LABELS = {
|
||||
"full_diallel": "完全双列",
|
||||
"partial_diallel": "部分双列",
|
||||
"line_tester": "line×tester (NCII)",
|
||||
"nciii": "NCIII 测交",
|
||||
}
|
||||
_DESIGN_FROM_LABEL = {v: k for k, v in _DESIGN_LABELS.items()}
|
||||
|
||||
|
||||
_SF_ALLELES = {"sf"}
|
||||
|
||||
|
||||
def _parse_s_alleles(raw: str | None) -> set[str] | None:
|
||||
"""解析 S-等位基因串(如 "S1/S3"、"S1,S2 S3")→ 归一化等位集合;空白/无数据返回 None。
|
||||
|
||||
大小写归一(S1/s1);"Sf"/"sf" 为自交亲和功能缺失等位,单独标记含 sf。
|
||||
"""
|
||||
if raw is None or not str(raw).strip():
|
||||
return None
|
||||
parts = [p.strip() for p in str(raw).replace("/", ",").replace(";", ",").replace(" ", ",").split(",")]
|
||||
codes = {p.lower() for p in parts if p}
|
||||
return codes or None
|
||||
|
||||
|
||||
def _s_compat_check(female_s: str | None, male_s: str | None) -> tuple[str, str | None]:
|
||||
"""桃配子体型自交不亲和(S-RNase) 交配兼容性判定。
|
||||
|
||||
规则:任一亲本携带 Sf(自交亲和等位,SI 功能缺失)→ 完全兼容;
|
||||
否则按共享 S 等位数:0=完全兼容,1=半兼容(花粉半数不亲和,坐果率降),
|
||||
2=完全不相容(配了不结)。缺 S 数据 → 不校验(None)。
|
||||
返回 (状态, 文案):状态 full/half/none/unknown。
|
||||
"""
|
||||
f_set, m_set = _parse_s_alleles(female_s), _parse_s_alleles(male_s)
|
||||
if f_set is None or m_set is None:
|
||||
return "unknown", None
|
||||
if f_set & _SF_ALLELES or m_set & _SF_ALLELES:
|
||||
return "full", None
|
||||
shared = sorted(f_set & m_set)
|
||||
if len(shared) >= 2:
|
||||
return "none", f"S-等位基因完全不相容(共享 {'/'.join(shared)}),该组合无法坐果"
|
||||
if len(shared) == 1:
|
||||
return "half", f"S-等位基因半兼容(共享 {shared[0]}),约半数花粉不亲和,坐果率下降"
|
||||
return "full", None
|
||||
|
||||
|
||||
def _validate_design_type(design_type: str | None) -> str | None:
|
||||
if _is_blank(design_type):
|
||||
return None
|
||||
code = _DESIGN_FROM_LABEL.get(str(design_type).strip()) or str(design_type).strip()
|
||||
if code not in _COMBINING_DESIGNS:
|
||||
raise CustomException(
|
||||
msg=f"交配设计取值不合法: {design_type}(可用: {'、'.join(_DESIGN_LABELS.values())})"
|
||||
)
|
||||
return code
|
||||
|
||||
|
||||
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 CrossCombinationService:
|
||||
"""杂交组合 模块服务层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
self.auth = auth
|
||||
self.db = db
|
||||
|
||||
async def _attach_fk_labels(self, items: list[CrossCombinationOutSchema]) -> None:
|
||||
if not items:
|
||||
return
|
||||
crud = BreedingCrossCombinationCRUD(self.auth, self.db)
|
||||
bre_target_id_ids = {getattr(it, "bre_target_id") for it in items if getattr(it, "bre_target_id")}
|
||||
if bre_target_id_ids:
|
||||
refs = await BreedingTargetCRUD(self.auth, self.db).get_list(search={"id": ("in", list(bre_target_id_ids))})
|
||||
ref_map = {r.id: getattr(r, "target_name") for r in refs}
|
||||
for it in items:
|
||||
it.bre_target_name = ref_map.get(getattr(it, "bre_target_id"))
|
||||
female_parent_id_ids = {getattr(it, "female_parent_id") for it in items if getattr(it, "female_parent_id")}
|
||||
if female_parent_id_ids:
|
||||
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(search={"id": ("in", list(female_parent_id_ids))})
|
||||
ref_map = {r.id: getattr(r, "cultivar_name") for r in refs}
|
||||
for it in items:
|
||||
it.female_parent_name = ref_map.get(getattr(it, "female_parent_id"))
|
||||
male_parent_id_ids = {getattr(it, "male_parent_id") for it in items if getattr(it, "male_parent_id")}
|
||||
if male_parent_id_ids:
|
||||
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(search={"id": ("in", list(male_parent_id_ids))})
|
||||
ref_map = {r.id: getattr(r, "cultivar_name") for r in refs}
|
||||
for it in items:
|
||||
it.male_parent_name = ref_map.get(getattr(it, "male_parent_id"))
|
||||
parent_combination_id_ids = {getattr(it, "parent_combination_id") for it in items if getattr(it, "parent_combination_id")}
|
||||
if parent_combination_id_ids:
|
||||
refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(search={"id": ("in", list(parent_combination_id_ids))})
|
||||
ref_map = {r.id: getattr(r, "combination_code") for r in refs}
|
||||
for it in items:
|
||||
it.parent_combination_code = ref_map.get(getattr(it, "parent_combination_id"))
|
||||
|
||||
async def detail(self, id: int) -> CrossCombinationOutSchema:
|
||||
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该杂交组合不存在")
|
||||
out = CrossCombinationOutSchema.model_validate(obj)
|
||||
await self._attach_fk_labels([out])
|
||||
return out
|
||||
|
||||
async def get_list(
|
||||
self,
|
||||
search: CrossCombinationQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> list[CrossCombinationOutSchema]:
|
||||
obj_list = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(
|
||||
search=search_to_dict(search), order_by=order_by
|
||||
)
|
||||
outs = [CrossCombinationOutSchema.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: CrossCombinationQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> PageResultSchema[CrossCombinationOutSchema]:
|
||||
offset = (page_no - 1) * page_size
|
||||
result = await BreedingCrossCombinationCRUD(self.auth, self.db).page(
|
||||
offset=offset,
|
||||
limit=page_size,
|
||||
order_by=order_by or [{"id": "asc"}],
|
||||
search=search_to_dict(search, {}),
|
||||
out_schema=CrossCombinationOutSchema,
|
||||
)
|
||||
await self._attach_fk_labels(result.items)
|
||||
return result
|
||||
|
||||
async def _check_s_compat(self, female_parent_id: int | None, male_parent_id: int | None) -> str | None:
|
||||
"""读亲本 S-等位基因做交配兼容性校验;完全不相容 → 409;半兼容返回警示文案。"""
|
||||
if not female_parent_id or not male_parent_id:
|
||||
return None
|
||||
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(
|
||||
search={"id": ("in", [female_parent_id, male_parent_id])}
|
||||
)
|
||||
by_id = {g.id: g for g in refs}
|
||||
female_s = getattr(by_id.get(female_parent_id), "s_alleles", None)
|
||||
male_s = getattr(by_id.get(male_parent_id), "s_alleles", None)
|
||||
status, msg = _s_compat_check(female_s, male_s)
|
||||
if status == "none":
|
||||
raise CustomException(msg=msg)
|
||||
return msg if status == "half" else None
|
||||
|
||||
async def _check_parent_roles(self, female_parent_id: int | None, male_parent_id: int | None) -> None:
|
||||
"""亲本校验:母本父本同质自交 → 409;已显式配置为单角色的种质不得用于另一角色。
|
||||
|
||||
桃为两性花,绝大多数种质可双作;can_be_female/can_be_male 两列
|
||||
default=False 表示未配置,视为均可(不拦)。仅当某侧被显式标记为
|
||||
不可作(该侧 False、另一侧 True)时按数据错误拦截。
|
||||
"""
|
||||
if not female_parent_id or not male_parent_id:
|
||||
return
|
||||
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(
|
||||
search={"id": ("in", [female_parent_id, male_parent_id])}
|
||||
)
|
||||
by_id = {g.id: g for g in refs}
|
||||
female = by_id.get(female_parent_id)
|
||||
male = by_id.get(male_parent_id)
|
||||
if female is None or male is None:
|
||||
return
|
||||
f_name = getattr(female, "cultivar_name", "母本") or "母本"
|
||||
m_name = getattr(male, "cultivar_name", "父本") or "父本"
|
||||
if female_parent_id == male_parent_id:
|
||||
raise CustomException(msg=f"母本与父本同为「{f_name}」,自交组合请确认")
|
||||
if female.can_be_male and not female.can_be_female:
|
||||
raise CustomException(msg=f"母本「{f_name}」已标记为仅可作父本,不能作母本")
|
||||
if male.can_be_female and not male.can_be_male:
|
||||
raise CustomException(msg=f"父本「{m_name}」已标记为仅可作母本,不能作父本")
|
||||
|
||||
async def _gen_combination_code(self, cross_year: int | None) -> str:
|
||||
"""自动生成组合编号:YY + 3 位序号(如 26001、26002…),原子取号。"""
|
||||
year = cross_year or datetime.now().year
|
||||
prefix = f"{year % 100:02d}"
|
||||
|
||||
async def _seed() -> int | None:
|
||||
crud = BreedingCrossCombinationCRUD(self.auth, self.db)
|
||||
objs = await crud.get_list(search={"combination_code": ("like", prefix)})
|
||||
max_seq = 0
|
||||
for o in objs:
|
||||
code = o.combination_code or ""
|
||||
if code.startswith(prefix) and code[len(prefix):].isdigit():
|
||||
max_seq = max(max_seq, int(code[len(prefix):]))
|
||||
return max_seq + 1
|
||||
|
||||
seq = await NumberGenService(self.db).next_seq(f"combination:{year}", seed_fn=_seed)
|
||||
return f"{prefix}{seq:03d}"
|
||||
|
||||
async def create(self, data: CrossCombinationCreateSchema) -> CrossCombinationOutSchema:
|
||||
fields = data.model_dump(exclude_none=True)
|
||||
if _is_blank(fields.get("combination_code")):
|
||||
fields["combination_code"] = await self._gen_combination_code(fields.get("cross_year"))
|
||||
code = _validate_design_type(fields.get("design_type") or "full_diallel")
|
||||
fields["design_type"] = code or "full_diallel"
|
||||
data = CrossCombinationCreateSchema(**fields)
|
||||
exist_obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(combination_code=data.combination_code)
|
||||
if exist_obj:
|
||||
raise CustomException(msg="创建失败,组合编号已存在")
|
||||
await assert_parents_exist(
|
||||
self.db,
|
||||
[
|
||||
(TargetModel, data.bre_target_id, '育种目标'),
|
||||
(BreedingGermplasmModel, data.female_parent_id, '母本种质'),
|
||||
(BreedingGermplasmModel, data.male_parent_id, '父本种质'),
|
||||
(CrossCombinationModel, data.parent_combination_id, '母本组合'),
|
||||
],
|
||||
)
|
||||
await assert_dict_values(
|
||||
self.db,
|
||||
[
|
||||
('cross_method', data.cross_method, '杂交方式'),
|
||||
('cross_type', data.cross_type, '杂交类型'),
|
||||
('breeding_stage', data.stage, '育种阶段'),
|
||||
],
|
||||
)
|
||||
|
||||
await self._check_parent_roles(data.female_parent_id, data.male_parent_id)
|
||||
s_compat = await self._check_s_compat(data.female_parent_id, data.male_parent_id)
|
||||
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).create(data=data)
|
||||
out = CrossCombinationOutSchema.model_validate(obj)
|
||||
out.s_compat = s_compat
|
||||
await self._attach_fk_labels([out])
|
||||
return out
|
||||
|
||||
async def update(self, id: int, data: CrossCombinationUpdateSchema) -> CrossCombinationOutSchema:
|
||||
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="更新失败,该杂交组合不存在")
|
||||
if data.combination_code is not None:
|
||||
exist_obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(combination_code=data.combination_code)
|
||||
if exist_obj and exist_obj.id != id:
|
||||
raise CustomException(msg="更新失败,组合编号重复")
|
||||
await assert_parents_exist(
|
||||
self.db,
|
||||
[
|
||||
(TargetModel, data.bre_target_id, '育种目标'),
|
||||
(BreedingGermplasmModel, data.female_parent_id, '母本种质'),
|
||||
(BreedingGermplasmModel, data.male_parent_id, '父本种质'),
|
||||
(CrossCombinationModel, data.parent_combination_id, '母本组合'),
|
||||
],
|
||||
)
|
||||
await assert_dict_values(
|
||||
self.db,
|
||||
[
|
||||
('cross_method', data.cross_method, '杂交方式'),
|
||||
('cross_type', data.cross_type, '杂交类型'),
|
||||
('breeding_stage', data.stage, '育种阶段'),
|
||||
],
|
||||
)
|
||||
if data.design_type is not None:
|
||||
data.design_type = _validate_design_type(data.design_type) or data.design_type
|
||||
|
||||
eff_female = data.female_parent_id if data.female_parent_id is not None else obj.female_parent_id
|
||||
eff_male = data.male_parent_id if data.male_parent_id is not None else obj.male_parent_id
|
||||
await self._check_parent_roles(eff_female, eff_male)
|
||||
s_compat = await self._check_s_compat(eff_female, eff_male)
|
||||
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).update(id=id, data=data)
|
||||
out = CrossCombinationOutSchema.model_validate(obj)
|
||||
out.s_compat = s_compat
|
||||
await self._attach_fk_labels([out])
|
||||
return out
|
||||
|
||||
async def delete(self, ids: list[int]) -> None:
|
||||
if not ids:
|
||||
raise CustomException(msg="删除失败,删除对象不能为空")
|
||||
objs = await BreedingCrossCombinationCRUD(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,
|
||||
[
|
||||
(PollinationModel, 'combination_id', '授粉'),
|
||||
(SeedTreatmentModel, 'combination_id', '种子处理'),
|
||||
(SeedlingModel, 'combination_id', '实生苗'),
|
||||
(PlantingModel, 'combination_id', '定植'),
|
||||
(TreeModel, 'combination_id', '单株'),
|
||||
(TreeEvaluationModel, 'combination_id', '单株评价'),
|
||||
(TreePhotoModel, 'combination_id', '单株照片'),
|
||||
(SelectionResultModel, 'combination_id', '选择结果'),
|
||||
(TraitObservationModel, 'combination_id', '性状观测'),
|
||||
(PedigreeModel, 'combination_id', '系谱'),
|
||||
],
|
||||
)
|
||||
await BreedingCrossCombinationCRUD(self.auth, self.db).delete(ids=ids)
|
||||
|
||||
async def list_options(self) -> list[dict[str, Any]]:
|
||||
"""供前端下拉选择使用:返回 [{value, label, female_parent_id, male_parent_id}]。
|
||||
|
||||
female/male 亲本 id 供单株表单选中组合后自动回填母本/父本。
|
||||
"""
|
||||
obj_list = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
return [
|
||||
{
|
||||
"value": o.id,
|
||||
"label": o.combination_code,
|
||||
"female_parent_id": o.female_parent_id,
|
||||
"male_parent_id": o.male_parent_id,
|
||||
}
|
||||
for o in obj_list
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
|
||||
mapping_dict = {
|
||||
"combination_code": "组合编号",
|
||||
"cross_year": "杂交年份",
|
||||
"bre_target_name": "育种目标",
|
||||
"female_parent_name": "母本",
|
||||
"male_parent_name": "父本",
|
||||
"parent_combination_code": "母本组合",
|
||||
"cross_method": "杂交方式",
|
||||
"cross_type": "杂交类型",
|
||||
"design_type": "交配设计",
|
||||
"reason": "组配理由",
|
||||
"stage": "育种阶段",
|
||||
"cross_date": "杂交日期",
|
||||
"seed_count": "获种数",
|
||||
"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["cross_method"] = dict_value_to_label("cross_method", item.get("cross_method"))
|
||||
item["cross_type"] = dict_value_to_label("cross_type", item.get("cross_type"))
|
||||
item["design_type"] = _DESIGN_LABELS.get(item.get("design_type"), item.get("design_type"))
|
||||
item["stage"] = dict_value_to_label("breeding_stage", item.get("stage"))
|
||||
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_code",
|
||||
"杂交年份": "cross_year",
|
||||
"育种目标": "bre_target_id",
|
||||
"母本": "female_parent_id",
|
||||
"父本": "male_parent_id",
|
||||
"母本组合": "parent_combination_id",
|
||||
"杂交方式": "cross_method",
|
||||
"杂交类型": "cross_type",
|
||||
"交配设计": "design_type",
|
||||
"组配理由": "reason",
|
||||
"育种阶段": "stage",
|
||||
"杂交日期": "cross_date",
|
||||
"获种数": "seed_count",
|
||||
"备注": "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)}")
|
||||
bre_target_id_refs = await BreedingTargetCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
bre_target_id_map = {getattr(r, "target_name"): r.id for r in bre_target_id_refs}
|
||||
female_parent_id_refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
female_parent_id_map = {getattr(r, "cultivar_name"): r.id for r in female_parent_id_refs}
|
||||
male_parent_id_refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
male_parent_id_map = {getattr(r, "cultivar_name"): r.id for r in male_parent_id_refs}
|
||||
parent_combination_id_refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
parent_combination_id_map = {getattr(r, "combination_code"): r.id for r in parent_combination_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_code", "bre_target_id"]
|
||||
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 = BreedingCrossCombinationCRUD(self.auth, self.db)
|
||||
resolver = DictLabelResolver(self.auth, self.db, ["cross_method", "cross_type", "breeding_stage"])
|
||||
for i, row in enumerate(mapped_rows, start=1):
|
||||
try:
|
||||
bre_target_id_val = bre_target_id_map.get(str(row.get("bre_target_id")).strip()) if not _is_blank(row.get("bre_target_id")) else None
|
||||
female_parent_id_val = female_parent_id_map.get(str(row.get("female_parent_id")).strip()) if not _is_blank(row.get("female_parent_id")) else None
|
||||
male_parent_id_val = male_parent_id_map.get(str(row.get("male_parent_id")).strip()) if not _is_blank(row.get("male_parent_id")) else None
|
||||
parent_combination_id_val = parent_combination_id_map.get(str(row.get("parent_combination_id")).strip()) if not _is_blank(row.get("parent_combination_id")) else None
|
||||
fields = {
|
||||
"combination_code": _none_if_blank(row.get("combination_code")),
|
||||
"cross_year": _to_int(row.get("cross_year")),
|
||||
"bre_target_id": bre_target_id_val,
|
||||
"female_parent_id": female_parent_id_val,
|
||||
"male_parent_id": male_parent_id_val,
|
||||
"parent_combination_id": parent_combination_id_val,
|
||||
"cross_method": await resolver.resolve("cross_method", row.get("cross_method")),
|
||||
"cross_type": await resolver.resolve("cross_type", row.get("cross_type")),
|
||||
"design_type": _validate_design_type(row.get("design_type")) or "full_diallel",
|
||||
"reason": _none_if_blank(row.get("reason")),
|
||||
"stage": await resolver.resolve("breeding_stage", row.get("stage")),
|
||||
"cross_date": _none_if_blank(row.get("cross_date")),
|
||||
"seed_count": _to_int(row.get("seed_count")),
|
||||
"remark": _none_if_blank(row.get("remark")),
|
||||
}
|
||||
await self._check_parent_roles(female_parent_id_val, male_parent_id_val)
|
||||
unique_kwargs = {"combination_code": fields["combination_code"]}
|
||||
create_data = CrossCombinationCreateSchema(**fields)
|
||||
exist_obj = await crud.get(**unique_kwargs)
|
||||
if exist_obj:
|
||||
if update_support:
|
||||
await crud.update(id=exist_obj.id, data=CrossCombinationUpdateSchema(**fields))
|
||||
success_count += 1
|
||||
else:
|
||||
error_msgs.append(f"第{i}行: 组合编号 {fields['combination_code']} 已存在")
|
||||
else:
|
||||
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 = [
|
||||
{"杂交方式": ["人工杂交", "自然授粉", "回交"]},
|
||||
{"杂交类型": ["杂交", "自交", "开放"]},
|
||||
{"交配设计": ["完全双列", "部分双列", "line×tester (NCII)", "NCIII 测交"]},
|
||||
{"育种阶段": ["germplasm", "parent", "seedling", "sp", "ap", "line", "regional_trial", "released"]},
|
||||
]
|
||||
return ExcelUtil.get_excel_template(
|
||||
header_list=header_list,
|
||||
selector_header_list=selector_header_list,
|
||||
option_list=option_list,
|
||||
)
|
||||
Reference in New Issue
Block a user