Files
dpb/backend/scripts/_backup_query_param/site__service.py.bak
T
34047007@qq.com b95053c52c init: 初始化 dpb 桃育种系统代码库
前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
2026-08-06 00:17:49 +08:00

482 lines
20 KiB
Plaintext

from typing import Any
from fastapi import UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.base_schema import AuthSchema, PageResultSchema
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
from .crud import BreedingPlotCRUD, BreedingSiteCRUD
from .schema import (
BreedingPlotCreateSchema,
BreedingPlotOutSchema,
BreedingPlotQueryParam,
BreedingPlotUpdateSchema,
BreedingSiteCreateSchema,
BreedingSiteOutSchema,
BreedingSiteQueryParam,
BreedingSiteUpdateSchema,
)
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
# ── 基地(site) ───────────────────────────────────────────────────────
class BreedingSiteService:
"""基地管理模块服务层"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
async def detail(self, id: int) -> BreedingSiteOutSchema:
obj = await BreedingSiteCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="该基地不存在")
return BreedingSiteOutSchema.model_validate(obj)
async def get_list(
self,
search: BreedingSiteQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> list[BreedingSiteOutSchema]:
obj_list = await BreedingSiteCRUD(self.auth, self.db).get_list(
search=search_to_dict(search), order_by=order_by
)
return [BreedingSiteOutSchema.model_validate(obj) for obj in obj_list]
async def page(
self,
page_no: int,
page_size: int,
search: BreedingSiteQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> PageResultSchema[BreedingSiteOutSchema]:
offset = (page_no - 1) * page_size
return await BreedingSiteCRUD(self.auth, self.db).page(
offset=offset,
limit=page_size,
order_by=order_by or [{"id": "asc"}],
search=search_to_dict(search, {}),
out_schema=BreedingSiteOutSchema,
)
async def create(self, data: BreedingSiteCreateSchema) -> BreedingSiteOutSchema:
exist_obj = await BreedingSiteCRUD(self.auth, self.db).get(site_name=data.site_name)
if exist_obj:
raise CustomException(msg="创建失败,基地名称已存在")
obj = await BreedingSiteCRUD(self.auth, self.db).create(data=data)
return BreedingSiteOutSchema.model_validate(obj)
async def update(self, id: int, data: BreedingSiteUpdateSchema) -> BreedingSiteOutSchema:
obj = await BreedingSiteCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="更新失败,该基地不存在")
if data.site_name is not None:
exist_obj = await BreedingSiteCRUD(self.auth, self.db).get(site_name=data.site_name)
if exist_obj and exist_obj.id != id:
raise CustomException(msg="更新失败,基地名称重复")
obj = await BreedingSiteCRUD(self.auth, self.db).update(id=id, data=data)
return BreedingSiteOutSchema.model_validate(obj)
async def delete(self, ids: list[int]) -> None:
if not ids:
raise CustomException(msg="删除失败,删除对象不能为空")
objs = await BreedingSiteCRUD(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="删除失败,该基地不存在")
# 软删除基地前,先校验是否存在关联地块,避免产生孤儿数据
for id_ in ids:
plot = await BreedingPlotCRUD(self.auth, self.db).get(site_id=id_)
if plot:
raise CustomException(msg="删除失败,请先删除该基地下的所有试验地块")
await BreedingSiteCRUD(self.auth, self.db).delete(ids=ids)
async def list_options(self) -> list[dict[str, Any]]:
"""供前端下拉选择使用:返回 [{value, label}]。"""
obj_list = await BreedingSiteCRUD(self.auth, self.db).get_list(
order_by=[{"id": "asc"}]
)
return [{"value": o.id, "label": o.site_name} for o in obj_list]
@staticmethod
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
mapping_dict = {
"id": "编号",
"site_name": "基地名称",
"address": "详细地址",
"area": "基地面积(亩)",
"longitude": "经度",
"latitude": "纬度",
"eco_type": "生态区类型",
"remark": "备注",
"created_time": "创建时间",
"created_by": "创建者",
}
data = [dict(item) for item in obj_list]
for item in data:
creator = item.get("created_by")
item["created_by"] = creator.get("name", "未知") if isinstance(creator, dict) else "未知"
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
async def batch_import(self, file: UploadFile, update_support: bool = False) -> str:
header_dict = {
"基地名称": "site_name",
"详细地址": "address",
"基地面积(亩)": "area",
"经度": "longitude",
"纬度": "latitude",
"生态区类型": "eco_type",
"备注": "remark",
}
try:
contents = await file.read()
rows = ExcelUtil.read_excel_to_dicts(contents)
await file.close()
if not rows:
raise CustomException(msg="导入文件为空")
missing_headers = [h for h in header_dict if h not in rows[0]]
if missing_headers:
raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
mapped_rows = []
for row in rows:
mapped_rows.append({en: row.get(ch) for ch, en in header_dict.items()})
required_fields = ["site_name"]
errors = []
for field in required_fields:
missing_indices = [i + 1 for i, r in enumerate(mapped_rows) if _is_blank(r.get(field))]
if missing_indices:
field_name = next(k for k, v in header_dict.items() if v == field)
rows_str = "、".join(str(i) for i in missing_indices)
errors.append(f"{field_name}不能为空,第{rows_str}行")
if errors:
raise CustomException(msg=f"导入失败,以下行缺少必要字段:\n{'; '.join(errors)}")
error_msgs: list[str] = []
success_count = 0
crud = BreedingSiteCRUD(self.auth, self.db)
resolver = DictLabelResolver(self.auth, self.db, ["eco_type"])
for i, row in enumerate(mapped_rows, start=1):
try:
fields = {
"site_name": str(row["site_name"]).strip(),
"address": _none_if_blank(row.get("address")),
"area": _to_float(row.get("area")),
"longitude": _to_float(row.get("longitude")),
"latitude": _to_float(row.get("latitude")),
"eco_type": await resolver.resolve("eco_type", row.get("eco_type")),
"remark": _none_if_blank(row.get("remark")),
}
create_data = BreedingSiteCreateSchema(**fields)
exist_obj = await crud.get(site_name=create_data.site_name)
if exist_obj:
if update_support:
await crud.update(id=exist_obj.id, data=BreedingSiteUpdateSchema(**fields))
success_count += 1
else:
error_msgs.append(f"第{i}行: 基地名称 {create_data.site_name} 已存在")
else:
await crud.create(data=create_data)
success_count += 1
except Exception as e:
error_msgs.append(f"第{i}行: {e!s}")
continue
result = f"成功导入 {success_count} 条数据"
if error_msgs:
result += "\n错误信息:\n" + "\n".join(error_msgs)
return result
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: list[str] = []
option_list: list[dict[str, list[str]]] = []
return ExcelUtil.get_excel_template(
header_list=header_list,
selector_header_list=selector_header_list,
option_list=option_list,
)
# ── 试验地(plot) ──────────────────────────────────────────────────────
class BreedingPlotService:
"""试验地管理模块服务层"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
async def _attach_site_name(self, items: list[BreedingPlotOutSchema]) -> None:
"""批量填充 site_name(按 site_id 关联基地名称)。"""
site_ids = {item.site_id for item in items if item.site_id}
if not site_ids:
return
sites = await BreedingSiteCRUD(self.auth, self.db).get_list(
search={"id": ("in", list(site_ids))}
)
site_map = {s.id: s.site_name for s in sites}
for item in items:
item.site_name = site_map.get(item.site_id)
async def detail(self, id: int) -> BreedingPlotOutSchema:
obj = await BreedingPlotCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="该试验地块不存在")
out = BreedingPlotOutSchema.model_validate(obj)
await self._attach_site_name([out])
return out
async def get_list(
self,
search: BreedingPlotQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> list[BreedingPlotOutSchema]:
obj_list = await BreedingPlotCRUD(self.auth, self.db).get_list(
search=search_to_dict(search), order_by=order_by
)
outs = [BreedingPlotOutSchema.model_validate(obj) for obj in obj_list]
await self._attach_site_name(outs)
return outs
async def page(
self,
page_no: int,
page_size: int,
search: BreedingPlotQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> PageResultSchema[BreedingPlotOutSchema]:
offset = (page_no - 1) * page_size
result = await BreedingPlotCRUD(self.auth, self.db).page(
offset=offset,
limit=page_size,
order_by=order_by or [{"id": "asc"}],
search=search_to_dict(search, {}),
out_schema=BreedingPlotOutSchema,
)
await self._attach_site_name(result.items)
return result
async def create(self, data: BreedingPlotCreateSchema) -> BreedingPlotOutSchema:
site = await BreedingSiteCRUD(self.auth, self.db).get(id=data.site_id)
if not site:
raise CustomException(msg="创建失败,所属基地不存在")
exist_obj = await BreedingPlotCRUD(self.auth, self.db).get(
site_id=data.site_id, plot_code=data.plot_code
)
if exist_obj:
raise CustomException(msg="创建失败,该基地下地块编号已存在")
obj = await BreedingPlotCRUD(self.auth, self.db).create(data=data)
out = BreedingPlotOutSchema.model_validate(obj)
out.site_name = site.site_name
return out
async def update(self, id: int, data: BreedingPlotUpdateSchema) -> BreedingPlotOutSchema:
obj = await BreedingPlotCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="更新失败,该试验地块不存在")
site_id = data.site_id if data.site_id is not None else obj.site_id
if data.plot_code is not None:
exist_obj = await BreedingPlotCRUD(self.auth, self.db).get(
site_id=site_id, plot_code=data.plot_code
)
if exist_obj and exist_obj.id != id:
raise CustomException(msg="更新失败,该基地下地块编号重复")
obj = await BreedingPlotCRUD(self.auth, self.db).update(id=id, data=data)
out = BreedingPlotOutSchema.model_validate(obj)
site = await BreedingSiteCRUD(self.auth, self.db).get(id=out.site_id)
out.site_name = site.site_name if site else None
return out
async def delete(self, ids: list[int]) -> None:
if not ids:
raise CustomException(msg="删除失败,删除对象不能为空")
objs = await BreedingPlotCRUD(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 BreedingPlotCRUD(self.auth, self.db).delete(ids=ids)
async def list_options(self) -> list[dict[str, Any]]:
"""供前端下拉选择使用:返回 [{value, label}]。"""
obj_list = await BreedingPlotCRUD(self.auth, self.db).get_list(
order_by=[{"id": "asc"}]
)
outs = [BreedingPlotOutSchema.model_validate(o) for o in obj_list]
await self._attach_site_name(outs)
return [{"value": o.id, "label": f"{o.site_name or ''}-{o.plot_code}"} for o in outs]
@staticmethod
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
mapping_dict = {
"id": "编号",
"site_name": "所属基地",
"plot_code": "地块编号/名称",
"row_orientation": "行向",
"row_count": "行数",
"col_count": "每行株数",
"grid_note": "株行距/网格说明",
"area": "地块面积(亩)",
"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) -> str:
header_dict = {
"所属基地": "site_name",
"地块编号/名称": "plot_code",
"行向": "row_orientation",
"行数": "row_count",
"每行株数": "col_count",
"株行距/网格说明": "grid_note",
"地块面积(亩)": "area",
}
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)}")
# 预加载基地名称→ID映射,供导入转换 site_name → site_id
sites = await BreedingSiteCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
site_name_to_id = {s.site_name: s.id for s in sites}
mapped_rows = []
for row in rows:
mapped_rows.append({en: row.get(ch) for ch, en in header_dict.items()})
required_fields = ["site_name", "plot_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 = BreedingPlotCRUD(self.auth, self.db)
resolver = DictLabelResolver(self.auth, self.db, ["row_orientation"])
for i, row in enumerate(mapped_rows, start=1):
try:
site_name = str(row["site_name"]).strip()
if site_name not in site_name_to_id:
error_msgs.append(f"第{i}行: 基地名称 {site_name} 不存在")
continue
fields = {
"site_id": site_name_to_id[site_name],
"plot_code": str(row["plot_code"]).strip(),
"row_orientation": await resolver.resolve("row_orientation", row.get("row_orientation")),
"row_count": _to_int(row.get("row_count")),
"col_count": _to_int(row.get("col_count")),
"grid_note": _none_if_blank(row.get("grid_note")),
"area": _to_float(row.get("area")),
}
create_data = BreedingPlotCreateSchema(**fields)
exist_obj = await crud.get(site_id=create_data.site_id, plot_code=create_data.plot_code)
if exist_obj:
if update_support:
await crud.update(id=exist_obj.id, data=BreedingPlotUpdateSchema(**fields))
success_count += 1
else:
error_msgs.append(f"第{i}行: 基地 {site_name} 下地块 {create_data.plot_code} 已存在")
else:
await crud.create(data=create_data)
success_count += 1
except Exception as e:
error_msgs.append(f"第{i}行: {e!s}")
continue
result = f"成功导入 {success_count} 条数据"
if error_msgs:
result += "\n错误信息:\n" + "\n".join(error_msgs)
return result
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,
)
def _to_int(v: Any) -> int | None:
if _is_blank(v):
return None
try:
return int(float(v))
except (TypeError, ValueError):
return None