init: 初始化 dpb 桃育种系统代码库
前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Path, Query, Security, status
|
||||
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, BatchSetAvailable, PageResultSchema, PaginationQueryParam
|
||||
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 PositionCreateSchema, PositionOutSchema, PositionQueryParam, PositionUpdateSchema
|
||||
from .service import PositionService
|
||||
|
||||
PositionRouter = APIRouter(route_class=OperationLogRoute, prefix="/position", tags=["岗位管理"])
|
||||
|
||||
|
||||
@PositionRouter.get("/list", summary="查询岗位", response_model=ResponseSchema[PageResultSchema[PositionOutSchema]])
|
||||
async def get_obj_list_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:query"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[PositionQueryParam, Query()],
|
||||
) -> JSONResponse:
|
||||
result_dict = await PositionService(auth, db).page(
|
||||
page_no=page.page_no,
|
||||
page_size=page.page_size,
|
||||
search=search,
|
||||
order_by=page.order_by,
|
||||
)
|
||||
return SuccessResponse(data=result_dict, msg="查询岗位列表成功")
|
||||
|
||||
|
||||
@PositionRouter.get("/detail/{id}", summary="查询岗位详情", response_model=ResponseSchema[PositionOutSchema])
|
||||
async def get_obj_detail_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:detail"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
id: Annotated[int, Path(description="岗位ID", ge=1)],
|
||||
) -> JSONResponse:
|
||||
result_dict = await PositionService(auth, db).detail(id=id)
|
||||
return SuccessResponse(data=result_dict, msg="获取岗位详情成功")
|
||||
|
||||
|
||||
@PositionRouter.post("/create", status_code=status.HTTP_201_CREATED, summary="创建岗位", response_model=ResponseSchema[PositionOutSchema])
|
||||
async def create_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:create"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
data: Annotated[PositionCreateSchema, Body(description="岗位创建参数")],
|
||||
) -> JSONResponse:
|
||||
result_dict = await PositionService(auth, db).create(data=data)
|
||||
return SuccessResponse(data=result_dict, msg="创建岗位成功")
|
||||
|
||||
|
||||
@PositionRouter.put("/update/{id}", summary="修改岗位", response_model=ResponseSchema[PositionOutSchema])
|
||||
async def update_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:update"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
id: Annotated[int, Path(description="岗位ID", ge=1)],
|
||||
data: Annotated[PositionUpdateSchema, Body(description="岗位修改参数")],
|
||||
) -> JSONResponse:
|
||||
result_dict = await PositionService(auth, db).update(id=id, data=data)
|
||||
return SuccessResponse(data=result_dict, msg="修改岗位成功")
|
||||
|
||||
|
||||
@PositionRouter.delete("/delete", summary="删除岗位", response_model=ResponseSchema[None])
|
||||
async def delete_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:delete"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
ids: Annotated[list[int], Body(description="ID列表")],
|
||||
) -> JSONResponse:
|
||||
await PositionService(auth, db).delete(ids=ids)
|
||||
return SuccessResponse(msg="删除岗位成功")
|
||||
|
||||
|
||||
@PositionRouter.patch("/status/batch", summary="批量修改岗位状态", response_model=ResponseSchema[None])
|
||||
async def batch_set_available_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:patch"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
data: Annotated[BatchSetAvailable, Body(description="状态设置")],
|
||||
) -> JSONResponse:
|
||||
await PositionService(auth, db).set_available(data=data)
|
||||
return SuccessResponse(msg="批量修改岗位状态成功")
|
||||
|
||||
|
||||
@PositionRouter.get("/options", summary="获取岗位下拉选项", response_model=ResponseSchema[list[dict[str, int | str]]])
|
||||
async def get_position_options_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:query"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
options = await PositionService(auth, db).get_options()
|
||||
return SuccessResponse(data=options, msg="获取岗位选项成功")
|
||||
|
||||
|
||||
@PositionRouter.post("/export", summary="导出岗位")
|
||||
async def export_obj_list_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:position:export"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
search: Annotated[PositionQueryParam, Body()],
|
||||
) -> StreamingResponse:
|
||||
position_query_result = await PositionService(auth, db).get_list(search=search)
|
||||
position_export_result = PositionService.export_list(position_list=[item.model_dump() for item in position_query_result])
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(position_export_result),
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": "attachment; filename=position.xlsx"},
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
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 PositionModel
|
||||
from .schema import PositionCreateSchema, PositionUpdateSchema
|
||||
|
||||
|
||||
class PositionCRUD(CRUDBase[PositionModel, PositionCreateSchema, PositionUpdateSchema]):
|
||||
"""岗位模块数据层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
super().__init__(model=PositionModel, auth=auth, db=db)
|
||||
|
||||
async def get_options(self) -> list[dict[str, Any]]:
|
||||
"""获取岗位下拉选项,返回 [{value, label}]"""
|
||||
items = await self.get_list(search={"status": 0})
|
||||
return [{"value": item.id, "label": item.name} for item in items]
|
||||
@@ -0,0 +1,25 @@
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.core.base_model import ModelMixin, UserMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.api.v1.module_system.user.model import UserModel
|
||||
|
||||
|
||||
class PositionModel(ModelMixin, UserMixin):
|
||||
"""岗位模型"""
|
||||
|
||||
__tablename__: str = "sys_position"
|
||||
__table_args__: dict[str, str] = {"comment": "岗位表"}
|
||||
|
||||
name: Mapped[str] = mapped_column(String(64), nullable=False, index=True, comment="岗位名称")
|
||||
code: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, comment="岗位编码")
|
||||
order: Mapped[int] = mapped_column(Integer, nullable=False, default=1, comment="显示排序")
|
||||
status: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="状态(0:启动 1:停用)")
|
||||
description: Mapped[str | None] = mapped_column(Text, default=None, nullable=True, comment="备注")
|
||||
|
||||
# 关联关系
|
||||
users: Mapped[list["UserModel"]] = relationship(secondary="sys_user_positions", back_populates="positions")
|
||||
@@ -0,0 +1,53 @@
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from app.core.base_schema import BaseQueryParam, BaseSchema, UserByQueryParam, UserBySchema
|
||||
|
||||
|
||||
class PositionCreateSchema(BaseModel):
|
||||
"""岗位创建模型"""
|
||||
|
||||
name: str = Field(..., min_length=1, max_length=64, description="岗位名称")
|
||||
code: str = Field(..., min_length=1, max_length=64, description="岗位编码")
|
||||
order: int = Field(default=1, ge=0, description="显示排序")
|
||||
status: int = Field(default=0, ge=0, le=1, description="状态(0:启动 1:停用)")
|
||||
description: str | None = Field(default=None, max_length=255, description="描述")
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _validate_name(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("岗位名称不能为空")
|
||||
return v
|
||||
|
||||
@field_validator("code")
|
||||
@classmethod
|
||||
def _validate_code(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("岗位编码不能为空")
|
||||
return v
|
||||
|
||||
@field_validator("status")
|
||||
@classmethod
|
||||
def _validate_status(cls, v: int) -> int:
|
||||
if v not in {0, 1}:
|
||||
raise ValueError("状态仅支持 0(正常) 或 1(禁用)")
|
||||
return v
|
||||
|
||||
|
||||
class PositionUpdateSchema(PositionCreateSchema):
|
||||
"""岗位更新模型"""
|
||||
|
||||
|
||||
class PositionOutSchema(PositionCreateSchema, BaseSchema, UserBySchema):
|
||||
"""岗位信息响应模型"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class PositionQueryParam(BaseQueryParam, UserByQueryParam):
|
||||
"""岗位管理查询参数"""
|
||||
|
||||
name: str | None = Field(None, description="岗位名称", json_schema_extra={"q": "like"})
|
||||
status: int | None = Field(None, ge=0, le=1, description="状态(0:启动 1:停用)", json_schema_extra={"q": "eq"})
|
||||
@@ -0,0 +1,111 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.base_schema import AuthSchema, BatchSetAvailable, PageResultSchema
|
||||
from app.core.exceptions import CustomException
|
||||
from app.utils.common_util import search_to_dict
|
||||
from app.utils.excel_util import ExcelUtil
|
||||
|
||||
from .crud import PositionCRUD
|
||||
from .schema import (
|
||||
PositionCreateSchema,
|
||||
PositionOutSchema,
|
||||
PositionQueryParam,
|
||||
PositionUpdateSchema,
|
||||
)
|
||||
|
||||
|
||||
class PositionService:
|
||||
"""岗位管理服务
|
||||
|
||||
提供岗位 CRUD、批量启/禁用、Excel 导出等业务能力。
|
||||
"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
self.auth = auth
|
||||
self.db = db
|
||||
|
||||
async def detail(self, id: int) -> PositionOutSchema:
|
||||
obj = await PositionCRUD(self.auth, self.db).get_or_404(id=id)
|
||||
return PositionOutSchema.model_validate(obj)
|
||||
|
||||
async def get_options(self) -> list[dict[str, Any]]:
|
||||
"""获取岗位下拉选项,委托给 PositionCRUD"""
|
||||
return await PositionCRUD(self.auth, self.db).get_options()
|
||||
|
||||
async def get_list(
|
||||
self,
|
||||
search: PositionQueryParam | None = None,
|
||||
order_by: list[dict] | None = None,
|
||||
) -> list[PositionOutSchema]:
|
||||
position_list = await PositionCRUD(self.auth, self.db).get_list(search=search_to_dict(search), order_by=order_by)
|
||||
return [PositionOutSchema.model_validate(position) for position in position_list]
|
||||
|
||||
async def page(
|
||||
self,
|
||||
page_no: int,
|
||||
page_size: int,
|
||||
search: PositionQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> PageResultSchema[PositionOutSchema]:
|
||||
offset = (page_no - 1) * page_size
|
||||
return await PositionCRUD(self.auth, self.db).page(
|
||||
offset=offset,
|
||||
limit=page_size,
|
||||
order_by=order_by or [{"id": "asc"}],
|
||||
search=search_to_dict(search),
|
||||
out_schema=PositionOutSchema,
|
||||
)
|
||||
|
||||
async def create(self, data: PositionCreateSchema) -> PositionOutSchema:
|
||||
position = await PositionCRUD(self.auth, self.db).get(name=data.name)
|
||||
if position:
|
||||
raise CustomException(msg="创建失败,该数据已存在")
|
||||
new_position = await PositionCRUD(self.auth, self.db).create(data=data)
|
||||
return await self.detail(id=new_position.id)
|
||||
|
||||
async def update(self, id: int, data: PositionUpdateSchema) -> PositionOutSchema:
|
||||
_ = await PositionCRUD(self.auth, self.db).get_or_404(id=id, msg="更新失败,该数据不存在")
|
||||
exist_position = await PositionCRUD(self.auth, self.db).get(name=data.name)
|
||||
if exist_position and exist_position.id != id:
|
||||
raise CustomException(msg="更新失败,名称已存在")
|
||||
await PositionCRUD(self.auth, self.db).update(id=id, data=data)
|
||||
return await self.detail(id=id)
|
||||
|
||||
async def delete(self, ids: list[int]) -> None:
|
||||
if not ids:
|
||||
raise CustomException(msg="删除失败,删除对象不能为空")
|
||||
positions = await PositionCRUD(self.auth, self.db).get_list(search={"id": ("in", ids)})
|
||||
position_map = {p.id: p for p in positions}
|
||||
for pid in ids:
|
||||
if pid not in position_map:
|
||||
raise CustomException(msg="删除失败,该数据不存在")
|
||||
await PositionCRUD(self.auth, self.db).delete(ids=ids)
|
||||
|
||||
async def set_available(self, data: BatchSetAvailable) -> None:
|
||||
positions = await PositionCRUD(self.auth, self.db).get_list(search={"id": ("in", data.ids)})
|
||||
position_map = {p.id: p for p in positions}
|
||||
for pid in data.ids:
|
||||
if pid not in position_map:
|
||||
raise CustomException(msg="该数据不存在")
|
||||
await PositionCRUD(self.auth, self.db).set(ids=data.ids, status=data.status)
|
||||
|
||||
@staticmethod
|
||||
def export_list(position_list: list[dict]) -> bytes:
|
||||
mapping_dict = {
|
||||
"id": "编号",
|
||||
"name": "岗位名称",
|
||||
"order": "显示顺序",
|
||||
"status": "状态",
|
||||
"description": "备注",
|
||||
"created_time": "创建时间",
|
||||
"updated_time": "更新时间",
|
||||
"created_id": "创建者ID",
|
||||
"updated_id": "更新者ID",
|
||||
}
|
||||
data = position_list.copy()
|
||||
for item in data:
|
||||
item["status"] = "启用" if item.get("status") == 0 else "停用"
|
||||
item["creator"] = item.get("created_by", {}).get("name", "未知") if isinstance(item.get("created_by"), dict) else "未知"
|
||||
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
|
||||
Reference in New Issue
Block a user