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,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 (
PlantingCreateSchema,
PlantingOutSchema,
PlantingQueryParam,
PlantingUpdateSchema,
)
from .service import PlantingService
PlantingRouter = APIRouter(route_class=OperationLogRoute, prefix="/planting", tags=["定植管理"])
@PlantingRouter.get("/detail/{id}", summary="获取定植管理详情", response_model=ResponseSchema[PlantingOutSchema])
async def get_planting__detail_controller(
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:detail"]))],
id: Annotated[int, Path(description="定植管理ID")],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
service = PlantingService(auth, db)
result_dict = await service.detail(id=id)
return SuccessResponse(data=result_dict, msg="获取定植详情成功")
@PlantingRouter.get("/list", summary="分页查询定植管理", response_model=ResponseSchema[PageResultSchema[PlantingOutSchema]])
async def get_planting__list_controller(
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:query"]))],
page: Annotated[PaginationQueryParam, Depends()],
search: Annotated[PlantingQueryParam, Query()],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
service = PlantingService(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="查询定植列表成功")
@PlantingRouter.get("/options", summary="定植管理下拉选项")
async def get_planting__options_controller(
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:query"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
service = PlantingService(auth, db)
options = await service.list_options()
return SuccessResponse(data=options, msg="获取定植选项成功")
@PlantingRouter.post("/create", summary="创建定植管理", response_model=ResponseSchema[PlantingOutSchema])
async def create_planting__controller(
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:create"]))],
data: Annotated[PlantingCreateSchema, Body(description="创建参数")],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
service = PlantingService(auth, db)
result_dict = await service.create(data=data)
return SuccessResponse(data=result_dict, msg="创建定植成功")
@PlantingRouter.put("/update/{id}", summary="修改定植管理", response_model=ResponseSchema[PlantingOutSchema])
async def update_planting__controller(
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:update"]))],
id: Annotated[int, Path(description="定植管理ID")],
data: Annotated[PlantingUpdateSchema, Body(description="修改参数")],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
service = PlantingService(auth, db)
result_dict = await service.update(id=id, data=data)
return SuccessResponse(data=result_dict, msg="修改定植成功")
@PlantingRouter.delete("/delete", summary="删除定植管理", response_model=ResponseSchema[None])
async def delete_planting__controller(
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:delete"]))],
ids: Annotated[list[int], Body(description="ID列表")],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
service = PlantingService(auth, db)
await service.delete(ids=ids)
return SuccessResponse(msg="删除定植成功")
@PlantingRouter.post("/export", summary="导出定植管理")
async def export_planting__controller(
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:export"]))],
search: Annotated[PlantingQueryParam, Query()],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> StreamingResponse:
service = PlantingService(auth, db)
result_dict_list = await service.get_list(search=search)
export_result = PlantingService.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')}"},
)
@PlantingRouter.post("/import", summary="导入定植管理", response_model=ResponseSchema[ImportResultSchema])
async def import_planting__controller(
file: Annotated[UploadFile, File(description="导入文件")],
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:planting:import"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
service = PlantingService(auth, db)
batch_import_result = await service.batch_import(file=file, update_support=True)
return SuccessResponse(data=batch_import_result, msg="导入定植成功")
@PlantingRouter.post("/download/template", summary="获取定植管理导入模板", dependencies=[Depends(AuthPermission(["module_bre:planting:download"]))])
async def download_planting__template_controller() -> StreamingResponse:
import_template_result = PlantingService.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 PlantingModel
class BreedingPlantingCRUD(CRUDBase[PlantingModel, Any, Any]):
"""定植管理 CRUD —— 直接复用 CRUDBase(已自动注入数据权限过滤)。"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
super().__init__(PlantingModel, auth, db)
planting_crud = BreedingPlantingCRUD
@@ -0,0 +1,71 @@
"""定植管理 数据模型"""
from datetime import datetime
from sqlalchemy import Float, ForeignKey, Index, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from app.core.base_model import MappedBase, ModelMixin, UserMixin
class PlantingModel(ModelMixin, UserMixin, MappedBase):
"""定植管理 主数据表。"""
__tablename__ = "bre_planting"
combination_id: Mapped[int] = mapped_column(
Integer, ForeignKey("bre_cross_combination.id", ondelete="CASCADE"),
index=True, nullable=False, comment="杂交组合"
)
plot_id: Mapped[int] = mapped_column(
Integer, ForeignKey("bre_plot.id", ondelete="CASCADE"),
index=True, nullable=True, comment="试验地块"
)
planting_date: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="定植日期", default=None)
tree_count: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="定植株数", default=None)
row_no: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="行号", default=None)
col_no: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="列号", default=None)
bre_personnel_id: Mapped[int] = mapped_column(
Integer, ForeignKey("bre_personnel.id", ondelete="CASCADE"),
index=True, nullable=True, comment="定植人"
)
seedling_id: Mapped[int] = mapped_column(
Integer, ForeignKey("bre_seedling.id", ondelete="CASCADE"),
index=True, nullable=True, comment="育苗批次"
)
seed_lot_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("bre_seed_lot.id", ondelete="SET NULL"),
index=True, nullable=True, comment="种子来源批(选择强度链,规格 §3.13)"
)
rootstock_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("bre_rootstock.id", ondelete="SET NULL"),
index=True, nullable=True, comment="砧木"
)
entry_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("bre_trial_study_entry.id", ondelete="SET NULL"),
index=True, nullable=True, comment="参试条目"
)
trial_study_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("bre_trial_study.id", ondelete="SET NULL"),
index=True, nullable=True, comment="所属试验研究点"
)
block_no: 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_planting_created_deleted", "created_time", "is_deleted"),
)
@@ -0,0 +1,80 @@
from app.core.base_schema import CommonSchema
"""定植管理 —— Pydantic 校验/序列化模型。"""
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field
class PlantingBaseSchema(BaseModel):
model_config = ConfigDict(from_attributes=True)
combination_id: int = Field(..., description="杂交组合")
plot_id: int | None = Field(default=None, description="试验地块")
planting_date: str | None = Field(default=None, description="定植日期")
tree_count: int | None = Field(default=None, description="定植株数")
row_no: int | None = Field(default=None, description="行号")
col_no: int | None = Field(default=None, description="列号")
bre_personnel_id: int | None = Field(default=None, description="定植人")
seedling_id: int | None = Field(default=None, description="育苗批次")
seed_lot_id: int | None = Field(default=None, description="种子来源批(选择强度链)")
rootstock_id: int | None = Field(default=None, description="砧木")
entry_id: int | None = Field(default=None, description="参试条目")
trial_study_id: int | None = Field(default=None, description="所属试验研究点")
block_no: int | None = Field(default=None, description="区组号")
remark: str | None = Field(default=None, description="备注")
class PlantingCreateSchema(PlantingBaseSchema):
pass
class PlantingUpdateSchema(PlantingBaseSchema):
combination_id: int | None = Field(default=None, description="杂交组合")
plot_id: int | None = Field(default=None, description="试验地块")
planting_date: str | None = Field(default=None, description="定植日期")
tree_count: int | None = Field(default=None, description="定植株数")
row_no: int | None = Field(default=None, description="行号")
col_no: int | None = Field(default=None, description="列号")
bre_personnel_id: int | None = Field(default=None, description="定植人")
seedling_id: int | None = Field(default=None, description="育苗批次")
seed_lot_id: int | None = Field(default=None, description="种子来源批(选择强度链)")
rootstock_id: int | None = Field(default=None, description="砧木")
entry_id: int | None = Field(default=None, description="参试条目")
trial_study_id: int | None = Field(default=None, description="所属试验研究点")
block_no: int | None = Field(default=None, description="区组号")
remark: str | None = Field(default=None, description="备注")
class PlantingOutSchema(PlantingBaseSchema):
id: int
uuid: str
combination_name: str | None = None # 由 Service 层联表填充
plot_name: str | None = None # 由 Service 层联表填充
planting_date: str | None = None
tree_count: int | None = None
row_no: int | None = None
col_no: int | None = None
bre_personnel_name: str | None = None # 由 Service 层联表填充
seedling_name: str | None = None # 由 Service 层联表填充
lot_code: str | None = None # 由 Service 层联表填充(种子来源批号)
rootstock_name: str | None = None # 由 Service 层联表填充
entry_number: str | None = None # 由 Service 层联表填充(参试编号)
study_name: str | None = None # 由 Service 层联表填充(研究点名称)
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 PlantingQueryParam(BaseModel):
combination_id: int | None = Field(default=None, description="杂交组合", json_schema_extra={"q": "eq"})
plot_id: int | None = Field(default=None, description="试验地块", json_schema_extra={"q": "eq"})
bre_personnel_id: int | None = Field(default=None, description="定植人", json_schema_extra={"q": "eq"})
seedling_id: int | None = Field(default=None, description="育苗批次", json_schema_extra={"q": "eq"})
seed_lot_id: int | None = Field(default=None, description="种子来源批", json_schema_extra={"q": "eq"})
rootstock_id: int | None = Field(default=None, description="砧木", json_schema_extra={"q": "eq"})
entry_id: int | None = Field(default=None, description="参试条目", json_schema_extra={"q": "eq"})
trial_study_id: int | None = Field(default=None, description="所属试验研究点", json_schema_extra={"q": "eq"})
block_no: int | None = Field(default=None, description="区组号", json_schema_extra={"q": "eq"})
@@ -0,0 +1,375 @@
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 BreedingPlantingCRUD
from .schema import (
PlantingCreateSchema,
PlantingOutSchema,
PlantingQueryParam,
PlantingUpdateSchema,
)
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.seedling.crud import BreedingSeedlingCRUD
from app.api.v1.module_bre.seed_lot.crud import BreedingSeedLotCRUD
from app.api.v1.module_bre.rootstock.crud import BreedingRootstockCRUD
from app.api.v1.module_bre.trial_study_entry.crud import BreedingTrialStudyEntryCRUD
from app.api.v1.module_bre.trial_study.crud import BreedingTrialStudyCRUD
from app.core.base_crud import assert_no_children, assert_parents_exist
from app.api.v1.module_bre.site.model import BreedingPlotModel
from app.api.v1.module_bre.cross_combination.model import CrossCombinationModel
from app.api.v1.module_bre.personnel.model import PersonnelModel
from app.api.v1.module_bre.seedling.model import SeedlingModel
from app.api.v1.module_bre.seed_lot.model import SeedLotModel
from app.api.v1.module_bre.tree.model import TreeModel
from app.api.v1.module_bre.rootstock.model import RootstockModel
from app.api.v1.module_bre.trial_study_entry.model import TrialStudyEntryModel
from app.api.v1.module_bre.trial_study.model import TrialStudyModel
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 PlantingService:
"""定植管理 模块服务层"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
async def _attach_fk_labels(self, items: list[PlantingOutSchema]) -> None:
if not items:
return
crud = BreedingPlantingCRUD(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"))
seedling_id_ids = {getattr(it, "seedling_id") for it in items if getattr(it, "seedling_id")}
if seedling_id_ids:
refs = await BreedingSeedlingCRUD(self.auth, self.db).get_list(search={"id": ("in", list(seedling_id_ids))})
ref_map = {r.id: getattr(r, "sowing_date") for r in refs}
for it in items:
it.seedling_name = ref_map.get(getattr(it, "seedling_id"))
lot_ids = {getattr(it, "seed_lot_id") for it in items if getattr(it, "seed_lot_id")}
if lot_ids:
refs = await BreedingSeedLotCRUD(self.auth, self.db).get_list(search={"id": ("in", list(lot_ids))})
ref_map = {r.id: getattr(r, "lot_code") for r in refs}
for it in items:
it.lot_code = ref_map.get(getattr(it, "seed_lot_id"))
rootstock_id_ids = {getattr(it, "rootstock_id") for it in items if getattr(it, "rootstock_id")}
if rootstock_id_ids:
refs = await BreedingRootstockCRUD(self.auth, self.db).get_list(search={"id": ("in", list(rootstock_id_ids))})
ref_map = {r.id: getattr(r, "rootstock_name") for r in refs}
for it in items:
it.rootstock_name = ref_map.get(getattr(it, "rootstock_id"))
entry_id_ids = {getattr(it, "entry_id") for it in items if getattr(it, "entry_id")}
if entry_id_ids:
refs = await BreedingTrialStudyEntryCRUD(self.auth, self.db).get_list(search={"id": ("in", list(entry_id_ids))})
ref_map = {r.id: getattr(r, "entry_number") for r in refs}
for it in items:
it.entry_number = ref_map.get(getattr(it, "entry_id"))
trial_study_id_ids = {getattr(it, "trial_study_id") for it in items if getattr(it, "trial_study_id")}
if trial_study_id_ids:
refs = await BreedingTrialStudyCRUD(self.auth, self.db).get_list(search={"id": ("in", list(trial_study_id_ids))})
ref_map = {r.id: getattr(r, "study_name") for r in refs}
for it in items:
it.study_name = ref_map.get(getattr(it, "trial_study_id"))
async def detail(self, id: int) -> PlantingOutSchema:
obj = await BreedingPlantingCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="该定植不存在")
out = PlantingOutSchema.model_validate(obj)
await self._attach_fk_labels([out])
return out
async def get_list(
self,
search: PlantingQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> list[PlantingOutSchema]:
obj_list = await BreedingPlantingCRUD(self.auth, self.db).get_list(
search=search_to_dict(search), order_by=order_by
)
outs = [PlantingOutSchema.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: PlantingQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> PageResultSchema[PlantingOutSchema]:
offset = (page_no - 1) * page_size
result = await BreedingPlantingCRUD(self.auth, self.db).page(
offset=offset,
limit=page_size,
order_by=order_by or [{"id": "asc"}],
search=search_to_dict(search, {}),
out_schema=PlantingOutSchema,
)
await self._attach_fk_labels(result.items)
return result
async def create(self, data: PlantingCreateSchema) -> PlantingOutSchema:
await assert_parents_exist(
self.db,
[
(CrossCombinationModel, data.combination_id, '杂交组合'),
(BreedingPlotModel, data.plot_id, '试验地块'),
(PersonnelModel, data.bre_personnel_id, '育种人员'),
(SeedlingModel, data.seedling_id, '实生苗'),
(SeedLotModel, data.seed_lot_id, '种子批'),
(RootstockModel, data.rootstock_id, '砧木'),
(TrialStudyEntryModel, data.entry_id, '参试条目'),
(TrialStudyModel, data.trial_study_id, '试验研究点'),
],
)
# 选择强度链:种子批 used_count 由育苗阶段累加(§3.13),定植消耗的是苗非种,
# 不再二次 adjust_used,避免同一种子批被育苗+定植重复累加(虚增用种量)
obj = await BreedingPlantingCRUD(self.auth, self.db).create(data=data)
out = PlantingOutSchema.model_validate(obj)
await self._attach_fk_labels([out])
return out
async def update(self, id: int, data: PlantingUpdateSchema) -> PlantingOutSchema:
obj = await BreedingPlantingCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="更新失败,该定植不存在")
await assert_parents_exist(
self.db,
[
(CrossCombinationModel, data.combination_id, '杂交组合'),
(BreedingPlotModel, data.plot_id, '试验地块'),
(PersonnelModel, data.bre_personnel_id, '育种人员'),
(SeedlingModel, data.seedling_id, '实生苗'),
(SeedLotModel, data.seed_lot_id, '种子批'),
(RootstockModel, data.rootstock_id, '砧木'),
(TrialStudyEntryModel, data.entry_id, '参试条目'),
(TrialStudyModel, data.trial_study_id, '试验研究点'),
],
)
obj = await BreedingPlantingCRUD(self.auth, self.db).update(id=id, data=data)
out = PlantingOutSchema.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 BreedingPlantingCRUD(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,
[
(TreeModel, 'planting_id', '单株'),
],
)
# 定植删除不触碰种子批 used_count(育苗阶段已记账)
await BreedingPlantingCRUD(self.auth, self.db).delete(ids=ids)
async def list_options(self) -> list[dict[str, Any]]:
"""供前端下拉选择使用:返回 [{value, label}]。"""
obj_list = await BreedingPlantingCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
return [{"value": o.id, "label": o.planting_date} for o in obj_list]
@staticmethod
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
mapping_dict = {
"combination_name": "杂交组合",
"plot_name": "试验地块",
"planting_date": "定植日期",
"tree_count": "定植株数",
"row_no": "行号",
"col_no": "列号",
"bre_personnel_name": "定植人",
"seedling_name": "育苗批次",
"rootstock_name": "砧木",
"entry_number": "参试编号",
"study_name": "试验研究点",
"block_no": "区组号",
"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",
"试验地块": "plot_id",
"定植日期": "planting_date",
"定植株数": "tree_count",
"行号": "row_no",
"列号": "col_no",
"定植人": "bre_personnel_id",
"育苗批次": "seedling_id",
"砧木": "rootstock_id",
"参试编号": "entry_id",
"试验研究点": "trial_study_id",
"区组号": "block_no",
"备注": "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}
seedling_id_refs = await BreedingSeedlingCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
seedling_id_map = {getattr(r, "sowing_date"): r.id for r in seedling_id_refs}
rootstock_id_refs = await BreedingRootstockCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
rootstock_id_map = {getattr(r, "rootstock_name"): r.id for r in rootstock_id_refs}
entry_id_refs = await BreedingTrialStudyEntryCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
entry_id_map = {str(getattr(r, "entry_number")): r.id for r in entry_id_refs}
trial_study_id_refs = await BreedingTrialStudyCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
trial_study_id_map = {getattr(r, "study_name"): r.id for r in trial_study_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"]
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 = BreedingPlantingCRUD(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
plot_id_val = plot_id_map.get(str(row.get("plot_id")).strip()) if not _is_blank(row.get("plot_id")) else None
bre_personnel_id_val = bre_personnel_id_map.get(str(row.get("bre_personnel_id")).strip()) if not _is_blank(row.get("bre_personnel_id")) else None
seedling_id_val = seedling_id_map.get(str(row.get("seedling_id")).strip()) if not _is_blank(row.get("seedling_id")) else None
rootstock_id_val = rootstock_id_map.get(str(row.get("rootstock_id")).strip()) if not _is_blank(row.get("rootstock_id")) else None
entry_id_val = entry_id_map.get(str(row.get("entry_id")).strip()) if not _is_blank(row.get("entry_id")) else None
trial_study_id_val = trial_study_id_map.get(str(row.get("trial_study_id")).strip()) if not _is_blank(row.get("trial_study_id")) else None
fields = {
"combination_id": combination_id_val,
"plot_id": plot_id_val,
"planting_date": _none_if_blank(row.get("planting_date")),
"tree_count": _to_int(row.get("tree_count")),
"row_no": _to_int(row.get("row_no")),
"col_no": _to_int(row.get("col_no")),
"bre_personnel_id": bre_personnel_id_val,
"seedling_id": seedling_id_val,
"rootstock_id": rootstock_id_val,
"entry_id": entry_id_val,
"trial_study_id": trial_study_id_val,
"block_no": _to_int(row.get("block_no")),
"remark": _none_if_blank(row.get("remark")),
}
create_data = PlantingCreateSchema(**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 = [
"杂交组合",
"试验地块",
"定植日期",
"定植株数",
"行号",
"列号",
"定植人",
"育苗批次",
"砧木",
"参试编号",
"试验研究点",
"区组号",
"备注",
]
selector_header_list = []
option_list = [
]
return ExcelUtil.get_excel_template(
header_list=header_list,
selector_header_list=selector_header_list,
option_list=option_list,
)