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 (
|
||||
SelectionRuleCreateSchema,
|
||||
SelectionRuleOutSchema,
|
||||
SelectionRuleQueryParam,
|
||||
SelectionRuleUpdateSchema,
|
||||
)
|
||||
from .service import SelectionRuleService
|
||||
|
||||
SelectionRuleRouter = APIRouter(route_class=OperationLogRoute, prefix="/selection_rule", tags=["选择规则"])
|
||||
|
||||
|
||||
@SelectionRuleRouter.get("/detail/{id}", summary="获取选择规则详情", response_model=ResponseSchema[SelectionRuleOutSchema])
|
||||
async def get_selection_rule__detail_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:detail"]))],
|
||||
id: Annotated[int, Path(description="选择规则ID")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SelectionRuleService(auth, db)
|
||||
result_dict = await service.detail(id=id)
|
||||
return SuccessResponse(data=result_dict, msg="获取选择规则详情成功")
|
||||
|
||||
|
||||
@SelectionRuleRouter.get("/list", summary="分页查询选择规则", response_model=ResponseSchema[PageResultSchema[SelectionRuleOutSchema]])
|
||||
async def get_selection_rule__list_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:query"]))],
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[SelectionRuleQueryParam, Query()],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SelectionRuleService(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="查询选择规则列表成功")
|
||||
|
||||
|
||||
@SelectionRuleRouter.get("/options", summary="选择规则下拉选项")
|
||||
async def get_selection_rule__options_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:query"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SelectionRuleService(auth, db)
|
||||
options = await service.list_options()
|
||||
return SuccessResponse(data=options, msg="获取选择规则选项成功")
|
||||
|
||||
|
||||
@SelectionRuleRouter.post("/create", summary="创建选择规则", response_model=ResponseSchema[SelectionRuleOutSchema])
|
||||
async def create_selection_rule__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:create"]))],
|
||||
data: Annotated[SelectionRuleCreateSchema, Body(description="创建参数")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SelectionRuleService(auth, db)
|
||||
result_dict = await service.create(data=data)
|
||||
return SuccessResponse(data=result_dict, msg="创建选择规则成功")
|
||||
|
||||
|
||||
@SelectionRuleRouter.put("/update/{id}", summary="修改选择规则", response_model=ResponseSchema[SelectionRuleOutSchema])
|
||||
async def update_selection_rule__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:update"]))],
|
||||
id: Annotated[int, Path(description="选择规则ID")],
|
||||
data: Annotated[SelectionRuleUpdateSchema, Body(description="修改参数")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SelectionRuleService(auth, db)
|
||||
result_dict = await service.update(id=id, data=data)
|
||||
return SuccessResponse(data=result_dict, msg="修改选择规则成功")
|
||||
|
||||
|
||||
@SelectionRuleRouter.delete("/delete", summary="删除选择规则", response_model=ResponseSchema[None])
|
||||
async def delete_selection_rule__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:delete"]))],
|
||||
ids: Annotated[list[int], Body(description="ID列表")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SelectionRuleService(auth, db)
|
||||
await service.delete(ids=ids)
|
||||
return SuccessResponse(msg="删除选择规则成功")
|
||||
|
||||
|
||||
@SelectionRuleRouter.post("/export", summary="导出选择规则")
|
||||
async def export_selection_rule__controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:export"]))],
|
||||
search: Annotated[SelectionRuleQueryParam, Query()],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> StreamingResponse:
|
||||
service = SelectionRuleService(auth, db)
|
||||
result_dict_list = await service.get_list(search=search)
|
||||
export_result = SelectionRuleService.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')}"},
|
||||
)
|
||||
|
||||
|
||||
@SelectionRuleRouter.post("/import", summary="导入选择规则", response_model=ResponseSchema[ImportResultSchema])
|
||||
async def import_selection_rule__controller(
|
||||
file: Annotated[UploadFile, File(description="导入文件")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:selection_rule:import"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = SelectionRuleService(auth, db)
|
||||
batch_import_result = await service.batch_import(file=file, update_support=True)
|
||||
return SuccessResponse(data=batch_import_result, msg="导入选择规则成功")
|
||||
|
||||
|
||||
@SelectionRuleRouter.post("/download/template", summary="获取选择规则导入模板", dependencies=[Depends(AuthPermission(["module_bre:selection_rule:download"]))])
|
||||
async def download_selection_rule__template_controller() -> StreamingResponse:
|
||||
import_template_result = SelectionRuleService.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 SelectionRuleModel
|
||||
|
||||
|
||||
class BreedingSelectionRuleCRUD(CRUDBase[SelectionRuleModel, Any, Any]):
|
||||
"""选择规则 CRUD —— 直接复用 CRUDBase(已自动注入数据权限过滤)。"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
super().__init__(SelectionRuleModel, auth, db)
|
||||
|
||||
|
||||
selection_rule_crud = BreedingSelectionRuleCRUD
|
||||
@@ -0,0 +1,40 @@
|
||||
"""选择规则 数据模型"""
|
||||
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 SelectionRuleModel(ModelMixin, UserMixin, MappedBase):
|
||||
"""选择规则 主数据表。"""
|
||||
|
||||
__tablename__ = "bre_selection_rule"
|
||||
|
||||
rule_name: Mapped[str] = mapped_column(String(128), nullable=False, comment="规则名称")
|
||||
|
||||
target_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("bre_target.id", ondelete="CASCADE"),
|
||||
index=True, nullable=False, comment="育种目标"
|
||||
)
|
||||
|
||||
stage: Mapped[str | None] = mapped_column(String(32), nullable=True, comment="适用阶段", default=None)
|
||||
|
||||
conditions_json: Mapped[str] = mapped_column(Text, nullable=False, comment="条件(JSON)")
|
||||
|
||||
logic: Mapped[str | None] = mapped_column(String(8), nullable=True, comment="逻辑关系", default=None)
|
||||
|
||||
action: Mapped[str | None] = mapped_column(String(16), nullable=True, comment="动作", default=None)
|
||||
|
||||
priority: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="优先级", default=None)
|
||||
|
||||
enabled: Mapped[str | None] = mapped_column(String(1), 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_selection_rule_created_deleted", "created_time", "is_deleted"),
|
||||
)
|
||||
@@ -0,0 +1,63 @@
|
||||
from app.core.base_schema import CommonSchema
|
||||
"""选择规则 —— Pydantic 校验/序列化模型。"""
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class SelectionRuleBaseSchema(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
rule_name: str = Field(..., description="规则名称")
|
||||
target_id: int = Field(..., description="育种目标")
|
||||
stage: str | None = Field(default=None, description="适用阶段")
|
||||
conditions_json: str = Field(..., description="条件(JSON)")
|
||||
logic: str | None = Field(default=None, description="逻辑关系")
|
||||
action: str | None = Field(default=None, description="动作")
|
||||
priority: int | None = Field(default=None, description="优先级")
|
||||
enabled: str | None = Field(default=None, description="是否启用")
|
||||
remark: str | None = Field(default=None, description="备注")
|
||||
|
||||
|
||||
class SelectionRuleCreateSchema(SelectionRuleBaseSchema):
|
||||
pass
|
||||
|
||||
|
||||
class SelectionRuleUpdateSchema(SelectionRuleBaseSchema):
|
||||
rule_name: str | None = Field(default=None, description="规则名称")
|
||||
target_id: int | None = Field(default=None, description="育种目标")
|
||||
stage: str | None = Field(default=None, description="适用阶段")
|
||||
conditions_json: str | None = Field(default=None, description="条件(JSON)")
|
||||
logic: str | None = Field(default=None, description="逻辑关系")
|
||||
action: str | None = Field(default=None, description="动作")
|
||||
priority: int | None = Field(default=None, description="优先级")
|
||||
enabled: str | None = Field(default=None, description="是否启用")
|
||||
remark: str | None = Field(default=None, description="备注")
|
||||
|
||||
|
||||
class SelectionRuleOutSchema(SelectionRuleBaseSchema):
|
||||
id: int
|
||||
uuid: str
|
||||
rule_name: str | None = None
|
||||
target_name: str | None = None # 由 Service 层联表填充
|
||||
stage: str | None = None
|
||||
conditions_json: str | None = None
|
||||
logic: str | None = None
|
||||
action: str | None = None
|
||||
priority: int | None = None
|
||||
enabled: str | 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 SelectionRuleQueryParam(BaseModel):
|
||||
rule_name: str | None = Field(default=None, description="规则名称", json_schema_extra={"q": "like"})
|
||||
target_id: int | None = Field(default=None, description="育种目标", json_schema_extra={"q": "eq"})
|
||||
stage: str | None = Field(default=None, description="适用阶段", json_schema_extra={"q": "eq"})
|
||||
logic: str | None = Field(default=None, description="逻辑关系", json_schema_extra={"q": "eq"})
|
||||
action: str | None = Field(default=None, description="动作", json_schema_extra={"q": "eq"})
|
||||
enabled: str | None = Field(default=None, description="是否启用", json_schema_extra={"q": "eq"})
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
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 BreedingSelectionRuleCRUD
|
||||
from .schema import (
|
||||
SelectionRuleCreateSchema,
|
||||
SelectionRuleOutSchema,
|
||||
SelectionRuleQueryParam,
|
||||
SelectionRuleUpdateSchema,
|
||||
)
|
||||
from app.api.v1.module_bre.target.crud import BreedingTargetCRUD
|
||||
|
||||
|
||||
|
||||
from app.core.base_crud import assert_no_children, assert_parents_exist
|
||||
from app.api.v1.module_bre.target.model import TargetModel
|
||||
|
||||
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 SelectionRuleService:
|
||||
"""选择规则 模块服务层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
self.auth = auth
|
||||
self.db = db
|
||||
|
||||
async def _attach_fk_labels(self, items: list[SelectionRuleOutSchema]) -> None:
|
||||
if not items:
|
||||
return
|
||||
crud = BreedingSelectionRuleCRUD(self.auth, self.db)
|
||||
target_id_ids = {getattr(it, "target_id") for it in items if getattr(it, "target_id")}
|
||||
if target_id_ids:
|
||||
refs = await BreedingTargetCRUD(self.auth, self.db).get_list(search={"id": ("in", list(target_id_ids))})
|
||||
ref_map = {r.id: getattr(r, "target_name") for r in refs}
|
||||
for it in items:
|
||||
it.target_name = ref_map.get(getattr(it, "target_id"))
|
||||
|
||||
async def detail(self, id: int) -> SelectionRuleOutSchema:
|
||||
obj = await BreedingSelectionRuleCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该选择规则不存在")
|
||||
out = SelectionRuleOutSchema.model_validate(obj)
|
||||
await self._attach_fk_labels([out])
|
||||
return out
|
||||
|
||||
async def get_list(
|
||||
self,
|
||||
search: SelectionRuleQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> list[SelectionRuleOutSchema]:
|
||||
obj_list = await BreedingSelectionRuleCRUD(self.auth, self.db).get_list(
|
||||
search=search_to_dict(search), order_by=order_by
|
||||
)
|
||||
outs = [SelectionRuleOutSchema.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: SelectionRuleQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> PageResultSchema[SelectionRuleOutSchema]:
|
||||
offset = (page_no - 1) * page_size
|
||||
result = await BreedingSelectionRuleCRUD(self.auth, self.db).page(
|
||||
offset=offset,
|
||||
limit=page_size,
|
||||
order_by=order_by or [{"id": "asc"}],
|
||||
search=search_to_dict(search, {}),
|
||||
out_schema=SelectionRuleOutSchema,
|
||||
)
|
||||
await self._attach_fk_labels(result.items)
|
||||
return result
|
||||
|
||||
async def create(self, data: SelectionRuleCreateSchema) -> SelectionRuleOutSchema:
|
||||
await assert_parents_exist(
|
||||
self.db,
|
||||
[
|
||||
(TargetModel, data.target_id, '育种目标'),
|
||||
],
|
||||
)
|
||||
obj = await BreedingSelectionRuleCRUD(self.auth, self.db).create(data=data)
|
||||
out = SelectionRuleOutSchema.model_validate(obj)
|
||||
await self._attach_fk_labels([out])
|
||||
return out
|
||||
|
||||
async def update(self, id: int, data: SelectionRuleUpdateSchema) -> SelectionRuleOutSchema:
|
||||
obj = await BreedingSelectionRuleCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="更新失败,该选择规则不存在")
|
||||
await assert_parents_exist(
|
||||
self.db,
|
||||
[
|
||||
(TargetModel, data.target_id, '育种目标'),
|
||||
],
|
||||
)
|
||||
obj = await BreedingSelectionRuleCRUD(self.auth, self.db).update(id=id, data=data)
|
||||
out = SelectionRuleOutSchema.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 BreedingSelectionRuleCRUD(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 BreedingSelectionRuleCRUD(self.auth, self.db).delete(ids=ids)
|
||||
|
||||
async def list_options(self) -> list[dict[str, Any]]:
|
||||
"""供前端下拉选择使用:返回 [{value, label}]。"""
|
||||
obj_list = await BreedingSelectionRuleCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
return [{"value": o.id, "label": o.rule_name} for o in obj_list]
|
||||
|
||||
@staticmethod
|
||||
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
|
||||
mapping_dict = {
|
||||
"rule_name": "规则名称",
|
||||
"target_name": "育种目标",
|
||||
"stage": "适用阶段",
|
||||
"conditions_json": "条件(JSON)",
|
||||
"logic": "逻辑关系",
|
||||
"action": "动作",
|
||||
"priority": "优先级",
|
||||
"enabled": "是否启用",
|
||||
"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 = {
|
||||
"规则名称": "rule_name",
|
||||
"育种目标": "target_id",
|
||||
"适用阶段": "stage",
|
||||
"条件(JSON)": "conditions_json",
|
||||
"逻辑关系": "logic",
|
||||
"动作": "action",
|
||||
"优先级": "priority",
|
||||
"是否启用": "enabled",
|
||||
"备注": "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)}")
|
||||
target_id_refs = await BreedingTargetCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
||||
target_id_map = {getattr(r, "target_name"): r.id for r in target_id_refs}
|
||||
mapped_rows = []
|
||||
for row in rows:
|
||||
mapped_rows.append({en: row.get(ch) for ch, en in header_dict.items()})
|
||||
required_fields = ["rule_name", "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 = BreedingSelectionRuleCRUD(self.auth, self.db)
|
||||
for i, row in enumerate(mapped_rows, start=1):
|
||||
try:
|
||||
target_id_val = target_id_map.get(str(row.get("target_id")).strip()) if not _is_blank(row.get("target_id")) else None
|
||||
fields = {
|
||||
"rule_name": _none_if_blank(row.get("rule_name")),
|
||||
"target_id": target_id_val,
|
||||
"stage": _none_if_blank(row.get("stage")),
|
||||
"conditions_json": _none_if_blank(row.get("conditions_json")),
|
||||
"logic": _none_if_blank(row.get("logic")),
|
||||
"action": _none_if_blank(row.get("action")),
|
||||
"priority": _to_int(row.get("priority")),
|
||||
"enabled": _none_if_blank(row.get("enabled")),
|
||||
"remark": _none_if_blank(row.get("remark")),
|
||||
}
|
||||
create_data = SelectionRuleCreateSchema(**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 = [
|
||||
"规则名称",
|
||||
"育种目标",
|
||||
"适用阶段",
|
||||
"条件(JSON)",
|
||||
"逻辑关系",
|
||||
"动作",
|
||||
"优先级",
|
||||
"是否启用",
|
||||
"备注",
|
||||
]
|
||||
selector_header_list = ["逻辑关系", "动作", "是否启用"]
|
||||
option_list = [
|
||||
{"逻辑关系": ["and", "or"]},
|
||||
{"动作": ["keep", "eliminate"]},
|
||||
{"是否启用": ["1", "0"]},
|
||||
]
|
||||
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