init: 初始化 dpb 桃育种系统代码库
前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.common.response import ResponseSchema, SuccessResponse
|
||||
from app.core.base_schema import AuthSchema, PageResultSchema, PaginationQueryParam
|
||||
from app.core.dependencies import AuthPermission, db_getter
|
||||
from app.core.router_class import OperationLogRoute
|
||||
|
||||
from .schema import AlertOutSchema, AlertQueryParam
|
||||
from .service import AlertService
|
||||
|
||||
AlertRouter = APIRouter(route_class=OperationLogRoute, prefix="/alert", tags=["育种预警中心"])
|
||||
|
||||
|
||||
@AlertRouter.get("/list", summary="分页查询超期预警", response_model=ResponseSchema[PageResultSchema[AlertOutSchema]])
|
||||
async def get_alert__list_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:alert:query"]))],
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[AlertQueryParam, Query()],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = AlertService(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="查询超期预警列表成功")
|
||||
|
||||
|
||||
@AlertRouter.get("/detail/{id}", summary="获取超期预警详情", response_model=ResponseSchema[AlertOutSchema])
|
||||
async def get_alert__detail_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:alert:query"]))],
|
||||
id: Annotated[int, Path(description="预警ID")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = AlertService(auth, db)
|
||||
result_dict = await service.detail(id=id)
|
||||
return SuccessResponse(data=result_dict, msg="获取超期预警详情成功")
|
||||
|
||||
|
||||
@AlertRouter.post("/resolve/{id}", summary="标记预警已处理", response_model=ResponseSchema[AlertOutSchema])
|
||||
async def resolve_alert_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:alert:update"]))],
|
||||
id: Annotated[int, Path(description="预警ID")],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = AlertService(auth, db)
|
||||
result_dict = await service.resolve(id=id)
|
||||
return SuccessResponse(data=result_dict, msg="标记预警已处理成功")
|
||||
|
||||
|
||||
@AlertRouter.get("/options", summary="超期预警筛选选项")
|
||||
async def get_alert__options_controller(
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_bre:alert:query"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
service = AlertService(auth, db)
|
||||
options = await service.options()
|
||||
return SuccessResponse(data=options, msg="获取超期预警选项成功")
|
||||
@@ -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 AlertModel
|
||||
|
||||
|
||||
class BreedingAlertCRUD(CRUDBase[AlertModel, Any, Any]):
|
||||
"""超期预警 CRUD —— 仅复用查询/分页(生成侧不走 CRUDBase,防自审计噪声)。"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
super().__init__(AlertModel, auth, db)
|
||||
|
||||
|
||||
alert_crud = BreedingAlertCRUD
|
||||
@@ -0,0 +1,150 @@
|
||||
"""超期预警每日扫描 job(批3):树多年未决策 / 花粉批次过期 / 种子批超期。
|
||||
|
||||
作为系统级定时任务注册于 app/core/ap_scheduler.py(init_scheduler),
|
||||
每日执行一次。生成 bre_alert 行时直接 db.add(不经 CRUDBase,防自审计递归);
|
||||
同实体已有 open 预警时跳过(去重),待处理人 resolve 后下一轮可再次告警。
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import async_db_session
|
||||
|
||||
from .model import AlertModel
|
||||
from app.api.v1.module_bre.tree.model import TreeModel
|
||||
from app.api.v1.module_bre.selection_result.model import SelectionResultModel
|
||||
from app.api.v1.module_bre.pollen.model import PollenModel
|
||||
from app.api.v1.module_bre.seed_lot.model import SeedLotModel
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 桃育种:杂种实生苗童期通常 3 年进入初选,定植后 3 年仍无选育决策即预警
|
||||
TREE_UNDECIDED_YEARS = 3
|
||||
# 种子批库存超过 harvest_year 的年限视为超期,需复检活力/更新
|
||||
SEED_LOT_MAX_YEARS = 3
|
||||
|
||||
|
||||
def _cutoff_iso(years: int, today: date) -> str:
|
||||
"""距今 years 年整天的下一日(含当日时间戳单株也命中)。"""
|
||||
boundary = datetime(today.year - years, today.month, today.day) + timedelta(days=1)
|
||||
return boundary.date().isoformat()
|
||||
|
||||
|
||||
async def _add_open_alert(
|
||||
db: AsyncSession,
|
||||
alert_type: str,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
message: str,
|
||||
) -> None:
|
||||
"""落一条 open 预警(调用方已确认无同实体 open 记录)。"""
|
||||
db.add(
|
||||
AlertModel(
|
||||
alert_type=alert_type,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
message=message,
|
||||
status="open",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def run_overdue_scan() -> bool:
|
||||
"""每日超期预警扫描:写 bre_alert(open 去重)。返回本轮新增条数。"""
|
||||
today = date.today()
|
||||
written = 0
|
||||
async with async_db_session() as db:
|
||||
# ① 树 N 年未决策:定植距今超 N 年且无任何 selection_result 记录
|
||||
open_tree = (
|
||||
select(AlertModel.id)
|
||||
.where(
|
||||
AlertModel.alert_type == "tree_undecided",
|
||||
AlertModel.entity_type == "bre_tree",
|
||||
AlertModel.entity_id == TreeModel.id,
|
||||
AlertModel.status == "open",
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
trees = (await db.execute(
|
||||
select(TreeModel).where(
|
||||
TreeModel.planted_date.isnot(None),
|
||||
TreeModel.planted_date < _cutoff_iso(TREE_UNDECIDED_YEARS, today),
|
||||
~select(SelectionResultModel.id)
|
||||
.where(SelectionResultModel.tree_id == TreeModel.id)
|
||||
.exists(),
|
||||
~open_tree,
|
||||
)
|
||||
)).scalars().all()
|
||||
for t in trees:
|
||||
await _add_open_alert(
|
||||
db,
|
||||
"tree_undecided",
|
||||
"bre_tree",
|
||||
t.id,
|
||||
f"单株 {t.tree_no} 定植于 {t.planted_date},已超 {TREE_UNDECIDED_YEARS} 年无选育决策(selection_result 无记录),请及时评定",
|
||||
)
|
||||
written += 1
|
||||
|
||||
# ② 花粉批次过期:expiry_date 早于今天
|
||||
open_pollen = (
|
||||
select(AlertModel.id)
|
||||
.where(
|
||||
AlertModel.alert_type == "pollen_expiry",
|
||||
AlertModel.entity_type == "bre_pollen",
|
||||
AlertModel.entity_id == PollenModel.id,
|
||||
AlertModel.status == "open",
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
pollens = (await db.execute(
|
||||
select(PollenModel).where(
|
||||
PollenModel.expiry_date.isnot(None),
|
||||
PollenModel.expiry_date < today,
|
||||
~open_pollen,
|
||||
)
|
||||
)).scalars().all()
|
||||
for p in pollens:
|
||||
await _add_open_alert(
|
||||
db,
|
||||
"pollen_expiry",
|
||||
"bre_pollen",
|
||||
p.id,
|
||||
f"花粉批次 {p.lot_code} 已于 {p.expiry_date} 失效(贮藏 {p.storage_method}),请复测活力或重新采集",
|
||||
)
|
||||
written += 1
|
||||
|
||||
# ③ 种子批超期:harvest_year 距今超 N 年(按收获年份)
|
||||
open_lot = (
|
||||
select(AlertModel.id)
|
||||
.where(
|
||||
AlertModel.alert_type == "seed_lot_expiry",
|
||||
AlertModel.entity_type == "bre_seed_lot",
|
||||
AlertModel.entity_id == SeedLotModel.id,
|
||||
AlertModel.status == "open",
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
lots = (await db.execute(
|
||||
select(SeedLotModel).where(
|
||||
SeedLotModel.harvest_year.isnot(None),
|
||||
SeedLotModel.harvest_year <= today.year - SEED_LOT_MAX_YEARS,
|
||||
~open_lot,
|
||||
)
|
||||
)).scalars().all()
|
||||
for lot in lots:
|
||||
age = today.year - (lot.harvest_year or today.year)
|
||||
await _add_open_alert(
|
||||
db,
|
||||
"seed_lot_expiry",
|
||||
"bre_seed_lot",
|
||||
lot.id,
|
||||
f"种子批 {lot.lot_code} 为 {lot.harvest_year} 年收获,已存放 {age} 年,建议复检发芽率/更新库存",
|
||||
)
|
||||
written += 1
|
||||
|
||||
await db.commit()
|
||||
logger.info(f"超期预警扫描完成:新增 {written} 条预警")
|
||||
return written
|
||||
@@ -0,0 +1,28 @@
|
||||
"""超期预警 数据模型(批3:每日扫描 job 落库,open→resolved 生命周期)"""
|
||||
|
||||
from sqlalchemy import Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.base_model import MappedBase, ModelMixin, UserMixin
|
||||
|
||||
|
||||
class AlertModel(ModelMixin, UserMixin, MappedBase):
|
||||
"""超期预警。
|
||||
|
||||
alert_type 三类:tree_undecided 单株多年未决策 / pollen_expiry 花粉批次过期 /
|
||||
seed_lot_expiry 种子批超期。生成侧为每日定时 job,直接 db.add(不经 CRUDBase,
|
||||
避免自审计噪声);created_id 记录处理人,job 自动生成时为空。
|
||||
"""
|
||||
|
||||
__tablename__ = "bre_alert"
|
||||
|
||||
alert_type: Mapped[str] = mapped_column(
|
||||
String(32), index=True, nullable=False,
|
||||
comment="预警类型(tree_undecided/pollen_expiry/seed_lot_expiry)",
|
||||
)
|
||||
entity_type: Mapped[str] = mapped_column(String(64), nullable=False, comment="实体类型(业务表名)")
|
||||
entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False, comment="实体ID")
|
||||
message: Mapped[str | None] = mapped_column(Text, nullable=True, comment="预警内容", default=None)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="open", comment="状态(open未处理/resolved已处理)"
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""超期预警 —— Pydantic 校验/序列化模型。"""
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.core.base_schema import CommonSchema
|
||||
|
||||
|
||||
class AlertOutSchema(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
uuid: str
|
||||
alert_type: str | None = None
|
||||
entity_type: str | None = None
|
||||
entity_id: int | None = None
|
||||
message: str | None = None
|
||||
status: str | None = None
|
||||
created_time: datetime | None = None
|
||||
updated_time: datetime | None = None
|
||||
created_by: CommonSchema | None = None
|
||||
updated_by: CommonSchema | None = None
|
||||
|
||||
|
||||
class AlertQueryParam(BaseModel):
|
||||
alert_type: str | None = Field(default=None, description="预警类型", json_schema_extra={"q": "eq"})
|
||||
entity_type: str | None = Field(default=None, description="实体类型(业务表名)", json_schema_extra={"q": "like"})
|
||||
entity_id: int | None = Field(default=None, description="实体ID", json_schema_extra={"q": "eq"})
|
||||
status: str | None = Field(default=None, description="状态(open/resolved)", json_schema_extra={"q": "eq"})
|
||||
created_time: list[datetime] | None = Field(default=None, description="创建时间范围(_time 后缀由 search_to_dict 合并为 between)")
|
||||
@@ -0,0 +1,72 @@
|
||||
"""超期预警 模块服务层 —— 只读查询 + 标记处理;写入由每日扫描 job 直接落库。"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.base_schema import AuthSchema, PageResultSchema
|
||||
from app.core.exceptions import CustomException
|
||||
|
||||
from .crud import BreedingAlertCRUD
|
||||
from .model import AlertModel
|
||||
from .schema import AlertOutSchema, AlertQueryParam
|
||||
|
||||
|
||||
class AlertService:
|
||||
"""预警中心 —— 查询 + 处理。生成侧在 job.py,直接 db.add(不经 CRUDBase,防自审计递归)。"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
self.auth = auth
|
||||
self.db = db
|
||||
|
||||
async def page(
|
||||
self,
|
||||
page_no: int,
|
||||
page_size: int,
|
||||
search: AlertQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> PageResultSchema[AlertOutSchema]:
|
||||
from app.utils.common_util import search_to_dict
|
||||
|
||||
return await BreedingAlertCRUD(self.auth, self.db).page(
|
||||
offset=(page_no - 1) * page_size,
|
||||
limit=page_size,
|
||||
order_by=order_by or [{"id": "desc"}],
|
||||
search=search_to_dict(search, {}),
|
||||
out_schema=AlertOutSchema,
|
||||
)
|
||||
|
||||
async def get_list(self, search: AlertQueryParam | None = None) -> list[AlertOutSchema]:
|
||||
from app.utils.common_util import search_to_dict
|
||||
|
||||
objs = await BreedingAlertCRUD(self.auth, self.db).get_list(
|
||||
search=search_to_dict(search, {}), order_by=[{"id": "desc"}]
|
||||
)
|
||||
return [AlertOutSchema.model_validate(o) for o in objs]
|
||||
|
||||
async def detail(self, id: int) -> AlertOutSchema:
|
||||
obj = await BreedingAlertCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该预警不存在")
|
||||
return AlertOutSchema.model_validate(obj)
|
||||
|
||||
async def resolve(self, id: int) -> AlertOutSchema:
|
||||
obj = await BreedingAlertCRUD(self.auth, self.db).get(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该预警不存在")
|
||||
obj.status = "resolved"
|
||||
obj.updated_id = self.auth.user.id if self.auth.user.id else None
|
||||
self.db.add(obj)
|
||||
await self.db.flush()
|
||||
return AlertOutSchema.model_validate(obj)
|
||||
|
||||
async def options(self) -> dict[str, Any]:
|
||||
"""前端筛选下拉:预警类型 / 实体类型 去重集合。"""
|
||||
alert_types = (await self.db.execute(
|
||||
select(AlertModel.alert_type).distinct()
|
||||
)).scalars().all()
|
||||
entity_types = (await self.db.execute(
|
||||
select(AlertModel.entity_type).distinct()
|
||||
)).scalars().all()
|
||||
return {"alert_types": sorted(alert_types), "entity_types": sorted(entity_types)}
|
||||
Reference in New Issue
Block a user