mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-21 04:46:26 +00:00
feat(docs): enhance README and backend documentation for new user onboarding and backend conventions
- Added a "Start Here" section in both English and Chinese README files to guide new users on running the project locally and exploring its features. - Introduced backend conventions for date and serialization handling, clarifying the use of Pydantic v2 and PostgreSQL. - Updated the "Quick Start" section with detailed steps for first-time local setup, including environment requirements and backend setup instructions. - Improved overall structure and clarity of documentation to facilitate better understanding for developers and contributors.
This commit is contained in:
@@ -165,7 +165,7 @@ class DictTypeService:
|
||||
search={"dict_type": data.dict_type}
|
||||
)
|
||||
dict_data = [
|
||||
DictDataOutSchema.model_validate(row).model_dump() for row in dict_data_list if row
|
||||
DictDataOutSchema.model_validate(row).model_dump(mode="json") for row in dict_data_list if row
|
||||
]
|
||||
|
||||
value = json.dumps(dict_data, ensure_ascii=False)
|
||||
@@ -336,7 +336,7 @@ class DictDataService:
|
||||
search={"dict_type": dict_type}
|
||||
)
|
||||
dict_data = [
|
||||
DictDataOutSchema.model_validate(row).model_dump()
|
||||
DictDataOutSchema.model_validate(row).model_dump(mode="json")
|
||||
for row in dict_data_list
|
||||
if row
|
||||
]
|
||||
@@ -438,7 +438,7 @@ class DictDataService:
|
||||
search={"dict_type": data.dict_type}
|
||||
)
|
||||
dict_data = [
|
||||
DictDataOutSchema.model_validate(row).model_dump() for row in dict_data_list if row
|
||||
DictDataOutSchema.model_validate(row).model_dump(mode="json") for row in dict_data_list if row
|
||||
]
|
||||
|
||||
value = json.dumps(dict_data, ensure_ascii=False)
|
||||
@@ -507,7 +507,7 @@ class DictDataService:
|
||||
search={"dict_type": dict_type.dict_type}
|
||||
)
|
||||
dict_data = [
|
||||
DictDataOutSchema.model_validate(row).model_dump()
|
||||
DictDataOutSchema.model_validate(row).model_dump(mode="json")
|
||||
for row in dict_data_list
|
||||
if row
|
||||
]
|
||||
@@ -527,7 +527,7 @@ class DictDataService:
|
||||
search={"dict_type": data.dict_type}
|
||||
)
|
||||
dict_data = [
|
||||
DictDataOutSchema.model_validate(row).model_dump() for row in dict_data_list if row
|
||||
DictDataOutSchema.model_validate(row).model_dump(mode="json") for row in dict_data_list if row
|
||||
]
|
||||
|
||||
value = json.dumps(dict_data, ensure_ascii=False)
|
||||
|
||||
@@ -166,12 +166,14 @@ class ParamsService:
|
||||
new_obj = await ParamsCRUD(auth).update_obj_crud(id=id, data=data)
|
||||
if not new_obj:
|
||||
raise CustomException(msg="更新失败,系统配置不存在")
|
||||
new_obj_dict = ParamsOutSchema.model_validate(new_obj).model_dump()
|
||||
out = ParamsOutSchema.model_validate(new_obj)
|
||||
new_obj_dict = out.model_dump()
|
||||
redis_payload = out.model_dump(mode="json")
|
||||
|
||||
# 同步redis
|
||||
redis_key = f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{new_obj.config_key}"
|
||||
try:
|
||||
value = json.dumps(new_obj_dict, ensure_ascii=False)
|
||||
value = json.dumps(redis_payload, ensure_ascii=False)
|
||||
result = await RedisCURD(redis).set(
|
||||
key=redis_key,
|
||||
value=value,
|
||||
@@ -306,8 +308,10 @@ class ParamsService:
|
||||
# 保存到Redis并设置过期时间
|
||||
for config in config_obj:
|
||||
redis_key = f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{config.config_key}"
|
||||
config_obj_dict = ParamsOutSchema.model_validate(config).model_dump()
|
||||
value = json.dumps(config_obj_dict, ensure_ascii=False)
|
||||
out = ParamsOutSchema.model_validate(config)
|
||||
config_obj_dict = out.model_dump()
|
||||
redis_payload = out.model_dump(mode="json")
|
||||
value = json.dumps(redis_payload, ensure_ascii=False)
|
||||
result = await RedisCURD(redis).set(
|
||||
key=redis_key,
|
||||
value=value,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# # -*- coding: utf-8 -*-
|
||||
|
||||
# from fastapi import APIRouter, Body, Depends, Path, UploadFile
|
||||
# from fastapi.responses import JSONResponse, StreamingResponse
|
||||
@@ -30,11 +29,11 @@
|
||||
# ) -> JSONResponse:
|
||||
# """
|
||||
# 获取租户详情
|
||||
|
||||
|
||||
# 参数:
|
||||
# - id (int): 租户ID
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - JSONResponse: 包含租户详情的JSON响应
|
||||
# """
|
||||
@@ -50,21 +49,21 @@
|
||||
# ) -> JSONResponse:
|
||||
# """
|
||||
# 查询租户列表
|
||||
|
||||
|
||||
# 参数:
|
||||
# - page (PaginationQueryParam): 分页查询参数
|
||||
# - search (TenantQueryParam): 查询参数
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - JSONResponse: 包含租户列表分页信息的JSON响应
|
||||
# """
|
||||
# # 使用数据库分页而不是应用层分页
|
||||
# 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,
|
||||
# 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=page.order_by
|
||||
# )
|
||||
# log.info("查询租户列表成功")
|
||||
@@ -77,11 +76,11 @@
|
||||
# ) -> JSONResponse:
|
||||
# """
|
||||
# 创建租户
|
||||
|
||||
|
||||
# 参数:
|
||||
# - data (TenantCreateSchema): 租户创建模型
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - JSONResponse: 包含创建租户详情的JSON响应
|
||||
# """
|
||||
@@ -97,12 +96,12 @@
|
||||
# ) -> JSONResponse:
|
||||
# """
|
||||
# 修改租户
|
||||
|
||||
|
||||
# 参数:
|
||||
# - data (TenantUpdateSchema): 租户更新模型
|
||||
# - id (int): 租户ID
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - JSONResponse: 包含修改租户详情的JSON响应
|
||||
# """
|
||||
@@ -117,11 +116,11 @@
|
||||
# ) -> JSONResponse:
|
||||
# """
|
||||
# 删除租户
|
||||
|
||||
|
||||
# 参数:
|
||||
# - ids (list[int]): 租户ID列表
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - JSONResponse: 包含删除租户详情的JSON响应
|
||||
# """
|
||||
@@ -136,11 +135,11 @@
|
||||
# ) -> JSONResponse:
|
||||
# """
|
||||
# 批量修改租户状态
|
||||
|
||||
|
||||
# 参数:
|
||||
# - data (BatchSetAvailable): 批量修改租户状态模型
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - JSONResponse: 包含批量修改租户状态详情的JSON响应
|
||||
# """
|
||||
@@ -155,11 +154,11 @@
|
||||
# ) -> StreamingResponse:
|
||||
# """
|
||||
# 导出租户
|
||||
|
||||
|
||||
# 参数:
|
||||
# - search (TenantQueryParam): 查询参数
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - StreamingResponse: 包含租户列表的Excel文件流响应
|
||||
# """
|
||||
@@ -182,11 +181,11 @@
|
||||
# ) -> JSONResponse:
|
||||
# """
|
||||
# 导入租户
|
||||
|
||||
|
||||
# 参数:
|
||||
# - file (UploadFile): 导入的Excel文件
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - JSONResponse: 包含导入租户详情的JSON响应
|
||||
# """
|
||||
@@ -198,7 +197,7 @@
|
||||
# async def export_obj_template_controller() -> StreamingResponse:
|
||||
# """
|
||||
# 获取租户导入模板
|
||||
|
||||
|
||||
# 返回:
|
||||
# - StreamingResponse: 包含租户导入模板的Excel文件流响应
|
||||
# """
|
||||
@@ -212,4 +211,4 @@
|
||||
# 'Content-Disposition': f'attachment; filename={urllib.parse.quote("租户导入模板.xlsx")}',
|
||||
# 'Access-Control-Expose-Headers': 'Content-Disposition'
|
||||
# }
|
||||
# )
|
||||
# )
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# # -*- coding: utf-8 -*-
|
||||
|
||||
# from typing import Dict, List, Optional, Sequence, Union, Any
|
||||
|
||||
@@ -15,106 +14,106 @@
|
||||
# def __init__(self, auth: AuthSchema) -> None:
|
||||
# """
|
||||
# 初始化CRUD数据层
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# """
|
||||
# super().__init__(model=TenantModel, auth=auth)
|
||||
|
||||
|
||||
# async def get_by_id_crud(self, id: int, preload: Optional[List[Union[str, Any]]] = None) -> Optional[TenantModel]:
|
||||
# """
|
||||
# 详情
|
||||
|
||||
|
||||
# 参数:
|
||||
# - id (int): 租户ID
|
||||
# - preload (Optional[List[Union[str, Any]]]): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Optional[TenantModel]: 租户模型实例或None
|
||||
# """
|
||||
# return await self.get(id=id, preload=preload)
|
||||
|
||||
|
||||
# async def list_crud(self, search: Optional[Dict] = None, order_by: Optional[List[Dict[str, str]]] = None, preload: Optional[List[Union[str, Any]]] = None) -> Sequence[TenantModel]:
|
||||
# """
|
||||
# 列表查询
|
||||
|
||||
|
||||
# 参数:
|
||||
# - search (Optional[Dict]): 查询参数
|
||||
# - order_by (Optional[List[Dict[str, str]]]): 排序参数
|
||||
# - preload (Optional[List[Union[str, Any]]]): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Sequence[TenantModel]: 租户模型实例序列
|
||||
# """
|
||||
# return await self.list(search=search, order_by=order_by, preload=preload)
|
||||
|
||||
|
||||
# async def create_crud(self, data: TenantCreateSchema) -> Optional[TenantModel]:
|
||||
# """
|
||||
# 创建
|
||||
|
||||
|
||||
# 参数:
|
||||
# - data (TenantCreateSchema): 租户创建模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Optional[TenantModel]: 租户模型实例或None
|
||||
# """
|
||||
# return await self.create(data=data)
|
||||
|
||||
|
||||
# async def update_crud(self, id: int, data: TenantUpdateSchema) -> Optional[TenantModel]:
|
||||
# """
|
||||
# 更新
|
||||
|
||||
|
||||
# 参数:
|
||||
# - id (int): 租户ID
|
||||
# - data (TenantUpdateSchema): 租户更新模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Optional[TenantModel]: 租户模型实例或None
|
||||
# """
|
||||
# return await self.update(id=id, data=data)
|
||||
|
||||
|
||||
# async def delete_crud(self, ids: List[int]) -> None:
|
||||
# """
|
||||
# 批量删除
|
||||
|
||||
|
||||
# 参数:
|
||||
# - ids (List[int]): 租户ID列表
|
||||
|
||||
|
||||
# 返回:
|
||||
# - None
|
||||
# """
|
||||
# return await self.delete(ids=ids)
|
||||
|
||||
|
||||
# async def set_available_crud(self, ids: List[int], status: str) -> None:
|
||||
# """
|
||||
# 批量设置可用状态
|
||||
|
||||
|
||||
# 参数:
|
||||
# - ids (List[int]): 租户ID列表
|
||||
# - status (bool): 可用状态
|
||||
|
||||
|
||||
# 返回:
|
||||
# - None
|
||||
# """
|
||||
# return await self.set(ids=ids, status=status)
|
||||
|
||||
|
||||
# async def page_crud(self, offset: int, limit: int, order_by: Optional[List[Dict[str, str]]] = None, search: Optional[Dict] = None, preload: Optional[List[Union[str, Any]]] = None) -> Dict:
|
||||
# """
|
||||
# 分页查询
|
||||
|
||||
|
||||
# 参数:
|
||||
# - offset (int): 偏移量
|
||||
# - limit (int): 每页数量
|
||||
# - order_by (Optional[List[Dict[str, str]]]): 排序参数
|
||||
# - search (Optional[Dict]): 查询参数
|
||||
# - preload (Optional[List[Union[str, Any]]]): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Dict: 分页数据
|
||||
# """
|
||||
# order_by_list = order_by or [{'id': 'asc'}]
|
||||
# search_dict = search or {}
|
||||
|
||||
|
||||
# return await self.page(
|
||||
# offset=offset,
|
||||
# limit=limit,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# # -*- coding: utf-8 -*-
|
||||
|
||||
# from datetime import datetime
|
||||
# from sqlalchemy import DateTime, String
|
||||
@@ -10,12 +9,12 @@
|
||||
# class TenantModel(ModelMixin):
|
||||
# """
|
||||
# 租户模型
|
||||
|
||||
|
||||
# 核心数据隔离模型:
|
||||
# - 系统租户(id=1):管理所有租户和系统配置,由平台超管管理
|
||||
# - 普通租户(id>1):拥有自己的用户、部门、角色、客户等数据,租户间完全隔离
|
||||
# - 所有业务表通过tenant_id字段关联到租户,实现租户间数据隔离
|
||||
|
||||
|
||||
# 注意:
|
||||
# - 租户表本身不需要tenant_id字段(租户不属于租户)
|
||||
# - 租户表不需要customer_id字段(租户不属于客户)
|
||||
@@ -28,14 +27,14 @@
|
||||
# code: Mapped[str] = mapped_column(String(100), nullable=False, unique=True, comment='租户编码')
|
||||
# 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='结束时间')
|
||||
|
||||
|
||||
# @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:
|
||||
# """验证编码格式校验"""
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# # -*- coding: utf-8 -*-
|
||||
|
||||
# from typing import Optional
|
||||
# from fastapi import Query
|
||||
@@ -17,8 +16,8 @@
|
||||
# description: Optional[str] = Field(default=None, max_length=255, description="描述")
|
||||
# start_time: Optional[DateTimeStr] = Field(default=None, description="开始时间")
|
||||
# end_time: Optional[DateTimeStr] = Field(default=None, description="结束时间")
|
||||
|
||||
# @field_validator('name')
|
||||
|
||||
# @field_validator('name')
|
||||
# @classmethod
|
||||
# def _validate_name(cls, v: str) -> str:
|
||||
# v = v.strip()
|
||||
@@ -37,7 +36,7 @@
|
||||
# # 格式校验:名称只能包含字母、数字、下划线和中划线
|
||||
# if not self.name.isalnum() and not all(c in '-_' for c in self.name):
|
||||
# raise ValueError('名称只能包含字母、数字、下划线和中划线')
|
||||
|
||||
|
||||
# return self
|
||||
|
||||
|
||||
@@ -60,7 +59,7 @@
|
||||
# status: Optional[str] = Query(None, description="状态用(True:启用 False:禁用)"),
|
||||
# created_time: Optional[list[DateTimeStr]] = Query(None, description="创建时间范围", example=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
|
||||
# ) -> None:
|
||||
|
||||
|
||||
# # 模糊查询字段
|
||||
# self.name = ("like", name)
|
||||
|
||||
@@ -70,4 +69,3 @@
|
||||
# # 时间范围查询
|
||||
# if created_time and len(created_time) == 2:
|
||||
# self.created_time = ("between", (created_time[0], created_time[1]))
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# # -*- coding: utf-8 -*-
|
||||
|
||||
# import io
|
||||
# import random
|
||||
@@ -24,64 +23,64 @@
|
||||
# """
|
||||
# 租户管理模块服务层
|
||||
# """
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def detail_service(cls, auth: AuthSchema, id: int) -> Dict:
|
||||
# """
|
||||
# 详情
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - id (int): 租户ID
|
||||
|
||||
|
||||
# 返回:
|
||||
# - 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 list_service(cls, auth: AuthSchema, search: Optional[TenantQueryParam] = None, order_by: Optional[List[Dict[str, str]]] = None) -> List[Dict]:
|
||||
# """
|
||||
# 列表查询
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - search (Optional[TenantQueryParam]): 查询参数
|
||||
# - order_by (Optional[List[Dict[str, str]]]): 排序参数
|
||||
|
||||
|
||||
# 返回:
|
||||
# - List[Dict]: 租户模型实例字典列表
|
||||
# """
|
||||
# search_dict = search.__dict__ if search else None
|
||||
# obj_list = await TenantCRUD(auth).list_crud(search=search_dict, order_by=order_by)
|
||||
# return [TenantOutSchema.model_validate(obj).model_dump() for obj in obj_list]
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def page_service(cls, auth: AuthSchema, page_no: int, page_size: int, search: Optional[TenantQueryParam] = None, order_by: Optional[List[Dict[str, str]]] = None) -> Dict:
|
||||
# """
|
||||
# 分页查询
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - page_no (int): 页码
|
||||
# - page_size (int): 每页数量
|
||||
# - search (Optional[TenantQueryParam]): 查询参数
|
||||
# - order_by (Optional[List[Dict[str, str]]]): 排序参数
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Dict: 分页数据
|
||||
# """
|
||||
# search_dict = search.__dict__ if search else {}
|
||||
# order_by_list = order_by or [{'id': 'asc'}]
|
||||
# offset = (page_no - 1) * page_size
|
||||
|
||||
|
||||
# result = await TenantCRUD(auth).page_crud(
|
||||
# offset=offset,
|
||||
# limit=page_size,
|
||||
@@ -89,16 +88,16 @@
|
||||
# search=search_dict
|
||||
# )
|
||||
# return result
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def create_service(cls, auth: AuthSchema, data: TenantCreateSchema) -> Dict:
|
||||
# """
|
||||
# 创建
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - data (TenantCreateSchema): 租户创建模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Dict: 租户模型实例字典
|
||||
# """
|
||||
@@ -111,33 +110,33 @@
|
||||
|
||||
# # 创建租户
|
||||
# tenant_obj = await TenantCRUD(auth).create_crud(data=data)
|
||||
|
||||
|
||||
# # 自动创建租户初始管理员用户
|
||||
# await cls._create_tenant_admin_user(auth, tenant_obj)
|
||||
|
||||
|
||||
# return TenantOutSchema.model_validate(tenant_obj).model_dump()
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def _create_tenant_admin_user(cls, auth: AuthSchema, tenant_obj) -> None:
|
||||
# """
|
||||
# 为新创建的租户自动创建初始管理员用户
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - tenant_obj: 租户对象
|
||||
|
||||
|
||||
# 返回:
|
||||
# - None
|
||||
# """
|
||||
# try:
|
||||
# # 生成初始管理员用户名(使用租户编码)
|
||||
# username = f"{tenant_obj.code}_admin"
|
||||
|
||||
|
||||
# # 生成随机密码
|
||||
# password_length = 12
|
||||
# characters = string.ascii_letters + string.digits + "!@#$%^&*"
|
||||
# password = ''.join(random.choice(characters) for _ in range(password_length))
|
||||
|
||||
|
||||
# # 创建管理员用户数据
|
||||
# admin_user_data = {
|
||||
# "username": username,
|
||||
@@ -148,28 +147,28 @@
|
||||
# "status": True,
|
||||
# "created_id": auth.user.id if auth.user else None
|
||||
# }
|
||||
|
||||
|
||||
# # 创建用户
|
||||
# new_user = await UserCRUD(auth).create(data=admin_user_data)
|
||||
|
||||
|
||||
# # 记录日志,包含临时密码信息(仅开发环境记录,生产环境应避免)
|
||||
# log.info(f"为租户[{tenant_obj.name}]创建初始管理员用户成功,用户名: {username},临时密码: {password}")
|
||||
|
||||
|
||||
# except Exception as e:
|
||||
# log.error(f"为租户[{tenant_obj.name}]创建初始管理员用户失败: {str(e)}")
|
||||
# # 不中断租户创建流程,仅记录错误
|
||||
# pass
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def update_service(cls, auth: AuthSchema, id: int, data: TenantUpdateSchema) -> Dict:
|
||||
# """
|
||||
# 更新
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - id (int): 租户ID
|
||||
# - data (TenantUpdateSchema): 租户更新模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - Dict: 租户模型实例字典
|
||||
# """
|
||||
@@ -177,81 +176,81 @@
|
||||
# if id == 1:
|
||||
# obj = await TenantCRUD(auth).update_crud(id=id, data=data)
|
||||
# log.info(f"系统租户配额设置已更新")
|
||||
|
||||
|
||||
# return TenantOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
|
||||
# # 检查数据是否存在
|
||||
# obj = await TenantCRUD(auth).get_by_id_crud(id=id)
|
||||
# if not obj:
|
||||
# raise CustomException(msg='更新失败,该数据不存在')
|
||||
|
||||
|
||||
# # 检查名称是否重复
|
||||
# exist_obj = await TenantCRUD(auth).get(name=data.name)
|
||||
# if exist_obj and exist_obj.id != id:
|
||||
# raise CustomException(msg='更新失败,名称重复')
|
||||
|
||||
|
||||
# obj = await TenantCRUD(auth).update_crud(id=id, data=data)
|
||||
# return TenantOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def delete_service(cls, auth: AuthSchema, ids: List[int]) -> None:
|
||||
# """
|
||||
# 删除
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - ids (List[int]): 租户ID列表
|
||||
|
||||
|
||||
# 返回:
|
||||
# - None
|
||||
# """
|
||||
# if len(ids) < 1:
|
||||
# raise CustomException(msg='删除失败,删除对象不能为空')
|
||||
|
||||
|
||||
# # 系统租户保护:不允许删除系统租户(id=1)
|
||||
# if 1 in ids:
|
||||
# raise CustomException(msg='系统租户不允许删除')
|
||||
|
||||
|
||||
# # 检查所有要删除的数据是否存在
|
||||
# for id in ids:
|
||||
# obj = await TenantCRUD(auth).get_by_id_crud(id=id)
|
||||
# if not obj:
|
||||
# raise CustomException(msg=f'删除失败,ID为{id}的数据不存在')
|
||||
|
||||
|
||||
# await TenantCRUD(auth).delete_crud(ids=ids)
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def set_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
||||
# """
|
||||
# 批量设置状态
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - data (BatchSetAvailable): 批量设置状态模型
|
||||
|
||||
|
||||
# 返回:
|
||||
# - None
|
||||
# """
|
||||
# # 系统租户保护:不允许禁用系统租户(id=1)
|
||||
# if data.status is False and 1 in data.ids:
|
||||
# raise CustomException(msg='系统租户不允许禁用')
|
||||
|
||||
|
||||
# await TenantCRUD(auth).set_available_crud(ids=data.ids, status=data.status)
|
||||
|
||||
|
||||
# @classmethod
|
||||
# async def batch_export_service(cls, obj_list: List[Dict[str, Any]]) -> bytes:
|
||||
# """
|
||||
# 批量导出
|
||||
|
||||
|
||||
# 参数:
|
||||
# - obj_list (List[Dict[str, Any]]): 租户模型实例字典列表
|
||||
|
||||
|
||||
# 返回:
|
||||
# - bytes: Excel文件字节流
|
||||
# """
|
||||
# mapping_dict = {
|
||||
# 'id': '编号',
|
||||
# 'name': '名称',
|
||||
# 'name': '名称',
|
||||
# 'code': '编码',
|
||||
# 'status': '状态',
|
||||
# 'description': '备注',
|
||||
@@ -268,17 +267,17 @@
|
||||
# # 系统租户特殊标记
|
||||
# if item.get('id') == 1:
|
||||
# item['name'] = f"{item.get('name')} [系统租户]"
|
||||
|
||||
|
||||
# # 处理状态
|
||||
# item['status'] = '正常' if item.get('status') else '停用'
|
||||
|
||||
|
||||
# # 处理创建者
|
||||
# creator_info = item.get('created_id')
|
||||
# if isinstance(creator_info, dict):
|
||||
# item['created_id'] = creator_info.get('name', '未知')
|
||||
# else:
|
||||
# item['created_id'] = '未知'
|
||||
|
||||
|
||||
# # 限制导出数量,防止大数据量导出
|
||||
# max_export_count = 1000
|
||||
# if len(data) > max_export_count:
|
||||
@@ -291,16 +290,16 @@
|
||||
# async def batch_import_service(cls, auth: AuthSchema, file: UploadFile, update_support: bool = False) -> str:
|
||||
# """
|
||||
# 批量导入
|
||||
|
||||
|
||||
# 参数:
|
||||
# - auth (AuthSchema): 认证信息模型
|
||||
# - file (UploadFile): 上传的Excel文件
|
||||
# - update_support (bool): 是否支持更新存在数据
|
||||
|
||||
|
||||
# 返回:
|
||||
# - str: 导入结果信息
|
||||
# """
|
||||
|
||||
|
||||
# header_dict = {
|
||||
# '名称': 'name',
|
||||
# '编码': 'code',
|
||||
@@ -315,23 +314,23 @@
|
||||
# contents = await file.read()
|
||||
# df = pd.read_excel(io.BytesIO(contents))
|
||||
# await file.close()
|
||||
|
||||
|
||||
# # 验证导入数量限制
|
||||
# max_import_count = 100
|
||||
# if len(df) > max_import_count:
|
||||
# raise CustomException(msg=f"单次导入不能超过{max_import_count}条数据")
|
||||
|
||||
|
||||
# if df.empty:
|
||||
# raise CustomException(msg="导入文件为空")
|
||||
|
||||
|
||||
# # 检查表头是否完整
|
||||
# missing_headers = [header for header in header_dict.keys() if header not in df.columns]
|
||||
# if missing_headers:
|
||||
# raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
|
||||
|
||||
|
||||
# # 重命名列名
|
||||
# df.rename(columns=header_dict, inplace=True)
|
||||
|
||||
|
||||
# # 验证必填字段
|
||||
# required_fields = ['name', 'code', 'status']
|
||||
# for field in required_fields:
|
||||
@@ -340,13 +339,13 @@
|
||||
# field_name = [k for k,v in header_dict.items() if v == field][0]
|
||||
# error_rows = [i+1 for i in missing_rows]
|
||||
# raise CustomException(msg=f"{field_name}不能为空,第{error_rows}行")
|
||||
|
||||
|
||||
# error_msgs = []
|
||||
# success_count = 0
|
||||
# count = 0
|
||||
# processed_names = set() # 用于检测重复名称
|
||||
# processed_codes = set() # 用于检测重复编码
|
||||
|
||||
|
||||
# # 处理每一行数据
|
||||
# for index, row in df.iterrows():
|
||||
# count += 1
|
||||
@@ -357,31 +356,31 @@
|
||||
# except ValueError:
|
||||
# error_msgs.append(f"第{count}行: 状态必须是'正常'或'停用'")
|
||||
# continue
|
||||
|
||||
|
||||
# # 字段格式验证
|
||||
# name = str(row['name']).strip()
|
||||
# if len(name) < 2 or len(name) > 64:
|
||||
# error_msgs.append(f"第{count}行: 租户名称长度必须在2-64个字符之间")
|
||||
# continue
|
||||
|
||||
|
||||
# # 检查名称是否只包含允许的字符
|
||||
# if not all(c.isalnum() or c in '-_' for c in name.replace(' ', '')):
|
||||
# error_msgs.append(f"第{count}行: 租户名称只能包含字母、数字、下划线、中划线和空格")
|
||||
# continue
|
||||
|
||||
|
||||
# # 检查导入文件内的重复名称
|
||||
# if name in processed_names:
|
||||
# error_msgs.append(f"第{count}行: 租户名称 '{name}' 在文件中重复")
|
||||
# continue
|
||||
# processed_names.add(name)
|
||||
|
||||
|
||||
# # 处理编码
|
||||
# code = str(row['code']).strip()
|
||||
# if code in processed_codes:
|
||||
# error_msgs.append(f"第{count}行: 租户编码 '{code}' 在文件中重复")
|
||||
# continue
|
||||
# processed_codes.add(code)
|
||||
|
||||
|
||||
# # 构建租户数据
|
||||
# data = {
|
||||
# "name": name,
|
||||
@@ -389,13 +388,13 @@
|
||||
# "status": status,
|
||||
# "description": str(row['description']).strip(),
|
||||
# }
|
||||
|
||||
|
||||
|
||||
|
||||
# # 检查时间有效性
|
||||
# if 'start_time' in data and 'end_time' in data and data['start_time'] > data['end_time']:
|
||||
# error_msgs.append(f"第{count}行: 开始时间不能晚于结束时间")
|
||||
# continue
|
||||
|
||||
|
||||
# # 处理租户导入
|
||||
# exists_obj = await TenantCRUD(auth).get(name=data["name"])
|
||||
# if exists_obj:
|
||||
@@ -403,7 +402,7 @@
|
||||
# if exists_obj.id == 1:
|
||||
# error_msgs.append(f"第{count}行: 系统租户不允许修改")
|
||||
# continue
|
||||
|
||||
|
||||
# if update_support:
|
||||
# await TenantCRUD(auth).update(id=exists_obj.id, data=data)
|
||||
# success_count += 1
|
||||
@@ -415,17 +414,17 @@
|
||||
# if exists_code:
|
||||
# error_msgs.append(f"第{count}行: 租户编码 '{data['code']}' 已存在")
|
||||
# continue
|
||||
|
||||
|
||||
# # 创建租户
|
||||
# new_tenant = await TenantCRUD(auth).create(data=data)
|
||||
# success_count += 1
|
||||
|
||||
|
||||
# # 自动创建租户管理员(如果导入数量不是特别大)
|
||||
# if success_count < 10: # 限制自动创建管理员的数量
|
||||
# await cls._create_tenant_admin_user(auth, new_tenant)
|
||||
# else:
|
||||
# log.info(f"批量导入超过10个租户,跳过自动创建管理员用户")
|
||||
|
||||
|
||||
# except Exception as e:
|
||||
# error_msgs.append(f"第{count}行: {str(e)}")
|
||||
# continue
|
||||
@@ -436,10 +435,10 @@
|
||||
# result += "\n错误信息:\n" + "\n".join(error_msgs)
|
||||
# # 记录错误详情到日志
|
||||
# log.error(f"租户批量导入错误详情: {error_msgs}")
|
||||
|
||||
|
||||
# log.info(f"租户批量导入完成: 成功{success_count}条, 失败{len(error_msgs)}条")
|
||||
# return result
|
||||
|
||||
|
||||
# except CustomException:
|
||||
# raise
|
||||
# except Exception as e:
|
||||
@@ -450,20 +449,20 @@
|
||||
# async def import_template_download_service(cls) -> bytes:
|
||||
# """
|
||||
# 下载导入模板
|
||||
|
||||
|
||||
# 返回:
|
||||
# - bytes: Excel文件字节流
|
||||
# """
|
||||
# header_list = ['名称', '编码', '状态', '描述', '开始时间', '结束时间']
|
||||
# selector_header_list = ['状态']
|
||||
# selector_header_list = ['状态']
|
||||
# option_list = [{'状态': ['正常', '停用']}]
|
||||
|
||||
|
||||
# # 添加示例数据和说明
|
||||
# sample_data = [
|
||||
# ['测试租户1', 'TEST001', '正常', '这是一个测试租户', '', ''],
|
||||
# ['测试租户2', 'TEST002', '正常', '这是另一个测试租户', '', '']
|
||||
# ]
|
||||
|
||||
|
||||
# # 添加说明文本
|
||||
# description = """导入说明:
|
||||
# 1. 名称和编码为必填项,名称长度2-64个字符
|
||||
@@ -472,9 +471,9 @@
|
||||
# 4. 时间格式:YYYY-MM-DD HH:MM:SS或YYYY-MM-DD
|
||||
# 5. 单次导入最多支持100条数据
|
||||
# """
|
||||
|
||||
|
||||
# return ExcelUtil.get_excel_template(
|
||||
# header_list=header_list,
|
||||
# selector_header_list=selector_header_list,
|
||||
# option_list=option_list
|
||||
# )
|
||||
# )
|
||||
|
||||
Reference in New Issue
Block a user