260 lines
11 KiB
Python
260 lines
11 KiB
Python
from typing import Any
|
|
|
|
from fastapi import UploadFile
|
|
from sqlalchemy import func, select
|
|
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 BreedingEnvironmentConditionCRUD
|
|
from .model import EnvironmentConditionModel
|
|
from .schema import (
|
|
EnvironmentConditionCreateSchema,
|
|
EnvironmentConditionOutSchema,
|
|
EnvironmentConditionQueryParam,
|
|
EnvironmentConditionUpdateSchema,
|
|
)
|
|
from app.core.base_crud import assert_parents_exist
|
|
from app.api.v1.module_bre.site.crud import BreedingSiteCRUD
|
|
from app.api.v1.module_bre.site.model import BreedingSiteModel
|
|
|
|
|
|
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
|
|
|
|
|
|
def _to_decimal(v: Any):
|
|
if _is_blank(v):
|
|
return None
|
|
try:
|
|
return float(v)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
class EnvironmentConditionService:
|
|
"""环境因子 模块服务层"""
|
|
|
|
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
|
self.auth = auth
|
|
self.db = db
|
|
|
|
async def _attach_fk_labels(self, items: list[EnvironmentConditionOutSchema]) -> None:
|
|
if not items:
|
|
return
|
|
site_ids = {getattr(it, "site_id") for it in items if getattr(it, "site_id")}
|
|
if site_ids:
|
|
refs = await BreedingSiteCRUD(self.auth, self.db).get_list(search={"id": ("in", list(site_ids))})
|
|
ref_map = {r.id: getattr(r, "site_name") for r in refs}
|
|
for it in items:
|
|
it.site_name = ref_map.get(getattr(it, "site_id"))
|
|
|
|
async def _assert_site_year_unique(
|
|
self, site_id: int | None, year: int | None, exclude_id: int | None = None
|
|
) -> None:
|
|
"""(site_id, year) 唯一校验 —— 与 DB UNIQUE(uq_env_site_year) 对齐,含软删行。"""
|
|
if site_id is None or year is None:
|
|
return
|
|
conditions = [
|
|
EnvironmentConditionModel.site_id == site_id,
|
|
EnvironmentConditionModel.year == year,
|
|
]
|
|
if exclude_id is not None:
|
|
conditions.append(EnvironmentConditionModel.id != exclude_id)
|
|
result = await self.db.execute(select(func.count()).select_from(EnvironmentConditionModel).where(*conditions))
|
|
if result.scalar() or 0:
|
|
raise CustomException(
|
|
msg=f"该基地({site_id})在 {year} 年的环境记录已存在", status_code=409
|
|
)
|
|
|
|
async def detail(self, id: int) -> EnvironmentConditionOutSchema:
|
|
obj = await BreedingEnvironmentConditionCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="该环境记录不存在")
|
|
out = EnvironmentConditionOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def get_list(
|
|
self,
|
|
search: EnvironmentConditionQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> list[EnvironmentConditionOutSchema]:
|
|
obj_list = await BreedingEnvironmentConditionCRUD(self.auth, self.db).get_list(
|
|
search=search_to_dict(search), order_by=order_by
|
|
)
|
|
outs = [EnvironmentConditionOutSchema.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: EnvironmentConditionQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> PageResultSchema[EnvironmentConditionOutSchema]:
|
|
offset = (page_no - 1) * page_size
|
|
result = await BreedingEnvironmentConditionCRUD(self.auth, self.db).page(
|
|
offset=offset,
|
|
limit=page_size,
|
|
order_by=order_by or [{"id": "asc"}],
|
|
search=search_to_dict(search, {}),
|
|
out_schema=EnvironmentConditionOutSchema,
|
|
)
|
|
await self._attach_fk_labels(result.items)
|
|
return result
|
|
|
|
async def create(self, data: EnvironmentConditionCreateSchema) -> EnvironmentConditionOutSchema:
|
|
await assert_parents_exist(self.db, [(BreedingSiteModel, data.site_id, '试验基地')])
|
|
await self._assert_site_year_unique(data.site_id, data.year)
|
|
obj = await BreedingEnvironmentConditionCRUD(self.auth, self.db).create(data=data)
|
|
out = EnvironmentConditionOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def update(self, id: int, data: EnvironmentConditionUpdateSchema) -> EnvironmentConditionOutSchema:
|
|
obj = await BreedingEnvironmentConditionCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="更新失败,该环境记录不存在")
|
|
await assert_parents_exist(self.db, [(BreedingSiteModel, data.site_id, '试验基地')])
|
|
await self._assert_site_year_unique(data.site_id, data.year, exclude_id=id)
|
|
obj = await BreedingEnvironmentConditionCRUD(self.auth, self.db).update(id=id, data=data)
|
|
out = EnvironmentConditionOutSchema.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 BreedingEnvironmentConditionCRUD(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 BreedingEnvironmentConditionCRUD(self.auth, self.db).delete(ids=ids)
|
|
|
|
async def list_options(self) -> list[dict[str, Any]]:
|
|
"""供前端下拉选择使用:返回 [{value, label}]。"""
|
|
obj_list = await BreedingEnvironmentConditionCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
return [{"value": o.id, "label": f"基地{o.site_id}·{o.year}"} for o in obj_list]
|
|
|
|
@staticmethod
|
|
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
|
|
mapping_dict = {
|
|
"site_name": "试验基地",
|
|
"year": "年份",
|
|
"chilling_hours": "需冷量(小时)",
|
|
"growing_degree_days": "生长度日GDD",
|
|
"rainfall_mm": "降水量(mm)",
|
|
"temp_avg": "年均温度(℃)",
|
|
"soil_moisture": "土壤湿度",
|
|
"source": "数据来源",
|
|
"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 = {
|
|
"试验基地": "site_id",
|
|
"年份": "year",
|
|
"需冷量(小时)": "chilling_hours",
|
|
"生长度日GDD": "growing_degree_days",
|
|
"降水量(mm)": "rainfall_mm",
|
|
"年均温度(℃)": "temp_avg",
|
|
"土壤湿度": "soil_moisture",
|
|
"数据来源": "source",
|
|
"备注": "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)}")
|
|
site_refs = await BreedingSiteCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
site_map = {getattr(r, "site_name"): r.id for r in site_refs}
|
|
error_msgs: list[str] = []
|
|
success_count = 0
|
|
crud = BreedingEnvironmentConditionCRUD(self.auth, self.db)
|
|
for i, row in enumerate(rows, start=1):
|
|
try:
|
|
fields = {
|
|
"site_id": site_map.get(str(row.get("site_id")).strip())
|
|
if not _is_blank(row.get("site_id")) else None,
|
|
"year": _to_int(row.get("year")),
|
|
"chilling_hours": _to_decimal(row.get("chilling_hours")),
|
|
"growing_degree_days": _to_decimal(row.get("growing_degree_days")),
|
|
"rainfall_mm": _to_decimal(row.get("rainfall_mm")),
|
|
"temp_avg": _to_decimal(row.get("temp_avg")),
|
|
"soil_moisture": _to_decimal(row.get("soil_moisture")),
|
|
"source": _none_if_blank(row.get("source")),
|
|
"remark": _none_if_blank(row.get("remark")),
|
|
}
|
|
if fields["site_id"] is None or fields["year"] is None:
|
|
raise ValueError("试验基地/年份不能为空")
|
|
await self._assert_site_year_unique(fields["site_id"], fields["year"])
|
|
create_data = EnvironmentConditionCreateSchema(**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 = [
|
|
"试验基地",
|
|
"年份",
|
|
"需冷量(小时)",
|
|
"生长度日GDD",
|
|
"降水量(mm)",
|
|
"年均温度(℃)",
|
|
"土壤湿度",
|
|
"数据来源",
|
|
"备注",
|
|
]
|
|
selector_header_list = []
|
|
option_list = []
|
|
return ExcelUtil.get_excel_template(
|
|
header_list=header_list,
|
|
selector_header_list=selector_header_list,
|
|
option_list=option_list,
|
|
)
|