284 lines
11 KiB
Python
284 lines
11 KiB
Python
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 app.utils.dict_util import DictLabelResolver, dict_value_to_label
|
|
|
|
from .crud import BreedingPersonnelCRUD
|
|
from .schema import (
|
|
|
|
PersonnelCreateSchema,
|
|
PersonnelOutSchema,
|
|
PersonnelQueryParam,
|
|
PersonnelUpdateSchema,
|
|
)
|
|
|
|
|
|
from app.core.base_crud import assert_dict_values, assert_no_children, assert_parents_exist
|
|
from app.api.v1.module_bre.planting.model import PlantingModel
|
|
from app.api.v1.module_bre.pollination.model import PollinationModel
|
|
from app.api.v1.module_bre.seed_treatment.model import SeedTreatmentModel
|
|
from app.api.v1.module_bre.seedling.model import SeedlingModel
|
|
from app.api.v1.module_bre.tree_evaluation.model import TreeEvaluationModel
|
|
from app.api.v1.module_bre.tree.model import TreeModel
|
|
|
|
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 PersonnelService:
|
|
"""人员花名册 模块服务层"""
|
|
|
|
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
|
self.auth = auth
|
|
self.db = db
|
|
|
|
async def _attach_fk_labels(self, items: list[PersonnelOutSchema]) -> None:
|
|
if not items:
|
|
return
|
|
crud = BreedingPersonnelCRUD(self.auth, self.db)
|
|
|
|
async def detail(self, id: int) -> PersonnelOutSchema:
|
|
obj = await BreedingPersonnelCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="该人员花名册不存在")
|
|
out = PersonnelOutSchema.model_validate(obj)
|
|
await self._attach_fk_labels([out])
|
|
return out
|
|
|
|
async def get_list(
|
|
self,
|
|
search: PersonnelQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> list[PersonnelOutSchema]:
|
|
obj_list = await BreedingPersonnelCRUD(self.auth, self.db).get_list(
|
|
search=search_to_dict(search), order_by=order_by
|
|
)
|
|
outs = [PersonnelOutSchema.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: PersonnelQueryParam | None = None,
|
|
order_by: list[dict[str, str]] | None = None,
|
|
) -> PageResultSchema[PersonnelOutSchema]:
|
|
offset = (page_no - 1) * page_size
|
|
result = await BreedingPersonnelCRUD(self.auth, self.db).page(
|
|
offset=offset,
|
|
limit=page_size,
|
|
order_by=order_by or [{"id": "asc"}],
|
|
search=search_to_dict(search, {}),
|
|
out_schema=PersonnelOutSchema,
|
|
)
|
|
await self._attach_fk_labels(result.items)
|
|
return result
|
|
|
|
async def create(self, data: PersonnelCreateSchema) -> PersonnelOutSchema:
|
|
exist_obj = await BreedingPersonnelCRUD(self.auth, self.db).get(name=data.name)
|
|
if exist_obj:
|
|
raise CustomException(msg="创建失败,姓名已存在")
|
|
await assert_dict_values(
|
|
self.db,
|
|
[
|
|
('gender', data.gender, '性别'),
|
|
('personnel_role', data.role, '角色'),
|
|
],
|
|
)
|
|
|
|
obj = await BreedingPersonnelCRUD(self.auth, self.db).create(data=data)
|
|
out = PersonnelOutSchema.model_validate(obj)
|
|
return out
|
|
|
|
async def update(self, id: int, data: PersonnelUpdateSchema) -> PersonnelOutSchema:
|
|
obj = await BreedingPersonnelCRUD(self.auth, self.db).get(id=id)
|
|
if not obj:
|
|
raise CustomException(msg="更新失败,该人员花名册不存在")
|
|
if data.name is not None:
|
|
exist_obj = await BreedingPersonnelCRUD(self.auth, self.db).get(name=data.name)
|
|
if exist_obj and exist_obj.id != id:
|
|
raise CustomException(msg="更新失败,姓名重复")
|
|
await assert_dict_values(
|
|
self.db,
|
|
[
|
|
('gender', data.gender, '性别'),
|
|
('personnel_role', data.role, '角色'),
|
|
],
|
|
)
|
|
|
|
obj = await BreedingPersonnelCRUD(self.auth, self.db).update(id=id, data=data)
|
|
out = PersonnelOutSchema.model_validate(obj)
|
|
return out
|
|
|
|
async def delete(self, ids: list[int]) -> None:
|
|
if not ids:
|
|
raise CustomException(msg="删除失败,删除对象不能为空")
|
|
objs = await BreedingPersonnelCRUD(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, 'bre_personnel_id', '单株'),
|
|
(TreeEvaluationModel, 'bre_personnel_id', '单株评价'),
|
|
(SeedlingModel, 'bre_personnel_id', '实生苗'),
|
|
(PlantingModel, 'bre_personnel_id', '定植'),
|
|
(PollinationModel, 'bre_personnel_id', '授粉'),
|
|
(SeedTreatmentModel, 'bre_personnel_id', '种子处理'),
|
|
],
|
|
)
|
|
await BreedingPersonnelCRUD(self.auth, self.db).delete(ids=ids)
|
|
|
|
async def list_options(self) -> list[dict[str, Any]]:
|
|
"""供前端下拉选择使用:返回 [{value, label}]。"""
|
|
obj_list = await BreedingPersonnelCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
|
|
return [{"value": o.id, "label": o.name} for o in obj_list]
|
|
|
|
@staticmethod
|
|
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
|
|
mapping_dict = {
|
|
"name": "姓名",
|
|
"gender": "性别",
|
|
"role": "角色",
|
|
"phone": "联系电话",
|
|
"organization": "所属单位",
|
|
"join_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 "未知"
|
|
item["gender"] = dict_value_to_label("gender", item.get("gender"))
|
|
item["role"] = dict_value_to_label("personnel_role", item.get("role"))
|
|
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 = {
|
|
"姓名": "name",
|
|
"性别": "gender",
|
|
"角色": "role",
|
|
"联系电话": "phone",
|
|
"所属单位": "organization",
|
|
"入职日期": "join_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)}")
|
|
mapped_rows = []
|
|
for row in rows:
|
|
mapped_rows.append({en: row.get(ch) for ch, en in header_dict.items()})
|
|
required_fields = ["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 = BreedingPersonnelCRUD(self.auth, self.db)
|
|
resolver = DictLabelResolver(self.auth, self.db, ["gender", "personnel_role"])
|
|
for i, row in enumerate(mapped_rows, start=1):
|
|
try:
|
|
fields = {
|
|
"name": _none_if_blank(row.get("name")),
|
|
"gender": await resolver.resolve("gender", row.get("gender")),
|
|
"role": await resolver.resolve("personnel_role", row.get("role")),
|
|
"phone": _none_if_blank(row.get("phone")),
|
|
"organization": _none_if_blank(row.get("organization")),
|
|
"join_date": _none_if_blank(row.get("join_date")),
|
|
"remark": _none_if_blank(row.get("remark")),
|
|
}
|
|
unique_kwargs = {"name": fields["name"]}
|
|
create_data = PersonnelCreateSchema(**fields)
|
|
exist_obj = await crud.get(**unique_kwargs)
|
|
if exist_obj:
|
|
if update_support:
|
|
await crud.update(id=exist_obj.id, data=PersonnelUpdateSchema(**fields))
|
|
success_count += 1
|
|
else:
|
|
error_msgs.append(f"第{i}行: 姓名 {fields['name']} 已存在")
|
|
else:
|
|
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,
|
|
) |