init: 初始化 dpb 桃育种系统代码库
前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
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 (
|
||||
SeedLotCreateSchema,
|
||||
SeedLotOutSchema,
|
||||
SeedLotQueryParam,
|
||||
SeedLotUpdateSchema,
|
||||
)
|
||||
from .service import SeedLotService
|
||||
|
||||
SeedLotRouter = APIRouter(route_class=OperationLogRoute, prefix="/seed_lot", tags=["种子批管理"])
|
||||
|
||||
|
||||
@SeedLotRouter.get("/detail/{id}", summary="获取种子批详情", response_model=ResponseSchema[SeedLotOutSchema])
|
||||
async def get_seed_lot__detail_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:detail"]))],
|
||||
id: Annotated[int, Path(description="种子批ID")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SeedLotService(auth, db)
|
||||
result_dict = await service.detail(id=id)
|
||||
return SuccessResponse(data=result_dict, msg="获取种子批详情成功")
|
||||
|
||||
|
||||
@SeedLotRouter.get("/list", summary="分页查询种子批", response_model=ResponseSchema[PageResultSchema[SeedLotOutSchema]])
|
||||
async def get_seed_lot__list_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:query"]))],
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[SeedLotQueryParam, Query()],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SeedLotService(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="查询种子批列表成功")
|
||||
|
||||
|
||||
@SeedLotRouter.get("/options", summary="种子批下拉选项")
|
||||
async def get_seed_lot__options_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:query"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SeedLotService(auth, db)
|
||||
options = await service.list_options()
|
||||
return SuccessResponse(data=options, msg="获取种子批选项成功")
|
||||
|
||||
|
||||
@SeedLotRouter.post("/create", summary="创建种子批", response_model=ResponseSchema[SeedLotOutSchema])
|
||||
async def create_seed_lot__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:create"]))],
|
||||
data: Annotated[SeedLotCreateSchema, Body(description="创建参数")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SeedLotService(auth, db)
|
||||
result_dict = await service.create(data=data)
|
||||
return SuccessResponse(data=result_dict, msg="创建种子批成功")
|
||||
|
||||
|
||||
@SeedLotRouter.put("/update/{id}", summary="修改种子批", response_model=ResponseSchema[SeedLotOutSchema])
|
||||
async def update_seed_lot__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:update"]))],
|
||||
id: Annotated[int, Path(description="种子批ID")],
|
||||
data: Annotated[SeedLotUpdateSchema, Body(description="修改参数")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SeedLotService(auth, db)
|
||||
result_dict = await service.update(id=id, data=data)
|
||||
return SuccessResponse(data=result_dict, msg="修改种子批成功")
|
||||
|
||||
|
||||
@SeedLotRouter.delete("/delete", summary="删除种子批", response_model=ResponseSchema[None])
|
||||
async def delete_seed_lot__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:delete"]))],
|
||||
ids: Annotated[list[int], Body(description="ID列表")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SeedLotService(auth, db)
|
||||
await service.delete(ids=ids)
|
||||
return SuccessResponse(msg="删除种子批成功")
|
||||
|
||||
|
||||
@SeedLotRouter.post("/export", summary="导出种子批")
|
||||
async def export_seed_lot__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:export"]))],
|
||||
search: Annotated[SeedLotQueryParam, Query()],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> StreamingResponse:
|
||||
service = SeedLotService(auth, db)
|
||||
result_dict_list = await service.get_list(search=search)
|
||||
export_result = SeedLotService.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')}"},
|
||||
)
|
||||
|
||||
|
||||
@SeedLotRouter.post("/import", summary="导入种子批", response_model=ResponseSchema[ImportResultSchema])
|
||||
async def import_seed_lot__controller(
|
||||
file: Annotated[UploadFile, File(description="导入文件")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:seed_lot:import"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SeedLotService(auth, db)
|
||||
batch_import_result = await service.batch_import(file=file, update_support=True)
|
||||
return SuccessResponse(data=batch_import_result, msg="导入种子批成功")
|
||||
|
||||
|
||||
@SeedLotRouter.post("/download/template", summary="获取种子批导入模板", dependencies=[Depends(AuthPermission(["module_bre:seed_lot:download"]))])
|
||||
async def download_seed_lot__template_controller() -> StreamingResponse:
|
||||
import_template_result = SeedLotService.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 SeedLotModel
|
||||
|
||||
|
||||
class BreedingSeedLotCRUD(CRUDBase[SeedLotModel, Any, Any]):
|
||||
"""种子批 CRUD —— 直接复用 CRUDBase(已自动注入数据权限过滤)。"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
super().__init__(SeedLotModel, auth, db)
|
||||
|
||||
|
||||
seed_lot_crud = BreedingSeedLotCRUD
|
||||
@@ -0,0 +1,48 @@
|
||||
"""种子批(库存) 数据模型"""
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import Date, ForeignKey, Index, Integer, Numeric, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.base_model import MappedBase, ModelMixin, UserMixin
|
||||
|
||||
|
||||
class SeedLotModel(ModelMixin, UserMixin, MappedBase):
|
||||
"""种子批·库存(规格 §3.13;used_count 派生 remaining,选择强度链源头)。"""
|
||||
|
||||
__tablename__ = "bre_seed_lot"
|
||||
|
||||
combination_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("bre_cross_combination.id", ondelete="CASCADE"),
|
||||
index=True, nullable=False, comment="杂交组合"
|
||||
)
|
||||
|
||||
pollination_id: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("bre_pollination.id", ondelete="SET NULL"),
|
||||
index=True, nullable=True, comment="授粉记录(关联补链)", default=None
|
||||
)
|
||||
|
||||
lot_code: Mapped[str] = mapped_column(String(64), nullable=False, index=True, comment="种子批号")
|
||||
|
||||
harvest_year: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="收获年份", default=None)
|
||||
|
||||
seed_count: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="收获粒数(选择强度源头)", default=None)
|
||||
|
||||
used_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="已取用粒数(seedling 按出苗数累加)")
|
||||
|
||||
germination_rate: Mapped[float | None] = mapped_column(Numeric(5, 2), nullable=True, comment="发芽率%(活力)", default=None)
|
||||
|
||||
storage_type: Mapped[str | None] = mapped_column(String(16), nullable=True, comment="存储类型(种子库/离体/DNA)", default=None)
|
||||
|
||||
storage_location: Mapped[str | None] = mapped_column(String(128), nullable=True, comment="存放位置", default=None)
|
||||
|
||||
test_date: Mapped[date | None] = mapped_column(Date, 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_seed_lot_created_deleted", "created_time", "is_deleted"),
|
||||
Index("uq_bre_seed_lot_code", "lot_code", unique=True),
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""种子批管理 —— Pydantic 校验/序列化模型。"""
|
||||
from datetime import date, datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.core.base_schema import CommonSchema
|
||||
|
||||
|
||||
class SeedLotBaseSchema(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
combination_id: int = Field(..., description="杂交组合")
|
||||
pollination_id: int | None = Field(default=None, description="授粉记录(关联补链)")
|
||||
lot_code: str = Field(..., description="种子批号")
|
||||
harvest_year: int | None = Field(default=None, description="收获年份")
|
||||
seed_count: int | None = Field(default=None, description="收获粒数(选择强度源头)")
|
||||
used_count: int = Field(default=0, description="已取用粒数")
|
||||
germination_rate: float | None = Field(default=None, description="发芽率%")
|
||||
storage_type: str | None = Field(default=None, description="存储类型(种子库/离体/DNA)")
|
||||
storage_location: str | None = Field(default=None, description="存放位置")
|
||||
test_date: date | None = Field(default=None, description="活力检测日期")
|
||||
remark: str | None = Field(default=None, description="备注")
|
||||
|
||||
|
||||
class SeedLotCreateSchema(SeedLotBaseSchema):
|
||||
pass
|
||||
|
||||
|
||||
class SeedLotUpdateSchema(SeedLotBaseSchema):
|
||||
combination_id: int | None = Field(default=None, description="杂交组合")
|
||||
pollination_id: int | None = Field(default=None, description="授粉记录(关联补链)")
|
||||
lot_code: str | None = Field(default=None, description="种子批号")
|
||||
harvest_year: int | None = Field(default=None, description="收获年份")
|
||||
seed_count: int | None = Field(default=None, description="收获粒数(选择强度源头)")
|
||||
used_count: int | None = Field(default=None, description="已取用粒数")
|
||||
germination_rate: float | None = Field(default=None, description="发芽率%")
|
||||
storage_type: str | None = Field(default=None, description="存储类型(种子库/离体/DNA)")
|
||||
storage_location: str | None = Field(default=None, description="存放位置")
|
||||
test_date: date | None = Field(default=None, description="活力检测日期")
|
||||
remark: str | None = Field(default=None, description="备注")
|
||||
|
||||
|
||||
class SeedLotOutSchema(SeedLotBaseSchema):
|
||||
id: int
|
||||
uuid: str
|
||||
combination_name: str | None = None # 联表填充(组合编号)
|
||||
pollination_name: str | None = None # 联表填充(授粉记录)
|
||||
remaining: int | None = None # 派生剩余可播种量 = seed_count - used_count
|
||||
lot_code: str | None = None
|
||||
combination_id: int | None = None
|
||||
pollination_id: int | None = None
|
||||
harvest_year: int | None = None
|
||||
seed_count: int | None = None
|
||||
used_count: int | None = None
|
||||
germination_rate: float | None = None
|
||||
storage_type: str | None = None
|
||||
storage_location: str | None = None
|
||||
test_date: date | 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 SeedLotQueryParam(BaseModel):
|
||||
lot_code: str | None = Field(default=None, description="种子批号", json_schema_extra={"q": "like"})
|
||||
combination_id: int | None = Field(default=None, description="杂交组合", json_schema_extra={"q": "eq"})
|
||||
pollination_id: int | None = Field(default=None, description="授粉记录", json_schema_extra={"q": "eq"})
|
||||
harvest_year: int | None = Field(default=None, description="收获年份", json_schema_extra={"q": "eq"})
|
||||
storage_type: str | None = Field(default=None, description="存储类型", json_schema_extra={"q": "eq"})
|
||||
@@ -0,0 +1,314 @@
|
||||
from typing import Any
|
||||
|
||||
from fastapi import UploadFile
|
||||
from sqlalchemy import func, select, update
|
||||
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.bre_audit_ctx import bre_audit_suppress
|
||||
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 BreedingSeedLotCRUD
|
||||
from .model import SeedLotModel
|
||||
from .schema import (
|
||||
SeedLotCreateSchema,
|
||||
SeedLotOutSchema,
|
||||
SeedLotQueryParam,
|
||||
SeedLotUpdateSchema,
|
||||
)
|
||||
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.pollination.model import PollinationModel
|
||||
from app.api.v1.module_bre.pollination.crud import BreedingPollinationCRUD
|
||||
|
||||
|
||||
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_int(v: Any) -> int | None:
|
||||
if _is_blank(v):
|
||||
return None
|
||||
try:
|
||||
return int(float(v))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
async def adjust_used(db: AsyncSession, lot_id: int | None, delta: int) -> None:
|
||||
"""种子批已用粒数累加(seedling 引用该批时按出苗数维护,clamp >= 0)。
|
||||
|
||||
选择强度链前段:seed_count(获种) → used_count(已用) → remaining 派生。
|
||||
delta 可正可负(新建累加 / 删除或解除关联回退)。
|
||||
"""
|
||||
if lot_id is None or not delta:
|
||||
return
|
||||
await db.execute(
|
||||
update(SeedLotModel)
|
||||
.where(SeedLotModel.id == lot_id, SeedLotModel.is_deleted.is_(False))
|
||||
.values(used_count=func.greatest(func.coalesce(SeedLotModel.used_count, 0) + delta, 0))
|
||||
)
|
||||
|
||||
|
||||
class SeedLotService:
|
||||
"""种子批管理 模块服务层"""
|
||||
|
||||
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 = [SeedLotModel.lot_code == code.strip(), SeedLotModel.is_deleted.is_(False)]
|
||||
if exclude_id is not None:
|
||||
conditions.append(SeedLotModel.id != exclude_id)
|
||||
result = await self.db.execute(select(func.count()).select_from(SeedLotModel).where(*conditions))
|
||||
if result.scalar() or 0:
|
||||
raise CustomException(msg=f"种子批号 {code} 已存在", status_code=409)
|
||||
|
||||
async def _check_parents(self, data: SeedLotCreateSchema | SeedLotUpdateSchema) -> None:
|
||||
await assert_parents_exist(
|
||||
self.db,
|
||||
[
|
||||
(CrossCombinationModel, data.combination_id, '杂交组合'),
|
||||
(PollinationModel, data.pollination_id, '授粉记录'),
|
||||
],
|
||||
)
|
||||
|
||||
async def _attach_fk_labels(self, items: list[SeedLotOutSchema]) -> None:
|
||||
if not items:
|
||||
return
|
||||
combo_ids = {getattr(it, "combination_id") for it in items if getattr(it, "combination_id")}
|
||||
if combo_ids:
|
||||
refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(search={"id": ("in", list(combo_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"))
|
||||
poll_ids = {getattr(it, "pollination_id") for it in items if getattr(it, "pollination_id")}
|
||||
if poll_ids:
|
||||
refs = await BreedingPollinationCRUD(self.auth, self.db).get_list(search={"id": ("in", list(poll_ids))})
|
||||
ref_map = {r.id: f"{getattr(r, 'pollination_method') or '授粉'}#{r.id}" for r in refs}
|
||||
for it in items:
|
||||
it.pollination_name = ref_map.get(getattr(it, "pollination_id"))
|
||||
|
||||
def _fill_remaining(self, items: list[SeedLotOutSchema]) -> None:
|
||||
for it in items:
|
||||
if it.seed_count is not None and it.used_count is not None:
|
||||
it.remaining = max(it.seed_count - it.used_count, 0)
|
||||
else:
|
||||
it.remaining = None
|
||||
|
||||
async def detail(self, id: int) -> SeedLotOutSchema:
|
||||
obj = await BreedingSeedLotCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该种子批不存在")
|
||||
out = SeedLotOutSchema.model_validate(obj)
|
||||
await self._attach_fk_labels([out])
|
||||
self._fill_remaining([out])
|
||||
return out
|
||||
|
||||
async def get_list(
|
||||
self,
|
||||
search: SeedLotQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> list[SeedLotOutSchema]:
|
||||
obj_list = await BreedingSeedLotCRUD(self.auth, self.db).get_list(
|
||||
search=search_to_dict(search), order_by=order_by
|
||||
)
|
||||
outs = [SeedLotOutSchema.model_validate(obj) for obj in obj_list]
|
||||
await self._attach_fk_labels(outs)
|
||||
self._fill_remaining(outs)
|
||||
return outs
|
||||
|
||||
async def page(
|
||||
self,
|
||||
page_no: int,
|
||||
page_size: int,
|
||||
search: SeedLotQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> PageResultSchema[SeedLotOutSchema]:
|
||||
offset = (page_no - 1) * page_size
|
||||
result = await BreedingSeedLotCRUD(self.auth, self.db).page(
|
||||
offset=offset,
|
||||
limit=page_size,
|
||||
order_by=order_by or [{"id": "asc"}],
|
||||
search=search_to_dict(search, {}),
|
||||
out_schema=SeedLotOutSchema,
|
||||
)
|
||||
await self._attach_fk_labels(result.items)
|
||||
self._fill_remaining(result.items)
|
||||
return result
|
||||
|
||||
async def create(self, data: SeedLotCreateSchema) -> SeedLotOutSchema:
|
||||
await self._check_code(data.lot_code)
|
||||
await self._check_parents(data)
|
||||
obj = await BreedingSeedLotCRUD(self.auth, self.db).create(data=data)
|
||||
out = SeedLotOutSchema.model_validate(obj)
|
||||
await self._attach_fk_labels([out])
|
||||
self._fill_remaining([out])
|
||||
return out
|
||||
|
||||
async def update(self, id: int, data: SeedLotUpdateSchema) -> SeedLotOutSchema:
|
||||
obj = await BreedingSeedLotCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="更新失败,该种子批不存在")
|
||||
if not _is_blank(data.lot_code):
|
||||
await self._check_code(data.lot_code, exclude_id=id)
|
||||
await self._check_parents(data)
|
||||
obj = await BreedingSeedLotCRUD(self.auth, self.db).update(id=id, data=data)
|
||||
out = SeedLotOutSchema.model_validate(obj)
|
||||
await self._attach_fk_labels([out])
|
||||
self._fill_remaining([out])
|
||||
return out
|
||||
|
||||
async def delete(self, ids: list[int]) -> None:
|
||||
if not ids:
|
||||
raise CustomException(msg="删除失败,删除对象不能为空")
|
||||
objs = await BreedingSeedLotCRUD(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 BreedingSeedLotCRUD(self.auth, self.db).delete(ids=ids)
|
||||
|
||||
async def list_options(self) -> list[dict[str, Any]]:
|
||||
"""供前端下拉选择使用:返回 [{value, label}]。"""
|
||||
obj_list = await BreedingSeedLotCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
return [{"value": o.id, "label": o.lot_code} for o in obj_list]
|
||||
|
||||
@staticmethod
|
||||
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
|
||||
mapping_dict = {
|
||||
"combination_name": "杂交组合",
|
||||
"lot_code": "种子批号",
|
||||
"harvest_year": "收获年份",
|
||||
"seed_count": "收获粒数",
|
||||
"used_count": "已用粒数",
|
||||
"remaining": "剩余粒数",
|
||||
"germination_rate": "发芽率%",
|
||||
"storage_type": "存储类型",
|
||||
"storage_location": "存放位置",
|
||||
"test_date": "检测日期",
|
||||
"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",
|
||||
"种子批号": "lot_code",
|
||||
"收获年份": "harvest_year",
|
||||
"收获粒数": "seed_count",
|
||||
"已用粒数": "used_count",
|
||||
"发芽率%": "germination_rate",
|
||||
"存储类型": "storage_type",
|
||||
"存放位置": "storage_location",
|
||||
"检测日期": "test_date",
|
||||
"备注": "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)}")
|
||||
combo_refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
combo_map = {getattr(r, "combination_code"): r.id for r in combo_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", "lot_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 = BreedingSeedLotCRUD(self.auth, self.db)
|
||||
# 批量导入:抑制逐行审计,仅导入结束汇总记一条 IMPORT 审计行
|
||||
with bre_audit_suppress():
|
||||
for i, row in enumerate(mapped_rows, start=1):
|
||||
try:
|
||||
combo_val = combo_map.get(str(row.get("combination_id")).strip()) if not _is_blank(row.get("combination_id")) else None
|
||||
fields = {
|
||||
"combination_id": combo_val,
|
||||
"lot_code": _none_if_blank(row.get("lot_code")),
|
||||
"harvest_year": _to_int(row.get("harvest_year")),
|
||||
"seed_count": _to_int(row.get("seed_count")),
|
||||
"used_count": _to_int(row.get("used_count")) or 0,
|
||||
"germination_rate": _none_if_blank(row.get("germination_rate")),
|
||||
"storage_type": _none_if_blank(row.get("storage_type")),
|
||||
"storage_location": _none_if_blank(row.get("storage_location")),
|
||||
"test_date": _none_if_blank(row.get("test_date")),
|
||||
"remark": _none_if_blank(row.get("remark")),
|
||||
}
|
||||
create_data = SeedLotCreateSchema(**fields)
|
||||
await self._check_code(create_data.lot_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
|
||||
from app.api.v1.module_bre.audit.service import AuditLogService
|
||||
await AuditLogService.write(
|
||||
self.db,
|
||||
entity_type="bre_seed_lot",
|
||||
entity_id=None,
|
||||
action="IMPORT",
|
||||
new_value=f"valid={success_count}, invalid={len(error_msgs)}",
|
||||
created_id=self.auth.user.id if self.auth.user.id else None,
|
||||
)
|
||||
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 = [
|
||||
"杂交组合",
|
||||
"种子批号",
|
||||
"收获年份",
|
||||
"收获粒数",
|
||||
"已用粒数",
|
||||
"发芽率%",
|
||||
"存储类型",
|
||||
"存放位置",
|
||||
"检测日期",
|
||||
"备注",
|
||||
]
|
||||
return ExcelUtil.get_excel_template(
|
||||
header_list=header_list,
|
||||
selector_header_list=[],
|
||||
option_list=[],
|
||||
)
|
||||
Reference in New Issue
Block a user