mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-21 20:55:14 +00:00
refactor: 完成系统架构升级与模块拆分
本次提交进行了大规模的系统重构: 1. 拆分租户相关模块到platform平台层,重构租户表名与关联关系 2. 迁移日志、工单、插件等模块到对应层级,统一代码结构 3. 重构批量操作接口路径,从/available/setting改为/status/batch 4. 新增批量删除基础模型,统一处理批量操作逻辑 5. 优化导入导出接口,修正路由方法与描述信息 6. 修复循环引用问题,重构依赖注入与类型导入 7. 更新初始化脚本与路由注册,新增平台管理路由 8. 重构岗位模型,新增岗位编码字段与校验 9. 完善部门删除逻辑,新增子部门删除限制 10. 更新初始化数据与配置文件,适配新架构
This commit is contained in:
@@ -0,0 +1,303 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Path
|
||||
from fastapi.responses import JSONResponse
|
||||
from redis.asyncio.client import Redis
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.common.response import ResponseSchema, SuccessResponse
|
||||
from app.core.base_params import PaginationQueryParam
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.dependencies import AuthPermission, redis_getter
|
||||
from app.core.logger import log
|
||||
from app.core.router_class import OperationLogRoute
|
||||
|
||||
from .schema import (
|
||||
TenantConfigItem,
|
||||
TenantConfigOutSchema,
|
||||
TenantCreateSchema,
|
||||
TenantMenuSetSchema,
|
||||
TenantOutSchema,
|
||||
TenantQueryParam,
|
||||
TenantQuotaOutSchema,
|
||||
TenantQuotaUpdateSchema,
|
||||
TenantUpdateSchema,
|
||||
TenantUserAddSchema,
|
||||
TenantUserOutSchema,
|
||||
)
|
||||
from .service import TenantService
|
||||
|
||||
TenantRouter = APIRouter(route_class=OperationLogRoute, prefix="/tenant", tags=["租户管理"])
|
||||
|
||||
|
||||
@TenantRouter.get(
|
||||
"/detail/{id}",
|
||||
summary="获取租户详情",
|
||||
description="获取租户详情",
|
||||
response_model=ResponseSchema[TenantOutSchema],
|
||||
)
|
||||
async def get_obj_detail_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:query"]))],
|
||||
) -> JSONResponse:
|
||||
result_dict = await TenantService.detail_service(id=id, auth=auth)
|
||||
log.info(f"获取租户详情成功 {id}")
|
||||
return SuccessResponse(data=result_dict, msg="获取租户详情成功")
|
||||
|
||||
|
||||
@TenantRouter.get(
|
||||
"/list",
|
||||
summary="查询租户列表",
|
||||
description="查询租户列表(分页)",
|
||||
response_model=ResponseSchema[dict],
|
||||
)
|
||||
async def get_obj_list_controller(
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[TenantQueryParam, Depends()],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:query"]))],
|
||||
) -> JSONResponse:
|
||||
order_by = [{"id": "asc"}]
|
||||
if page.order_by:
|
||||
order_by = page.order_by
|
||||
result_dict = await TenantService.page_service(
|
||||
auth=auth,
|
||||
page_no=page.page_no if page.page_no is not None else 1,
|
||||
page_size=page.page_size if page.page_size is not None else 10,
|
||||
search=search,
|
||||
order_by=order_by,
|
||||
)
|
||||
log.info("查询租户列表成功")
|
||||
return SuccessResponse(data=result_dict, msg="查询租户列表成功")
|
||||
|
||||
|
||||
@TenantRouter.post(
|
||||
"/create",
|
||||
summary="创建租户",
|
||||
description="创建租户",
|
||||
response_model=ResponseSchema[TenantOutSchema],
|
||||
)
|
||||
async def create_obj_controller(
|
||||
data: TenantCreateSchema,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:create"]))],
|
||||
) -> JSONResponse:
|
||||
result_dict = await TenantService.create_service(auth=auth, data=data)
|
||||
log.info(f"创建租户成功: {result_dict.get('name')}")
|
||||
return SuccessResponse(data=result_dict, msg="创建租户成功")
|
||||
|
||||
|
||||
@TenantRouter.put(
|
||||
"/update/{id}",
|
||||
summary="修改租户",
|
||||
description="修改租户",
|
||||
response_model=ResponseSchema[TenantOutSchema],
|
||||
)
|
||||
async def update_obj_controller(
|
||||
data: TenantUpdateSchema,
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:update"]))],
|
||||
) -> JSONResponse:
|
||||
result_dict = await TenantService.update_service(auth=auth, id=id, data=data)
|
||||
log.info(f"修改租户成功: {result_dict.get('name')}")
|
||||
return SuccessResponse(data=result_dict, msg="修改租户成功")
|
||||
|
||||
|
||||
@TenantRouter.delete(
|
||||
"/delete",
|
||||
summary="删除租户",
|
||||
description="删除租户",
|
||||
)
|
||||
async def delete_obj_controller(
|
||||
ids: Annotated[list[int], Body(..., description="ID列表")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:delete"]))],
|
||||
) -> JSONResponse:
|
||||
await TenantService.delete_service(auth=auth, ids=ids)
|
||||
log.info(f"删除租户成功: {ids}")
|
||||
return SuccessResponse(msg="删除租户成功")
|
||||
|
||||
|
||||
@TenantRouter.patch(
|
||||
"/status/batch",
|
||||
summary="批量修改租户状态",
|
||||
description="批量修改租户状态",
|
||||
)
|
||||
async def batch_set_available_obj_controller(
|
||||
data: BatchSetAvailable,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:patch"]))],
|
||||
) -> JSONResponse:
|
||||
await TenantService.set_available_service(auth=auth, data=data)
|
||||
log.info(f"批量修改租户状态成功: {data.ids}")
|
||||
return SuccessResponse(msg="批量修改租户状态成功")
|
||||
|
||||
|
||||
@TenantRouter.put(
|
||||
"/status/{id}",
|
||||
summary="启/禁用租户",
|
||||
description="修改单个租户的启用/禁用状态",
|
||||
)
|
||||
async def toggle_tenant_status_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:patch"]))],
|
||||
) -> JSONResponse:
|
||||
await TenantService.toggle_status_service(auth=auth, id=id)
|
||||
log.info(f"修改租户状态成功: {id}")
|
||||
return SuccessResponse(msg="修改租户状态成功")
|
||||
|
||||
|
||||
@TenantRouter.get(
|
||||
"/{id}/users",
|
||||
summary="获取租户用户列表",
|
||||
description="获取指定租户下的所有用户",
|
||||
response_model=ResponseSchema[list[TenantUserOutSchema]],
|
||||
)
|
||||
async def get_tenant_users_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:query"]))],
|
||||
) -> JSONResponse:
|
||||
result = await TenantService.get_tenant_users_service(auth=auth, tenant_id=id)
|
||||
log.info(f"获取租户用户列表成功: tenant_id={id}")
|
||||
return SuccessResponse(data=result, msg="获取租户用户列表成功")
|
||||
|
||||
|
||||
@TenantRouter.post(
|
||||
"/{id}/users",
|
||||
summary="向租户添加用户",
|
||||
description="将指定用户添加到租户中",
|
||||
response_model=ResponseSchema[None],
|
||||
)
|
||||
async def add_tenant_user_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
data: TenantUserAddSchema,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:create"]))],
|
||||
) -> JSONResponse:
|
||||
await TenantService.add_tenant_user_service(auth=auth, tenant_id=id, data=data)
|
||||
log.info(f"向租户添加用户成功: tenant_id={id}, user_id={data.user_id}")
|
||||
return SuccessResponse(msg="添加用户成功")
|
||||
|
||||
|
||||
@TenantRouter.delete(
|
||||
"/{id}/users/{uid}",
|
||||
summary="从租户移除用户",
|
||||
description="将指定用户从租户中移除",
|
||||
response_model=ResponseSchema[None],
|
||||
)
|
||||
async def remove_tenant_user_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
uid: Annotated[int, Path(description="用户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:delete"]))],
|
||||
) -> JSONResponse:
|
||||
await TenantService.remove_tenant_user_service(auth=auth, tenant_id=id, user_id=uid)
|
||||
log.info(f"从租户移除用户成功: tenant_id={id}, user_id={uid}")
|
||||
return SuccessResponse(msg="移除用户成功")
|
||||
|
||||
|
||||
# ============ P1: 配额管理 ============
|
||||
|
||||
|
||||
@TenantRouter.get(
|
||||
"/{id}/quota",
|
||||
summary="获取租户配额",
|
||||
description="获取指定租户的资源配额信息",
|
||||
response_model=ResponseSchema[TenantQuotaOutSchema],
|
||||
)
|
||||
async def get_tenant_quota_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:query"]))],
|
||||
) -> JSONResponse:
|
||||
result = await TenantService.get_quota_service(auth=auth, tenant_id=id)
|
||||
return SuccessResponse(data=result, msg="获取租户配额成功")
|
||||
|
||||
|
||||
@TenantRouter.put(
|
||||
"/{id}/quota",
|
||||
summary="修改租户配额",
|
||||
description="修改指定租户的资源配额(需超级管理员权限)",
|
||||
response_model=ResponseSchema[TenantQuotaOutSchema],
|
||||
)
|
||||
async def update_tenant_quota_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
data: TenantQuotaUpdateSchema,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:update"]))],
|
||||
) -> JSONResponse:
|
||||
result = await TenantService.update_quota_service(auth=auth, tenant_id=id, data=data)
|
||||
return SuccessResponse(data=result, msg="修改租户配额成功")
|
||||
|
||||
|
||||
# ============ P1: 租户配置 ============
|
||||
|
||||
|
||||
@TenantRouter.get(
|
||||
"/{id}/config",
|
||||
summary="获取租户配置",
|
||||
description="获取指定租户的个性化配置",
|
||||
response_model=ResponseSchema[list[TenantConfigOutSchema]],
|
||||
)
|
||||
async def get_tenant_config_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:query"]))],
|
||||
) -> JSONResponse:
|
||||
result = await TenantService.get_config_service(auth=auth, tenant_id=id)
|
||||
return SuccessResponse(data=result, msg="获取租户配置成功")
|
||||
|
||||
|
||||
@TenantRouter.get(
|
||||
"/{id}/config/info",
|
||||
summary="获取租户配置(公开-缓存)",
|
||||
description="从 Redis 缓存获取租户个性化配置,无需登录(供登录页等场景使用)",
|
||||
response_model=ResponseSchema[list[TenantConfigOutSchema]],
|
||||
)
|
||||
async def get_tenant_config_info_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
redis: Annotated[Redis, Depends(redis_getter)],
|
||||
) -> JSONResponse:
|
||||
result = await TenantService.get_config_cache_service(redis=redis, tenant_id=id)
|
||||
return SuccessResponse(data=result, msg="获取租户配置成功")
|
||||
|
||||
|
||||
@TenantRouter.put(
|
||||
"/{id}/config",
|
||||
summary="更新租户配置",
|
||||
description="批量更新租户的个性化配置",
|
||||
response_model=ResponseSchema[list[TenantConfigOutSchema]],
|
||||
)
|
||||
async def update_tenant_config_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
data: Annotated[list[TenantConfigItem], Body(..., description="配置项列表")],
|
||||
redis: Annotated[Redis, Depends(redis_getter)],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:update"]))],
|
||||
) -> JSONResponse:
|
||||
result = await TenantService.update_config_service(
|
||||
auth=auth, redis=redis, tenant_id=id, items=data
|
||||
)
|
||||
return SuccessResponse(data=result, msg="更新租户配置成功")
|
||||
|
||||
|
||||
# ============ P1: 租户菜单权限 ============
|
||||
|
||||
|
||||
@TenantRouter.get(
|
||||
"/{id}/menus",
|
||||
summary="获取租户菜单权限",
|
||||
description="获取指定租户有权限访问的菜单ID列表",
|
||||
response_model=ResponseSchema[list[int]],
|
||||
)
|
||||
async def get_tenant_menus_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:query"]))],
|
||||
) -> JSONResponse:
|
||||
result = await TenantService.get_menus_service(auth=auth, tenant_id=id)
|
||||
return SuccessResponse(data=result, msg="获取租户菜单成功")
|
||||
|
||||
|
||||
@TenantRouter.put(
|
||||
"/{id}/menus",
|
||||
summary="设置租户菜单权限",
|
||||
description="批量设置租户的菜单权限(先清空再写入,需超级管理员权限)",
|
||||
)
|
||||
async def set_tenant_menus_controller(
|
||||
id: Annotated[int, Path(description="租户ID")],
|
||||
data: TenantMenuSetSchema,
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:tenant:update"]))],
|
||||
) -> JSONResponse:
|
||||
await TenantService.set_menus_service(auth=auth, tenant_id=id, data=data)
|
||||
log.info(f"设置租户菜单权限成功: tenant_id={id}, count={len(data.menu_ids)}")
|
||||
return SuccessResponse(msg="设置租户菜单权限成功")
|
||||
@@ -0,0 +1,59 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.core.base_crud import CRUDBase
|
||||
|
||||
from .model import TenantModel
|
||||
from .schema import TenantCreateSchema, TenantOutSchema, TenantUpdateSchema
|
||||
|
||||
|
||||
class TenantCRUD(CRUDBase[TenantModel, TenantCreateSchema, TenantUpdateSchema]):
|
||||
"""租户数据层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema) -> None:
|
||||
self.auth = auth
|
||||
super().__init__(model=TenantModel, auth=auth)
|
||||
|
||||
async def get_by_id_crud(
|
||||
self, id: int, preload: list[str | Any] | None = None
|
||||
) -> TenantModel | None:
|
||||
return await self.get(id=id, preload=preload)
|
||||
|
||||
async def get_list_crud(
|
||||
self,
|
||||
search: dict | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
preload: list[str | Any] | None = None,
|
||||
) -> Sequence[TenantModel]:
|
||||
return await self.list(search=search, order_by=order_by, preload=preload)
|
||||
|
||||
async def page_crud(
|
||||
self,
|
||||
offset: int,
|
||||
limit: int,
|
||||
order_by: list[dict[str, str]] | None,
|
||||
search: dict | None = None,
|
||||
out_schema: type[TenantOutSchema] | None = None,
|
||||
preload: list[str | Any] | None = None,
|
||||
) -> dict:
|
||||
return await self.page(
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
order_by=order_by or [{"id": "asc"}],
|
||||
search=search or {},
|
||||
out_schema=out_schema or TenantOutSchema,
|
||||
preload=preload or [],
|
||||
)
|
||||
|
||||
async def create_crud(self, data: TenantCreateSchema) -> TenantModel | None:
|
||||
return await self.create(data=data)
|
||||
|
||||
async def update_crud(self, id: int, data: TenantUpdateSchema) -> TenantModel | None:
|
||||
return await self.update(id=id, data=data)
|
||||
|
||||
async def delete_crud(self, ids: list[int]) -> None:
|
||||
await self.delete(ids=ids)
|
||||
|
||||
async def set_available_crud(self, ids: list[int], status: str) -> None:
|
||||
await self.set(ids=ids, status=status)
|
||||
@@ -0,0 +1,189 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, SmallInteger, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, validates
|
||||
|
||||
from app.common.enums import PermissionFilterStrategy
|
||||
from app.core.base_model import MappedBase, ModelMixin
|
||||
|
||||
|
||||
class TenantModel(ModelMixin):
|
||||
"""
|
||||
租户模型 - 单一大表设计
|
||||
|
||||
- 系统租户(id=1):平台管理,由超级管理员维护
|
||||
- 普通租户(id>1):独立组织数据,通过业务表的 tenant_id 隔离
|
||||
- 配额字段直接集成到主表,简化结构便于管理
|
||||
"""
|
||||
|
||||
__tablename__: str = "platform_tenant"
|
||||
__table_args__: dict[str, str] = {"comment": "租户表"}
|
||||
__permission_strategy__: PermissionFilterStrategy = PermissionFilterStrategy.DATA_SCOPE
|
||||
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False, unique=True, comment="租户名称")
|
||||
code: Mapped[str] = mapped_column(String(100), nullable=False, unique=True, comment="租户编码")
|
||||
contact_name: Mapped[str | None] = mapped_column(
|
||||
String(64), nullable=True, default=None, comment="联系人姓名"
|
||||
)
|
||||
contact_phone: Mapped[str | None] = mapped_column(
|
||||
String(20), nullable=True, default=None, comment="联系人电话"
|
||||
)
|
||||
contact_email: Mapped[str | None] = mapped_column(
|
||||
String(128), nullable=True, default=None, comment="联系人邮箱"
|
||||
)
|
||||
address: Mapped[str | None] = mapped_column(
|
||||
String(255), nullable=True, default=None, comment="地址"
|
||||
)
|
||||
domain: Mapped[str | None] = mapped_column(
|
||||
String(255), nullable=True, default=None, comment="域名"
|
||||
)
|
||||
logo_url: Mapped[str | None] = mapped_column(
|
||||
String(500), nullable=True, default=None, comment="Logo URL"
|
||||
)
|
||||
sort: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="排序")
|
||||
package_id: Mapped[int | None] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("platform_package.id", ondelete="SET NULL", onupdate="CASCADE"),
|
||||
nullable=True,
|
||||
default=None,
|
||||
index=True,
|
||||
comment="关联套餐ID",
|
||||
)
|
||||
start_time: Mapped[datetime | None] = mapped_column(
|
||||
DateTime, nullable=True, default=None, comment="开始时间"
|
||||
)
|
||||
end_time: Mapped[datetime | None] = mapped_column(
|
||||
DateTime, nullable=True, default=None, comment="结束时间"
|
||||
)
|
||||
# 配额字段 - 直接集成到主表
|
||||
max_users: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=50, comment="最大用户数"
|
||||
)
|
||||
max_roles: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=20, comment="最大角色数"
|
||||
)
|
||||
max_storage_mb: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=500, comment="最大存储(MB)"
|
||||
)
|
||||
max_depts: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=50, comment="最大部门数"
|
||||
)
|
||||
|
||||
@validates("name")
|
||||
def validate_name(self, key: str, name: str) -> str:
|
||||
if not name or not name.strip():
|
||||
raise ValueError("名称不能为空")
|
||||
return name
|
||||
|
||||
@validates("code")
|
||||
def validate_code(self, key: str, code: str) -> str:
|
||||
if not code or not code.strip():
|
||||
raise ValueError("编码不能为空")
|
||||
if not code.isalnum():
|
||||
raise ValueError("编码只能包含字母和数字")
|
||||
return code
|
||||
|
||||
@validates("max_users", "max_roles", "max_storage_mb", "max_depts")
|
||||
def validate_quota(self, key: str, value: int) -> int:
|
||||
if value < 1:
|
||||
raise ValueError(f"{key} 不能小于 1")
|
||||
return value
|
||||
|
||||
|
||||
class TenantUserModel(MappedBase):
|
||||
"""
|
||||
用户-租户关联表
|
||||
|
||||
支持一个用户关联多个租户(如顾问在多个租户间切换)。
|
||||
每个用户有一个默认租户(is_default=1),用于登录后的默认上下文。
|
||||
"""
|
||||
|
||||
__tablename__: str = "platform_user_tenant"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("user_id", "tenant_id", name="uq_user_tenant"),
|
||||
{"comment": "用户租户关联表"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment="主键ID")
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("sys_user.id", ondelete="CASCADE", onupdate="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="用户ID",
|
||||
)
|
||||
tenant_id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("platform_tenant.id", ondelete="CASCADE", onupdate="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="租户ID",
|
||||
)
|
||||
role: Mapped[str] = mapped_column(
|
||||
String(20),
|
||||
nullable=False,
|
||||
default="member",
|
||||
comment="租户内角色(owner:拥有者 admin:管理员 member:成员)",
|
||||
)
|
||||
is_default: Mapped[int] = mapped_column(
|
||||
SmallInteger,
|
||||
nullable=False,
|
||||
default=0,
|
||||
comment="是否默认租户(0:否 1:是)",
|
||||
)
|
||||
create_time: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
default=datetime.now,
|
||||
nullable=False,
|
||||
comment="创建时间",
|
||||
)
|
||||
|
||||
|
||||
class TenantConfigModel(MappedBase):
|
||||
"""租户个性化配置模型 — 键值对存储"""
|
||||
|
||||
__tablename__: str = "platform_tenant_config"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("tenant_id", "config_key", name="uq_tenant_config_key"),
|
||||
{"comment": "租户配置表"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment="主键ID")
|
||||
tenant_id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("platform_tenant.id", ondelete="CASCADE", onupdate="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="租户ID",
|
||||
)
|
||||
config_key: Mapped[str] = mapped_column(String(100), nullable=False, comment="配置键")
|
||||
config_value: Mapped[str | None] = mapped_column(Text, nullable=True, comment="配置值")
|
||||
config_type: Mapped[str] = mapped_column(
|
||||
String(20), nullable=False, default="string", comment="配置类型(string/json/int/bool)"
|
||||
)
|
||||
|
||||
|
||||
class TenantMenuModel(MappedBase):
|
||||
"""租户菜单权限模型 — 控制租户可见的菜单项"""
|
||||
|
||||
__tablename__: str = "platform_tenant_menu"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("tenant_id", "menu_id", name="uq_tenant_menu"),
|
||||
{"comment": "租户菜单权限表"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment="主键ID")
|
||||
tenant_id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("platform_tenant.id", ondelete="CASCADE", onupdate="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="租户ID",
|
||||
)
|
||||
menu_id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("sys_menu.id", ondelete="CASCADE", onupdate="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="菜单ID",
|
||||
)
|
||||
@@ -0,0 +1,251 @@
|
||||
from fastapi import Query
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from app.common.enums import QueueEnum
|
||||
from app.core.base_schema import BaseSchema
|
||||
from app.core.validator import DateTimeStr, email_validator, mobile_validator
|
||||
|
||||
|
||||
class TenantCreateSchema(BaseModel):
|
||||
"""新增租户"""
|
||||
|
||||
name: str = Field(..., min_length=1, max_length=100, description="租户名称")
|
||||
code: str = Field(..., min_length=2, max_length=100, description="租户编码")
|
||||
status: str = Field(default="0", max_length=1, description="状态(0:正常 1:禁用)")
|
||||
description: str | None = Field(default=None, max_length=255, description="描述")
|
||||
start_time: DateTimeStr | None = Field(default=None, description="开始时间")
|
||||
end_time: DateTimeStr | None = Field(default=None, description="结束时间")
|
||||
contact_name: str | None = Field(default=None, max_length=64, description="联系人姓名")
|
||||
contact_phone: str | None = Field(default=None, max_length=20, description="联系人电话")
|
||||
contact_email: str | None = Field(default=None, max_length=128, description="联系人邮箱")
|
||||
address: str | None = Field(default=None, max_length=255, description="地址")
|
||||
domain: str | None = Field(default=None, max_length=255, description="域名")
|
||||
logo_url: str | None = Field(default=None, max_length=500, description="Logo URL")
|
||||
sort: int = Field(default=0, ge=0, description="排序")
|
||||
package_id: int | None = Field(default=None, gt=0, description="关联套餐ID")
|
||||
|
||||
@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("租户编码不能为空")
|
||||
if not v.isalnum():
|
||||
raise ValueError("租户编码仅允许字母和数字")
|
||||
return v
|
||||
|
||||
@field_validator("status")
|
||||
@classmethod
|
||||
def _validate_status(cls, v: str) -> str:
|
||||
if v not in {"0", "1"}:
|
||||
raise ValueError("状态仅支持 0(正常) 或 1(禁用)")
|
||||
return v
|
||||
|
||||
@field_validator("contact_phone")
|
||||
@classmethod
|
||||
def _validate_contact_phone(cls, v: str | None) -> str | None:
|
||||
return mobile_validator(v)
|
||||
|
||||
@field_validator("contact_email")
|
||||
@classmethod
|
||||
def _validate_contact_email(cls, v: str | None) -> str | None:
|
||||
if not v:
|
||||
return v
|
||||
return email_validator(v)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_time_range(self):
|
||||
if self.start_time and self.end_time and self.start_time > self.end_time:
|
||||
raise ValueError("结束时间不能早于开始时间")
|
||||
return self
|
||||
|
||||
|
||||
class TenantUpdateSchema(BaseModel):
|
||||
"""更新租户"""
|
||||
|
||||
name: str | None = Field(default=None, max_length=100, description="租户名称")
|
||||
code: str | None = Field(default=None, max_length=100, description="租户编码")
|
||||
status: str | None = Field(default=None, max_length=1, description="状态(0:正常 1:禁用)")
|
||||
description: str | None = Field(default=None, max_length=255, description="描述")
|
||||
start_time: DateTimeStr | None = Field(default=None, description="开始时间")
|
||||
end_time: DateTimeStr | None = Field(default=None, description="结束时间")
|
||||
contact_name: str | None = Field(default=None, max_length=64, description="联系人姓名")
|
||||
contact_phone: str | None = Field(default=None, max_length=20, description="联系人电话")
|
||||
contact_email: str | None = Field(default=None, max_length=128, description="联系人邮箱")
|
||||
address: str | None = Field(default=None, max_length=255, description="地址")
|
||||
domain: str | None = Field(default=None, max_length=255, description="域名")
|
||||
logo_url: str | None = Field(default=None, max_length=500, description="Logo URL")
|
||||
sort: int | None = Field(default=None, ge=0, description="排序")
|
||||
package_id: int | None = Field(default=None, gt=0, description="关联套餐ID")
|
||||
|
||||
@field_validator("code")
|
||||
@classmethod
|
||||
def _validate_code(cls, v: str | None) -> str | None:
|
||||
if v is None:
|
||||
return v
|
||||
v = v.strip()
|
||||
if not v.isalnum():
|
||||
raise ValueError("租户编码仅允许字母和数字")
|
||||
return v
|
||||
|
||||
@field_validator("status")
|
||||
@classmethod
|
||||
def _validate_status(cls, v: str | None) -> str | None:
|
||||
if v is None:
|
||||
return v
|
||||
if v not in {"0", "1"}:
|
||||
raise ValueError("状态仅支持 0(正常) 或 1(禁用)")
|
||||
return v
|
||||
|
||||
@field_validator("contact_phone")
|
||||
@classmethod
|
||||
def _validate_contact_phone(cls, v: str | None) -> str | None:
|
||||
return mobile_validator(v)
|
||||
|
||||
@field_validator("contact_email")
|
||||
@classmethod
|
||||
def _validate_contact_email(cls, v: str | None) -> str | None:
|
||||
if not v:
|
||||
return v
|
||||
return email_validator(v)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_time_range(self):
|
||||
if self.start_time and self.end_time and self.start_time > self.end_time:
|
||||
raise ValueError("结束时间不能早于开始时间")
|
||||
return self
|
||||
|
||||
|
||||
class TenantOutSchema(TenantCreateSchema, BaseSchema):
|
||||
"""租户响应"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class TenantQueryParam:
|
||||
"""租户查询参数"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str | None = Query(None, description="租户名称"),
|
||||
code: str | None = Query(None, description="租户编码"),
|
||||
status: str | None = Query(None, description="状态"),
|
||||
created_time: list[DateTimeStr] | None = Query(
|
||||
None,
|
||||
description="创建时间范围",
|
||||
examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"],
|
||||
),
|
||||
) -> None:
|
||||
if name:
|
||||
self.name = (QueueEnum.like.value, name)
|
||||
if code:
|
||||
self.code = (QueueEnum.like.value, code)
|
||||
if status:
|
||||
self.status = (QueueEnum.eq.value, status)
|
||||
if created_time and len(created_time) == 2:
|
||||
self.created_time = (QueueEnum.between.value, (created_time[0], created_time[1]))
|
||||
|
||||
|
||||
class TenantUserAddSchema(BaseModel):
|
||||
"""向租户添加用户"""
|
||||
|
||||
user_id: int = Field(..., gt=0, description="用户ID")
|
||||
role: str = Field(default="member", max_length=20, description="租户内角色(owner/admin/member)")
|
||||
is_default: int = Field(default=0, ge=0, le=1, description="是否默认租户(0:否 1:是)")
|
||||
|
||||
@field_validator("role")
|
||||
@classmethod
|
||||
def _validate_role(cls, v: str) -> str:
|
||||
if v not in {"owner", "admin", "member"}:
|
||||
raise ValueError("租户角色仅支持 owner(拥有者)、admin(管理员)、member(成员)")
|
||||
return v
|
||||
|
||||
@field_validator("is_default")
|
||||
@classmethod
|
||||
def _validate_is_default(cls, v: int) -> int:
|
||||
if v not in {0, 1}:
|
||||
raise ValueError("是否默认仅支持 0(否) 或 1(是)")
|
||||
return v
|
||||
|
||||
|
||||
class TenantUserOutSchema(BaseModel):
|
||||
"""租户用户响应"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int = Field(..., description="关联ID")
|
||||
user_id: int = Field(..., description="用户ID")
|
||||
tenant_id: int = Field(..., description="租户ID")
|
||||
role: str = Field(..., description="租户内角色")
|
||||
is_default: int = Field(..., description="是否默认租户")
|
||||
create_time: DateTimeStr | None = Field(default=None, description="创建时间")
|
||||
username: str = Field(default="", description="用户名")
|
||||
name: str = Field(default="", description="用户姓名")
|
||||
|
||||
|
||||
# ============ P1: 配额管理 ============
|
||||
|
||||
|
||||
class TenantQuotaOutSchema(BaseModel):
|
||||
"""租户配额响应"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
tenant_id: int
|
||||
max_users: int
|
||||
max_roles: int
|
||||
max_storage_mb: int
|
||||
max_depts: int
|
||||
|
||||
|
||||
class TenantQuotaUpdateSchema(BaseModel):
|
||||
"""租户配额更新"""
|
||||
|
||||
max_users: int | None = Field(default=None, ge=0, description="最大用户数")
|
||||
max_roles: int | None = Field(default=None, ge=0, description="最大角色数")
|
||||
max_storage_mb: int | None = Field(default=None, ge=0, description="最大存储(MB)")
|
||||
max_depts: int | None = Field(default=None, ge=0, description="最大部门数")
|
||||
|
||||
|
||||
# ============ P1: 租户配置 ============
|
||||
|
||||
|
||||
class TenantConfigItem(BaseModel):
|
||||
"""单个配置项"""
|
||||
|
||||
config_key: str = Field(..., min_length=1, max_length=100, description="配置键")
|
||||
config_value: str = Field(..., max_length=65535, description="配置值")
|
||||
config_type: str = Field(default="string", max_length=20, description="配置类型(string/json/int/bool)")
|
||||
|
||||
@field_validator("config_type")
|
||||
@classmethod
|
||||
def _validate_config_type(cls, v: str) -> str:
|
||||
if v not in {"string", "json", "int", "bool"}:
|
||||
raise ValueError("配置类型仅支持 string、json、int、bool")
|
||||
return v
|
||||
|
||||
|
||||
class TenantConfigOutSchema(TenantConfigItem):
|
||||
"""租户配置响应"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
tenant_id: int
|
||||
|
||||
|
||||
# ============ P1: 租户菜单 ============
|
||||
|
||||
|
||||
class TenantMenuSetSchema(BaseModel):
|
||||
"""批量设置租户菜单权限"""
|
||||
|
||||
menu_ids: list[int] = Field(..., description="菜单ID列表")
|
||||
@@ -0,0 +1,676 @@
|
||||
import json
|
||||
import random
|
||||
import string
|
||||
|
||||
import sqlalchemy as sa
|
||||
from redis.asyncio.client import Redis
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.api.v1.module_system.dept.crud import DeptCRUD
|
||||
from app.api.v1.module_system.position.crud import PositionCRUD
|
||||
from app.api.v1.module_system.role.crud import RoleCRUD
|
||||
from app.api.v1.module_system.user.crud import UserCRUD
|
||||
from app.common.enums import RedisInitKeyConfig
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.exceptions import CustomException
|
||||
from app.core.logger import log
|
||||
from app.core.redis_crud import RedisCURD
|
||||
from app.utils.hash_bcrpy_util import PwdUtil
|
||||
|
||||
from .crud import TenantCRUD
|
||||
from .model import (
|
||||
TenantConfigModel,
|
||||
TenantMenuModel,
|
||||
TenantModel,
|
||||
TenantUserModel,
|
||||
)
|
||||
from .schema import (
|
||||
TenantConfigItem,
|
||||
TenantConfigOutSchema,
|
||||
TenantCreateSchema,
|
||||
TenantMenuSetSchema,
|
||||
TenantOutSchema,
|
||||
TenantQueryParam,
|
||||
TenantQuotaOutSchema,
|
||||
TenantQuotaUpdateSchema,
|
||||
TenantUpdateSchema,
|
||||
TenantUserAddSchema,
|
||||
TenantUserOutSchema,
|
||||
)
|
||||
|
||||
|
||||
class TenantService:
|
||||
"""租户管理模块服务层"""
|
||||
|
||||
@classmethod
|
||||
async def detail_service(cls, auth: AuthSchema, id: int) -> dict:
|
||||
obj = await TenantCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="租户不存在")
|
||||
result = TenantOutSchema.model_validate(obj).model_dump()
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
async def page_service(
|
||||
cls,
|
||||
auth: AuthSchema,
|
||||
page_no: int,
|
||||
page_size: int,
|
||||
search: TenantQueryParam | None = None,
|
||||
order_by: list[dict[str, str]] | None = None,
|
||||
) -> dict:
|
||||
return await TenantCRUD(auth).page_crud(
|
||||
offset=(page_no - 1) * page_size,
|
||||
limit=page_size,
|
||||
order_by=order_by or [{"id": "asc"}],
|
||||
search=search.__dict__ if search else {},
|
||||
out_schema=TenantOutSchema,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def create_service(cls, auth: AuthSchema, data: TenantCreateSchema) -> dict:
|
||||
if await TenantCRUD(auth).get(name=data.name):
|
||||
raise CustomException(msg="创建失败,名称已存在")
|
||||
if await TenantCRUD(auth).get(code=data.code):
|
||||
raise CustomException(msg="创建失败,编码已存在")
|
||||
|
||||
tenant_obj = await TenantCRUD(auth).create_crud(data=data)
|
||||
if not tenant_obj:
|
||||
raise CustomException(msg="创建租户失败")
|
||||
|
||||
# 创建租户初始管理员
|
||||
# 1. 生成初始管理员用户名
|
||||
# 2. 检查用户名是否已存在
|
||||
# 3. 创建初始管理员用户
|
||||
username = f"{tenant_obj.code}_admin"
|
||||
if await UserCRUD(auth).get_by_username_crud(username=username):
|
||||
raise CustomException(msg=f"初始管理员用户名已存在: {username},请更换租户编码后重试")
|
||||
|
||||
password_length = 12
|
||||
characters = string.ascii_letters + string.digits + "!@#$%^&*"
|
||||
password = "".join(random.choice(characters) for _ in range(password_length))
|
||||
admin_data = {
|
||||
"username": username,
|
||||
"password": PwdUtil.set_password_hash(password=password),
|
||||
"name": f"{tenant_obj.name}管理员",
|
||||
"tenant_id": tenant_obj.id,
|
||||
"status": "0",
|
||||
"is_superuser": False,
|
||||
}
|
||||
try:
|
||||
user_obj = await UserCRUD(auth).create(data=admin_data)
|
||||
if not user_obj:
|
||||
raise CustomException(msg="创建租户初始管理员失败")
|
||||
except CustomException:
|
||||
raise
|
||||
except Exception as e:
|
||||
log.error(f"为租户[{tenant_obj.name}]创建初始管理员失败: {e!s}")
|
||||
raise CustomException(msg="创建租户初始管理员失败")
|
||||
|
||||
log.info(
|
||||
f"为租户[{tenant_obj.name}]创建初始管理员成功,用户名: {username},临时密码: {password}"
|
||||
)
|
||||
|
||||
await auth.db.refresh(tenant_obj)
|
||||
result = TenantOutSchema.model_validate(tenant_obj).model_dump()
|
||||
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
async def update_service(cls, auth: AuthSchema, id: int, data: TenantUpdateSchema) -> dict:
|
||||
obj = await TenantCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="租户不存在")
|
||||
|
||||
old_package_id = obj.package_id
|
||||
|
||||
if id == 1:
|
||||
if data.code is not None and data.code != obj.code:
|
||||
raise CustomException(msg="系统租户编码不可修改")
|
||||
if data.status is not None and data.status == "1":
|
||||
raise CustomException(msg="系统租户不允许禁用")
|
||||
|
||||
# 套餐变更:仅超管可操作,防止租户管理员自行升级/降级套餐
|
||||
if data.package_id is not None and data.package_id != old_package_id:
|
||||
if not auth.user or not auth.user.is_superuser:
|
||||
raise CustomException(msg="仅平台管理员可变更租户套餐")
|
||||
|
||||
if data.name is not None:
|
||||
exist = await TenantCRUD(auth).get(name=data.name)
|
||||
if exist and exist.id != id:
|
||||
raise CustomException(msg="更新失败,名称重复")
|
||||
if data.code is not None:
|
||||
exist = await TenantCRUD(auth).get(code=data.code)
|
||||
if exist and exist.id != id:
|
||||
raise CustomException(msg="更新失败,编码重复")
|
||||
|
||||
updated = await TenantCRUD(auth).update_crud(id=id, data=data)
|
||||
if not updated:
|
||||
raise CustomException(msg="更新失败")
|
||||
|
||||
# 套餐变更后:清理角色中不再可用的菜单关联,防止用户看到空白菜单
|
||||
if data.package_id is not None and data.package_id != old_package_id:
|
||||
from sqlalchemy import delete as sa_delete
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.v1.module_platform.package.service import PackageService
|
||||
from app.api.v1.module_system.role.model import RoleMenusModel, RoleModel
|
||||
|
||||
available_ids = await PackageService.get_tenant_available_menu_ids(auth, id)
|
||||
if available_ids:
|
||||
role_ids_stmt = select(RoleModel.id).where(RoleModel.tenant_id == id)
|
||||
result = await auth.db.execute(role_ids_stmt)
|
||||
tenant_role_ids = [row[0] for row in result.all()]
|
||||
if tenant_role_ids:
|
||||
await auth.db.execute(
|
||||
sa_delete(RoleMenusModel).where(
|
||||
RoleMenusModel.role_id.in_(tenant_role_ids),
|
||||
RoleMenusModel.menu_id.notin_(available_ids),
|
||||
)
|
||||
)
|
||||
await auth.db.flush()
|
||||
log.info(
|
||||
f"租户[{id}]套餐变更:已清理角色中不再可用的菜单关联, "
|
||||
f"available_menus={len(available_ids)}, roles_affected={len(tenant_role_ids)}"
|
||||
)
|
||||
|
||||
result = TenantOutSchema.model_validate(updated).model_dump()
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
async def delete_service(cls, auth: AuthSchema, ids: list[int]) -> None:
|
||||
if not ids:
|
||||
raise CustomException(msg="删除失败,删除对象不能为空")
|
||||
if 1 in ids:
|
||||
raise CustomException(msg="系统租户不允许删除")
|
||||
for id in ids:
|
||||
obj = await TenantCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
continue
|
||||
for tid in ids:
|
||||
reasons: list[str] = []
|
||||
if await UserCRUD(auth).list(search={"tenant_id": tid}):
|
||||
reasons.append("用户")
|
||||
if await DeptCRUD(auth).list(search={"tenant_id": tid}):
|
||||
reasons.append("部门")
|
||||
if await RoleCRUD(auth).list(search={"tenant_id": tid}):
|
||||
reasons.append("角色")
|
||||
if await PositionCRUD(auth).list(search={"tenant_id": tid}):
|
||||
reasons.append("岗位")
|
||||
if reasons:
|
||||
raise CustomException(
|
||||
msg=f"租户 ID={tid} 下仍有关联数据({','.join(reasons)}),请先清理后再删除"
|
||||
)
|
||||
await TenantCRUD(auth).delete_crud(ids=ids)
|
||||
|
||||
@classmethod
|
||||
async def set_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
||||
if data.status == "1" and 1 in data.ids:
|
||||
raise CustomException(msg="系统租户不允许禁用")
|
||||
await TenantCRUD(auth).set_available_crud(ids=data.ids, status=data.status)
|
||||
|
||||
@classmethod
|
||||
async def toggle_status_service(cls, auth: AuthSchema, id: int) -> None:
|
||||
"""切换单个租户的启用/禁用状态"""
|
||||
obj = await TenantCRUD(auth).get_by_id_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="租户不存在")
|
||||
if id == 1:
|
||||
raise CustomException(msg="系统租户不允许禁用")
|
||||
new_status = "0" if obj.status == "1" else "1"
|
||||
await TenantCRUD(auth).set_available_crud(ids=[id], status=new_status)
|
||||
|
||||
@classmethod
|
||||
async def get_tenant_users_service(cls, auth: AuthSchema, tenant_id: int) -> list[dict]:
|
||||
"""获取租户下的用户列表"""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.v1.module_system.user.model import UserModel
|
||||
|
||||
stmt = (
|
||||
select(TenantUserModel, UserModel)
|
||||
.join(UserModel, UserModel.id == TenantUserModel.user_id)
|
||||
.where(TenantUserModel.tenant_id == tenant_id)
|
||||
.order_by(TenantUserModel.is_default.desc(), TenantUserModel.id)
|
||||
)
|
||||
result = await auth.db.execute(stmt)
|
||||
rows = result.all()
|
||||
|
||||
users = []
|
||||
for tu, u in rows:
|
||||
users.append(
|
||||
TenantUserOutSchema(
|
||||
id=tu.id,
|
||||
user_id=tu.user_id,
|
||||
tenant_id=tu.tenant_id,
|
||||
role=tu.role,
|
||||
is_default=tu.is_default,
|
||||
create_time=tu.create_time,
|
||||
username=u.username,
|
||||
name=u.name,
|
||||
).model_dump()
|
||||
)
|
||||
return users
|
||||
|
||||
@classmethod
|
||||
async def add_tenant_user_service(
|
||||
cls, auth: AuthSchema, tenant_id: int, data: TenantUserAddSchema
|
||||
) -> None:
|
||||
"""向租户添加用户"""
|
||||
# 验证租户存在
|
||||
tenant = await TenantCRUD(auth).get_by_id_crud(id=tenant_id)
|
||||
if not tenant:
|
||||
raise CustomException(msg="租户不存在")
|
||||
|
||||
# 验证用户存在
|
||||
from app.api.v1.module_system.user.crud import UserCRUD
|
||||
|
||||
user = await UserCRUD(auth).get_by_id_crud(id=data.user_id)
|
||||
if not user:
|
||||
raise CustomException(msg="用户不存在")
|
||||
|
||||
# 检查是否已关联
|
||||
from sqlalchemy import select
|
||||
|
||||
exist_stmt = (
|
||||
select(TenantUserModel)
|
||||
.where(
|
||||
TenantUserModel.user_id == data.user_id,
|
||||
TenantUserModel.tenant_id == tenant_id,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
result = await auth.db.execute(exist_stmt)
|
||||
if result.scalar_one_or_none():
|
||||
raise CustomException(msg="该用户已关联此租户")
|
||||
|
||||
# 如果设为默认租户,先取消其他默认
|
||||
if data.is_default == 1:
|
||||
await auth.db.execute(
|
||||
sa
|
||||
.update(TenantUserModel)
|
||||
.where(TenantUserModel.user_id == data.user_id)
|
||||
.values(is_default=0)
|
||||
)
|
||||
elif data.is_default == 0:
|
||||
# 检查是否是该用户的第一个租户关联
|
||||
count_result = await auth.db.execute(
|
||||
select(sa.func.count())
|
||||
.select_from(TenantUserModel)
|
||||
.where(TenantUserModel.user_id == data.user_id)
|
||||
)
|
||||
count = count_result.scalar()
|
||||
if count == 0:
|
||||
# 第一个租户自动设为默认
|
||||
data.is_default = 1
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
tu = TenantUserModel(
|
||||
user_id=data.user_id,
|
||||
tenant_id=tenant_id,
|
||||
role=data.role,
|
||||
is_default=data.is_default,
|
||||
create_time=datetime.now(),
|
||||
)
|
||||
auth.db.add(tu)
|
||||
await auth.db.flush()
|
||||
|
||||
log.info(f"向租户[{tenant.name}]添加用户[{user.username}]成功, role={data.role}")
|
||||
|
||||
@classmethod
|
||||
async def remove_tenant_user_service(
|
||||
cls, auth: AuthSchema, tenant_id: int, user_id: int
|
||||
) -> None:
|
||||
"""从租户移除用户"""
|
||||
from sqlalchemy import select
|
||||
|
||||
# 查找关联记录
|
||||
exist_stmt = (
|
||||
select(TenantUserModel)
|
||||
.where(
|
||||
TenantUserModel.user_id == user_id,
|
||||
TenantUserModel.tenant_id == tenant_id,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
result = await auth.db.execute(exist_stmt)
|
||||
tu = result.scalar_one_or_none()
|
||||
if not tu:
|
||||
raise CustomException(msg="该用户未关联此租户")
|
||||
|
||||
# 不允许移除租户最后一个 owner
|
||||
if tu.role == "owner":
|
||||
count_result = await auth.db.execute(
|
||||
select(sa.func.count())
|
||||
.select_from(TenantUserModel)
|
||||
.where(
|
||||
TenantUserModel.tenant_id == tenant_id,
|
||||
TenantUserModel.role == "owner",
|
||||
)
|
||||
)
|
||||
owner_count = count_result.scalar()
|
||||
if owner_count <= 1:
|
||||
raise CustomException(msg="租户至少需要保留一个拥有者(owner)")
|
||||
|
||||
await auth.db.delete(tu)
|
||||
await auth.db.flush()
|
||||
|
||||
log.info(f"从租户[{tenant_id}]移除用户[{user_id}]成功")
|
||||
|
||||
# ============ P1: 配额管理 ============
|
||||
|
||||
@classmethod
|
||||
async def get_quota_service(cls, auth: AuthSchema, tenant_id: int) -> dict:
|
||||
"""获取租户配额(从租户主表读取)"""
|
||||
tenant = await TenantCRUD(auth).get_by_id_crud(id=tenant_id)
|
||||
if not tenant:
|
||||
raise CustomException(msg="租户不存在")
|
||||
return TenantQuotaOutSchema(
|
||||
tenant_id=tenant.id,
|
||||
max_users=tenant.max_users,
|
||||
max_roles=tenant.max_roles,
|
||||
max_storage_mb=tenant.max_storage_mb,
|
||||
max_depts=tenant.max_depts,
|
||||
).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def update_quota_service(
|
||||
cls, auth: AuthSchema, tenant_id: int, data: TenantQuotaUpdateSchema
|
||||
) -> dict:
|
||||
"""更新租户配额(直接更新租户主表)"""
|
||||
tenant = await TenantCRUD(auth).get_by_id_crud(id=tenant_id)
|
||||
if not tenant:
|
||||
raise CustomException(msg="租户不存在")
|
||||
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
for k, v in update_data.items():
|
||||
setattr(tenant, k, v)
|
||||
await auth.db.flush()
|
||||
log.info(f"租户[{tenant_id}]配额已更新: {update_data}")
|
||||
return TenantQuotaOutSchema(
|
||||
tenant_id=tenant.id,
|
||||
max_users=tenant.max_users,
|
||||
max_roles=tenant.max_roles,
|
||||
max_storage_mb=tenant.max_storage_mb,
|
||||
max_depts=tenant.max_depts,
|
||||
).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def check_quota_service(
|
||||
cls,
|
||||
auth: AuthSchema,
|
||||
tenant_id: int,
|
||||
resource_type: str, # "user"/"role"/"dept"
|
||||
) -> None:
|
||||
"""检查租户配额是否充足,不足时抛出异常"""
|
||||
from sqlalchemy import func, select
|
||||
|
||||
tenant = await TenantCRUD(auth).get_by_id_crud(id=tenant_id)
|
||||
if not tenant:
|
||||
raise CustomException(msg="租户不存在")
|
||||
|
||||
field_map = {
|
||||
"user": "max_users",
|
||||
"role": "max_roles",
|
||||
"dept": "max_depts",
|
||||
}
|
||||
if resource_type not in field_map:
|
||||
return
|
||||
|
||||
max_field = field_map[resource_type]
|
||||
max_limit = getattr(tenant, max_field, 0)
|
||||
|
||||
# 根据资源类型动态获取当前数量
|
||||
if resource_type == "user":
|
||||
from app.api.v1.module_system.user.model import UserModel
|
||||
count_stmt = select(func.count()).select_from(UserModel).where(
|
||||
UserModel.tenant_id == tenant_id,
|
||||
UserModel.is_deleted.is_(False),
|
||||
)
|
||||
elif resource_type == "role":
|
||||
from app.api.v1.module_system.role.model import RoleModel
|
||||
count_stmt = select(func.count()).select_from(RoleModel).where(
|
||||
RoleModel.tenant_id == tenant_id,
|
||||
RoleModel.is_deleted.is_(False),
|
||||
)
|
||||
elif resource_type == "dept":
|
||||
from app.api.v1.module_system.dept.model import DeptModel
|
||||
count_stmt = select(func.count()).select_from(DeptModel).where(
|
||||
DeptModel.tenant_id == tenant_id,
|
||||
DeptModel.is_deleted.is_(False),
|
||||
)
|
||||
|
||||
result = await auth.db.execute(count_stmt)
|
||||
current_count = result.scalar() or 0
|
||||
|
||||
if max_limit > 0 and current_count >= max_limit:
|
||||
resource_labels = {"user": "用户", "role": "角色", "dept": "部门"}
|
||||
raise CustomException(
|
||||
msg=f"租户{resource_labels.get(resource_type, resource_type)}数量已达上限({max_limit}),无法继续创建"
|
||||
)
|
||||
|
||||
# ============ P1: 租户配置 ============
|
||||
|
||||
@classmethod
|
||||
async def get_config_service(cls, auth: AuthSchema, tenant_id: int) -> list[dict]:
|
||||
"""获取租户所有配置(带 Redis 缓存)"""
|
||||
from sqlalchemy import select
|
||||
|
||||
stmt = select(TenantConfigModel).where(TenantConfigModel.tenant_id == tenant_id)
|
||||
result = await auth.db.execute(stmt)
|
||||
configs = result.scalars().all()
|
||||
return [TenantConfigOutSchema.model_validate(c).model_dump() for c in configs]
|
||||
|
||||
@classmethod
|
||||
async def get_config_cache_service(cls, redis: Redis, tenant_id: int) -> list[dict]:
|
||||
"""
|
||||
从 Redis 缓存获取租户配置,缓存未命中则从 DB 加载并回写缓存
|
||||
|
||||
参数:
|
||||
- redis (Redis): Redis 客户端实例
|
||||
- tenant_id (int): 租户ID
|
||||
|
||||
返回:
|
||||
- list[dict]: 租户配置列表
|
||||
"""
|
||||
redis_keys = await RedisCURD(redis).get_keys(
|
||||
f"{RedisInitKeyConfig.TENANT_CONFIG.key}:{tenant_id}:*"
|
||||
)
|
||||
redis_configs = await RedisCURD(redis).mget(redis_keys)
|
||||
configs = []
|
||||
for config in redis_configs:
|
||||
if not config:
|
||||
continue
|
||||
try:
|
||||
configs.append(json.loads(config))
|
||||
except Exception as e:
|
||||
log.error(f"解析租户配置数据失败: {e}")
|
||||
continue
|
||||
|
||||
if not configs:
|
||||
log.info(f"Redis 中没有租户[{tenant_id}]配置数据,从数据库中加载")
|
||||
from app.core.database import async_db_session
|
||||
|
||||
async with async_db_session() as session:
|
||||
async with session.begin():
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
|
||||
auth = AuthSchema(db=session, check_data_scope=False)
|
||||
configs = await cls.get_config_service(auth, tenant_id)
|
||||
await cls._sync_configs_to_redis(redis, tenant_id, configs)
|
||||
log.info(f"✅ 已从数据库加载 {len(configs)} 条租户配置到缓存")
|
||||
|
||||
return configs
|
||||
|
||||
@classmethod
|
||||
async def _sync_configs_to_redis(
|
||||
cls, redis: Redis, tenant_id: int, configs: list[dict]
|
||||
) -> None:
|
||||
"""将租户配置列表批量写入 Redis 缓存"""
|
||||
for cfg in configs:
|
||||
redis_key = (
|
||||
f"{RedisInitKeyConfig.TENANT_CONFIG.key}:{tenant_id}:{cfg.get('config_key')}"
|
||||
)
|
||||
value = json.dumps(cfg, ensure_ascii=False)
|
||||
await RedisCURD(redis).set(key=redis_key, value=value, expire=None)
|
||||
|
||||
@classmethod
|
||||
async def _del_configs_from_redis(cls, redis: Redis, tenant_id: int, keys: list[str]) -> None:
|
||||
"""删除租户配置的 Redis 缓存"""
|
||||
redis_keys = [f"{RedisInitKeyConfig.TENANT_CONFIG.key}:{tenant_id}:{k}" for k in keys]
|
||||
if redis_keys:
|
||||
await RedisCURD(redis).delete(*redis_keys)
|
||||
|
||||
@classmethod
|
||||
async def update_config_service(
|
||||
cls, auth: AuthSchema, redis: Redis, tenant_id: int, items: list[TenantConfigItem]
|
||||
) -> list[dict]:
|
||||
"""批量更新租户配置(同步 Redis 缓存)"""
|
||||
from sqlalchemy import select
|
||||
|
||||
for item in items:
|
||||
stmt = (
|
||||
select(TenantConfigModel)
|
||||
.where(
|
||||
TenantConfigModel.tenant_id == tenant_id,
|
||||
TenantConfigModel.config_key == item.config_key,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
result = await auth.db.execute(stmt)
|
||||
cfg = result.scalar_one_or_none()
|
||||
if cfg:
|
||||
cfg.config_value = item.config_value
|
||||
if item.config_type:
|
||||
cfg.config_type = item.config_type
|
||||
else:
|
||||
cfg = TenantConfigModel(
|
||||
tenant_id=tenant_id,
|
||||
config_key=item.config_key,
|
||||
config_value=item.config_value,
|
||||
config_type=item.config_type or "string",
|
||||
)
|
||||
auth.db.add(cfg)
|
||||
await auth.db.flush()
|
||||
|
||||
# 刷新 DB 数据并同步到 Redis
|
||||
configs = await cls.get_config_service(auth, tenant_id)
|
||||
await cls._sync_configs_to_redis(redis, tenant_id, configs)
|
||||
log.info(f"租户[{tenant_id}]配置已更新, keys={[i.config_key for i in items]}")
|
||||
return configs
|
||||
|
||||
# ============ P1: 租户菜单 ============
|
||||
|
||||
@classmethod
|
||||
async def get_menus_service(cls, auth: AuthSchema, tenant_id: int) -> list[int]:
|
||||
"""获取租户菜单权限(返回 menu_id 列表)"""
|
||||
from sqlalchemy import select
|
||||
|
||||
stmt = select(TenantMenuModel.menu_id).where(TenantMenuModel.tenant_id == tenant_id)
|
||||
result = await auth.db.execute(stmt)
|
||||
return [row[0] for row in result.all()]
|
||||
|
||||
@classmethod
|
||||
async def set_menus_service(
|
||||
cls, auth: AuthSchema, tenant_id: int, data: TenantMenuSetSchema
|
||||
) -> None:
|
||||
"""批量设置租户菜单权限(先清空再写入)"""
|
||||
from sqlalchemy import delete
|
||||
|
||||
await auth.db.execute(delete(TenantMenuModel).where(TenantMenuModel.tenant_id == tenant_id))
|
||||
for menu_id in data.menu_ids:
|
||||
auth.db.add(TenantMenuModel(tenant_id=tenant_id, menu_id=menu_id))
|
||||
await auth.db.flush()
|
||||
log.info(f"租户[{tenant_id}]菜单权限已设置, count={len(data.menu_ids)}")
|
||||
|
||||
@staticmethod
|
||||
async def get_tenant_menu_ids(auth: AuthSchema, tenant_id: int) -> list[int]:
|
||||
"""获取租户可用菜单ID列表(套餐菜单 + 自定义授权菜单的并集)
|
||||
|
||||
供角色/用户权限约束使用。
|
||||
"""
|
||||
from app.api.v1.module_platform.package.service import PackageService
|
||||
|
||||
return await PackageService.get_tenant_available_menu_ids(auth, tenant_id)
|
||||
|
||||
# ============ P1: 初始化缓存 ============
|
||||
|
||||
@classmethod
|
||||
async def init_tenant_config_cache(cls, redis: Redis) -> None:
|
||||
"""
|
||||
初始化所有租户配置到 Redis 缓存(应用启动时调用)。
|
||||
|
||||
参数:
|
||||
- redis (Redis): Redis 客户端实例
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.database import async_db_session
|
||||
|
||||
async with async_db_session() as session:
|
||||
async with session.begin():
|
||||
stmt = select(TenantModel)
|
||||
result = await session.execute(stmt)
|
||||
tenants = result.scalars().all()
|
||||
|
||||
for tenant in tenants:
|
||||
config_stmt = select(TenantConfigModel).where(
|
||||
TenantConfigModel.tenant_id == tenant.id
|
||||
)
|
||||
config_result = await session.execute(config_stmt)
|
||||
configs = config_result.scalars().all()
|
||||
config_list = [
|
||||
TenantConfigOutSchema.model_validate(c).model_dump() for c in configs
|
||||
]
|
||||
|
||||
if config_list:
|
||||
await cls._sync_configs_to_redis(redis, tenant.id, config_list)
|
||||
log.info(
|
||||
f"✅ 租户[{tenant.name}](id={tenant.id}) {len(config_list)} 条配置已缓存到 Redis"
|
||||
)
|
||||
else:
|
||||
log.warning(f"⚠️ 租户[{tenant.name}](id={tenant.id}) 无配置数据,跳过缓存")
|
||||
|
||||
# ============ P1: 到期提醒 ============
|
||||
|
||||
@staticmethod
|
||||
async def check_tenant_expiry() -> None:
|
||||
"""定时任务:检查租户到期并发送通知 / 自动禁用"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app.core.db_session import async_session_factory
|
||||
|
||||
async with async_session_factory() as db:
|
||||
now = datetime.now()
|
||||
# 扫描所有启用的租户
|
||||
stmt = sa.select(TenantModel).where(
|
||||
TenantModel.status == "0",
|
||||
TenantModel.end_time.isnot(None),
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
tenants = result.scalars().all()
|
||||
|
||||
for t in tenants:
|
||||
if t.end_time <= now:
|
||||
# 已到期:自动禁用
|
||||
await db.execute(
|
||||
sa.update(TenantModel).where(TenantModel.id == t.id).values(status="1")
|
||||
)
|
||||
log.info(f"租户[{t.name}]已到期,自动禁用")
|
||||
elif t.end_time <= now + timedelta(days=1):
|
||||
TenantService._notify_expiry(t, 1)
|
||||
elif t.end_time <= now + timedelta(days=7):
|
||||
TenantService._notify_expiry(t, 7)
|
||||
elif t.end_time <= now + timedelta(days=30):
|
||||
TenantService._notify_expiry(t, 30)
|
||||
|
||||
await db.commit()
|
||||
|
||||
@staticmethod
|
||||
async def _notify_expiry(tenant: TenantModel, days: int) -> None:
|
||||
"""发送到期提醒通知"""
|
||||
log.info(f"租户[{tenant.name}]将在 {days} 天后到期,联系人: {tenant.contact_email}")
|
||||
Reference in New Issue
Block a user