feat: 新增租户、客户和令牌模块及相关功能

refactor: 重构用户、角色、部门等模块的字段长度和校验逻辑

fix: 修复前端接口类型定义和字段显示问题

style: 优化代码格式和注释

perf: 提升数据库连接性能和查询效率

docs: 更新README和配置文档

test: 添加字段校验和数据库连接测试

chore: 更新依赖包和配置文件
This commit is contained in:
zhangtao
2025-12-21 23:14:02 +08:00
parent 33cf047c93
commit fb592d4f1b
71 changed files with 6274 additions and 209 deletions
+1 -1
View File
@@ -110,7 +110,7 @@ FastapiAdmin
| Type | Technology Stack | Version | | Type | Technology Stack | Version |
|------|------------------|---------| |------|------------------|---------|
| Backend | Python | ≥ 3.10 | | Backend | Python | 3.12 ≥ 3.10 |
| Backend | FastAPI | 0.109+ | | Backend | FastAPI | 0.109+ |
| Frontend | Node.js | ≥ 20.0 | | Frontend | Node.js | ≥ 20.0 |
| Frontend | Vue3 | 3.3+ | | Frontend | Vue3 | 3.3+ |
+1 -1
View File
@@ -110,7 +110,7 @@ FastapiAdmin
| 类型 | 技术栈 | 版本 | | 类型 | 技术栈 | 版本 |
|------|--------|------| |------|--------|------|
| 后端 | Python | ≥ 3.10 | | 后端 | Python | 3.12 ≥ 3.10 |
| 后端 | FastAPI | 0.109+ | | 后端 | FastAPI | 0.109+ |
| 前端 | Node.js | ≥ 20.0 | | 前端 | Node.js | ≥ 20.0 |
| 前端 | Vue3 | 3.3+ | | 前端 | Vue3 | 3.3+ |
@@ -0,0 +1,37 @@
"""迁移脚本
Revision ID: 8767328f6bc3
Revises:
Create Date: 2025-12-21 19:47:11.533199
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '8767328f6bc3'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index('ix_apscheduler_jobs_next_run_time', table_name='apscheduler_jobs')
op.drop_table('apscheduler_jobs')
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('apscheduler_jobs',
sa.Column('id', sa.VARCHAR(length=191), nullable=False),
sa.Column('next_run_time', sa.FLOAT(), nullable=True),
sa.Column('job_state', sa.BLOB(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_apscheduler_jobs_next_run_time', 'apscheduler_jobs', ['next_run_time'], unique=False)
# ### end Alembic commands ###
@@ -48,7 +48,6 @@ class McpQueryParam:
created_id: int | None = Query(None, description="创建人"), created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人"), updated_id: int | None = Query(None, description="更新人"),
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.name = ("like", name) if name else None self.name = ("like", name) if name else None
@@ -126,12 +126,12 @@ class JobLogQueryParam:
"""定时任务查询参数""" """定时任务查询参数"""
def __init__( def __init__(
self, self,
job_id: int | None = Query(None, description="定时任务ID"), job_id: int | None = Query(None, description="定时任务ID"),
job_name: str | None = Query(None, description="任务名称"), job_name: str | None = Query(None, description="任务名称"),
status: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]), updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
) -> None: ) -> None:
# 定时任务ID查询 # 定时任务ID查询
self.job_id = job_id self.job_id = job_id
@@ -63,7 +63,6 @@ class ApplicationQueryParam:
created_id: int | None = Query(None, description="创建人"), created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人"), updated_id: int | None = Query(None, description="更新人"),
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.name = ("like", name) if name else None self.name = ("like", name) if name else None
@@ -13,4 +13,4 @@ async def health_check() -> JSONResponse:
返回: 返回:
- JSONResponse: 包含健康状态的JSON响应 - JSONResponse: 包含健康状态的JSON响应
""" """
return JSONResponse(content={"msg": "Healthy"}, status_code=200) return JSONResponse(content={"msg": True}, status_code=200)
@@ -3,8 +3,9 @@
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from fastapi import Query from fastapi import Query
from app.core.validator import DateTimeStr from app.core.base_params import BaseQueryParam
from app.core.base_schema import BaseSchema, UserBySchema from app.core.base_schema import BaseSchema, UserBySchema
from app.core.validator import DateTimeStr
class DemoCreateSchema(BaseModel): class DemoCreateSchema(BaseModel):
@@ -39,7 +40,6 @@ class DemoCreateSchema(BaseModel):
# 描述校验:描述最大长度 # 描述校验:描述最大长度
if self.description and len(self.description) > 255: if self.description and len(self.description) > 255:
raise ValueError('描述长度不能超过255个字符') raise ValueError('描述长度不能超过255个字符')
return self return self
@@ -55,27 +55,33 @@ class DemoOutSchema(DemoCreateSchema, BaseSchema, UserBySchema):
class DemoQueryParam: class DemoQueryParam:
"""示例查询参数""" """示例查询参数"""
def __init__( def __init__(
self, self,
name: str | None = Query(None, description="名称"), name: str | None = Query(None, description="名称"),
description: str | None = Query(None, description="描述"),
status: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]), updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"), created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人"), updated_id: int | None = Query(None, description="更新人")
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.name = ("like", name) self.name = ("like", name)
if description:
self.description = ("like", description)
# 精确查询字段 # 精确查询字段
self.created_id = created_id if status:
self.updated_id = updated_id self.status = ("eq", status)
self.status = status
# 时间范围查询 # 时间范围查询
if created_time and len(created_time) == 2: if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1])) self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2: if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1])) self.updated_time = ("between", (updated_time[0], updated_time[1]))
# 关联查询字段
if created_id:
self.created_id = ("eq", created_id)
if updated_id:
self.updated_id = ("eq", updated_id)
@@ -119,8 +119,8 @@ export interface {{ class_name }}Table extends BaseType{
}}; }};
{% endif %} {% endif %}
{% endfor %} {% endfor %}
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
// 新增/修改/详情表单参数 // 新增/修改/详情表单参数
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
@@ -0,0 +1,215 @@
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Body, Depends, Path, UploadFile
from fastapi.responses import JSONResponse, StreamingResponse
import urllib.parse
from app.common.response import StreamResponse, SuccessResponse
from app.utils.common_util import bytes2file_response
from app.core.base_params import PaginationQueryParam
from app.core.dependencies import AuthPermission
from app.core.router_class import OperationLogRoute
from app.core.base_schema import BatchSetAvailable
from app.core.logger import log
from app.api.v1.module_system.auth.schema import AuthSchema
from .service import CustomerService
from .schema import (
CustomerCreateSchema,
CustomerUpdateSchema,
CustomerQueryParam
)
CustomerRouter = APIRouter(route_class=OperationLogRoute, prefix="/customer", tags=["客户模块"])
@CustomerRouter.get("/detail/{id}", summary="获取客户详情", description="获取客户详情")
async def get_obj_detail_controller(
id: int = Path(..., description="客户ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:customer:query"]))
) -> JSONResponse:
"""
获取客户详情
参数:
- id (int): 客户ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含客户详情的JSON响应
"""
result_dict = await CustomerService.detail_service(id=id, auth=auth)
log.info(f"获取客户详情成功 {id}")
return SuccessResponse(data=result_dict, msg="获取客户详情成功")
@CustomerRouter.get("/list", summary="查询客户列表", description="查询客户列表")
async def get_obj_list_controller(
page: PaginationQueryParam = Depends(),
search: CustomerQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:customer:query"]))
) -> JSONResponse:
"""
查询客户列表
参数:
- page (PaginationQueryParam): 分页查询参数
- search (CustomerQueryParam): 查询参数
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含客户列表分页信息的JSON响应
"""
# 使用数据库分页而不是应用层分页
result_dict = await CustomerService.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=page.order_by
)
log.info("查询客户列表成功")
return SuccessResponse(data=result_dict, msg="查询客户列表成功")
@CustomerRouter.post("/create", summary="创建客户", description="创建客户")
async def create_obj_controller(
data: CustomerCreateSchema,
auth: AuthSchema = Depends(AuthPermission(["module_system:customer:create"]))
) -> JSONResponse:
"""
创建客户
参数:
- data (CustomerCreateSchema): 客户创建模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含创建客户详情的JSON响应
"""
result_dict = await CustomerService.create_service(auth=auth, data=data)
log.info(f"创建客户成功: {result_dict.get('name')}")
return SuccessResponse(data=result_dict, msg="创建客户成功")
@CustomerRouter.put("/update/{id}", summary="修改客户", description="修改客户")
async def update_obj_controller(
data: CustomerUpdateSchema,
id: int = Path(..., description="客户ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:customer:update"]))
) -> JSONResponse:
"""
修改客户
参数:
- data (CustomerUpdateSchema): 客户更新模型
- id (int): 客户ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含修改客户详情的JSON响应
"""
result_dict = await CustomerService.update_service(auth=auth, id=id, data=data)
log.info(f"修改客户成功: {result_dict.get('name')}")
return SuccessResponse(data=result_dict, msg="修改客户成功")
@CustomerRouter.delete("/delete", summary="删除客户", description="删除客户")
async def delete_obj_controller(
ids: list[int] = Body(..., description="ID列表"),
auth: AuthSchema = Depends(AuthPermission(["module_system:customer:delete"]))
) -> JSONResponse:
"""
删除客户
参数:
- ids (list[int]): 客户ID列表
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含删除客户详情的JSON响应
"""
await CustomerService.delete_service(auth=auth, ids=ids)
log.info(f"删除客户成功: {ids}")
return SuccessResponse(msg="删除客户成功")
@CustomerRouter.patch("/available/setting", summary="批量修改客户状态", description="批量修改客户状态")
async def batch_set_available_obj_controller(
data: BatchSetAvailable,
auth: AuthSchema = Depends(AuthPermission(["module_system:customer:patch"]))
) -> JSONResponse:
"""
批量修改客户状态
参数:
- data (BatchSetAvailable): 批量修改客户状态模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含批量修改客户状态详情的JSON响应
"""
await CustomerService.set_available_service(auth=auth, data=data)
log.info(f"批量修改客户状态成功: {data.ids}")
return SuccessResponse(msg="批量修改客户状态成功")
@CustomerRouter.post('/export', summary="导出客户", description="导出客户")
async def export_obj_list_controller(
search: CustomerQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:customer:export"]))
) -> StreamingResponse:
"""
导出客户
参数:
- search (CustomerQueryParam): 查询参数
- auth (AuthSchema): 认证信息模型
返回:
- StreamingResponse: 包含客户列表的Excel文件流响应
"""
result_dict_list = await CustomerService.list_service(search=search, auth=auth)
export_result = await CustomerService.batch_export_service(obj_list=result_dict_list)
log.info('导出客户成功')
return StreamResponse(
data=bytes2file_response(export_result),
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={
'Content-Disposition': 'attachment; filename=example.xlsx'
}
)
@CustomerRouter.post('/import', summary="导入客户", description="导入客户")
async def import_obj_list_controller(
file: UploadFile,
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:import"]))
) -> JSONResponse:
"""
导入租户
参数:
- file (UploadFile): 导入的Excel文件
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含导入客户详情的JSON响应
"""
batch_import_result = await CustomerService.batch_import_service(file=file, auth=auth, update_support=True)
log.info(f"导入客户成功: {batch_import_result}")
return SuccessResponse(data=batch_import_result, msg="导入租户成功")
@CustomerRouter.post('/download/template', summary="获取客户导入模板", description="获取客户导入模板", dependencies=[Depends(AuthPermission(["module_system:customer:download"]))])
async def export_obj_template_controller() -> StreamingResponse:
"""
获取租户导入模板
返回:
- StreamingResponse: 包含租户导入模板的Excel文件流响应
"""
example_import_template_result = await CustomerService.import_template_download_service()
log.info('获取客户导入模板成功')
return StreamResponse(
data=bytes2file_response(example_import_template_result),
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={
'Content-Disposition': f'attachment; filename={urllib.parse.quote("客户导入模板.xlsx")}',
'Access-Control-Expose-Headers': 'Content-Disposition'
}
)
@@ -0,0 +1,125 @@
# -*- coding: utf-8 -*-
from typing import Dict, List, Optional, Sequence, Union, Any
from app.core.base_crud import CRUDBase
from app.api.v1.module_system.auth.schema import AuthSchema
from .model import CustomerModel
from .schema import CustomerCreateSchema, CustomerUpdateSchema, CustomerOutSchema
class CustomerCRUD(CRUDBase[CustomerModel, CustomerCreateSchema, CustomerUpdateSchema]):
"""客户数据层"""
def __init__(self, auth: AuthSchema) -> None:
"""
初始化CRUD数据层
参数:
- auth (AuthSchema): 认证信息模型
"""
super().__init__(model=CustomerModel, auth=auth)
async def get_by_id_crud(self, id: int, preload: Optional[List[Union[str, Any]]] = None) -> Optional[CustomerModel]:
"""
详情
参数:
- id (int): 客户ID
- preload (Optional[List[Union[str, Any]]]): 预加载关系,未提供时使用模型默认项
返回:
- Optional[CustomerModel]: 客户模型实例或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[CustomerModel]:
"""
列表查询
参数:
- 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: CustomerCreateSchema) -> Optional[CustomerModel]:
"""
创建
参数:
- data (CustomerCreateSchema): 客户创建模型
返回:
- Optional[CustomerModel]: 客户模型实例或None
"""
return await self.create(data=data)
async def update_crud(self, id: int, data: CustomerUpdateSchema) -> Optional[CustomerModel]:
"""
更新
参数:
- id (int): 客户ID
- data (CustomerUpdateSchema): 客户更新模型
返回:
- Optional[CustomerModel]: 客户模型实例或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,
order_by=order_by_list,
search=search_dict,
out_schema=CustomerOutSchema,
preload=preload
)
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship, validates
from app.core.base_model import ModelMixin, UserMixin, TenantMixin
if TYPE_CHECKING:
from app.api.v1.module_system.user.model import UserModel
class CustomerModel(ModelMixin, UserMixin):
"""
客户表
"""
__tablename__: str = 'sys_customer'
__table_args__: dict[str, str] = ({'comment': '客户表'})
__loader_options__: list[str] = ["created_by", "updated_by"]
name: Mapped[str] = mapped_column(String(64), nullable=False, comment='客户名称')
code: Mapped[str] = mapped_column(String(20), nullable=False, index=True, 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
@@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from fastapi import Query
from app.core.base_schema import BaseSchema, UserBySchema, TenantSchema, CustomerSchema
from app.core.validator import DateTimeStr
class CustomerCreateSchema(BaseModel):
"""新增模型"""
name: str = Field(..., description='客户名称')
code: Optional[str] = Field(default=None, description='客户编码')
status: str = Field(default="0", description="是否启用(0:启用 1:禁用)")
description: Optional[str] = Field(default=None, description="描述")
@field_validator('name')
@classmethod
def _validate_name(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError('名称不能为空')
return v
@model_validator(mode='after')
def _after_validation(self):
"""
核心业务规则校验
"""
# 长度校验:名称最小长度
if len(self.name) < 2 or len(self.name) > 64:
raise ValueError('名称长度必须在2-50个字符之间')
# 格式校验:名称只能包含字母、数字、下划线和中划线
if not self.name.isalnum() and not all(c in '-_' for c in self.name):
raise ValueError('名称只能包含字母、数字、下划线和中划线')
return self
class CustomerUpdateSchema(CustomerCreateSchema):
"""更新模型"""
...
class CustomerOutSchema(CustomerCreateSchema, BaseSchema, UserBySchema):
"""响应模型"""
model_config = ConfigDict(from_attributes=True)
class CustomerQueryParam:
"""客户查询参数"""
def __init__(
self,
name: str | None = Query(None, description="名称"),
description: 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"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人")
) -> None:
# 模糊查询字段
self.name = ("like", name)
if description:
self.description = ("like", description)
# 精确查询字段
if status:
self.status = ("eq", status)
# 时间范围查询
if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1]))
# 关联查询字段
if created_id:
self.created_id = ("eq", created_id)
if updated_id:
self.updated_id = ("eq", updated_id)
@@ -0,0 +1,312 @@
# -*- coding: utf-8 -*-
import io
from typing import Any, List, Dict, Optional
from fastapi import UploadFile
import pandas as pd
from app.api.v1.module_system.tenant.crud import TenantCRUD
from app.core.base_schema import BatchSetAvailable
from app.core.exceptions import CustomException
from app.utils.excel_util import ExcelUtil
from app.core.logger import log
from app.api.v1.module_system.auth.schema import AuthSchema
from .schema import CustomerCreateSchema, CustomerUpdateSchema, CustomerOutSchema, CustomerQueryParam
from .crud import CustomerCRUD
class CustomerService:
"""
客户管理模块服务层
"""
@classmethod
async def detail_service(cls, auth: AuthSchema, id: int) -> Dict:
"""
详情
参数:
- auth (AuthSchema): 认证信息模型
- id (int): 客户ID
返回:
- Dict: 客户模型实例字典
"""
obj = await CustomerCRUD(auth).get_by_id_crud(id=id)
if not obj:
raise CustomException(msg="该数据不存在")
return CustomerOutSchema.model_validate(obj).model_dump()
@classmethod
async def list_service(cls, auth: AuthSchema, search: Optional[CustomerQueryParam] = None, order_by: Optional[List[Dict[str, str]]] = None) -> List[Dict]:
"""
列表查询
参数:
- auth (AuthSchema): 认证信息模型
- search (Optional[CustomerQueryParam]): 查询参数
- order_by (Optional[List[Dict[str, str]]]): 排序参数
返回:
- List[Dict]: 客户模型实例字典列表
"""
search_dict = search.__dict__ if search else None
obj_list = await CustomerCRUD(auth).list_crud(search=search_dict, order_by=order_by)
return [CustomerOutSchema.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[CustomerQueryParam] = None, order_by: Optional[List[Dict[str, str]]] = None) -> Dict:
"""
分页查询
参数:
- auth (AuthSchema): 认证信息模型
- page_no (int): 页码
- page_size (int): 每页数量
- search (Optional[CustomerQueryParam]): 查询参数
- 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 CustomerCRUD(auth).page_crud(
offset=offset,
limit=page_size,
order_by=order_by_list,
search=search_dict
)
return result
@classmethod
async def create_service(cls, auth: AuthSchema, data: CustomerCreateSchema) -> Dict:
"""
创建
参数:
- auth (AuthSchema): 认证信息模型
- data (CustomerCreateSchema): 客户创建模型
返回:
- Dict: 客户模型实例字典
"""
obj = await CustomerCRUD(auth).get(name=data.name)
if obj:
raise CustomException(msg='创建失败,名称已存在')
obj = await CustomerCRUD(auth).get(code=data.code)
if obj:
raise CustomException(msg='创建失败,编码已存在')
obj = await CustomerCRUD(auth).create_crud(data=data)
return CustomerOutSchema.model_validate(obj).model_dump()
@classmethod
async def update_service(cls, auth: AuthSchema, id: int, data: CustomerUpdateSchema) -> Dict:
"""
更新
参数:
- auth (AuthSchema): 认证信息模型
- id (int): 客户ID
- data (CustomerUpdateSchema): 客户更新模型
返回:
- Dict: 客户模型实例字典
"""
# 检查数据是否存在
obj = await CustomerCRUD(auth).get_by_id_crud(id=id)
if not obj:
raise CustomException(msg='更新失败,该数据不存在')
# 检查名称是否重复
exist_obj = await CustomerCRUD(auth).get(name=data.name)
if exist_obj and exist_obj.id != id:
raise CustomException(msg='更新失败,名称重复')
obj = await CustomerCRUD(auth).update_crud(id=id, data=data)
return CustomerOutSchema.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='删除失败,删除对象不能为空')
# 检查所有要删除的数据是否存在
for id in ids:
obj = await CustomerCRUD(auth).get_by_id_crud(id=id)
if not obj:
raise CustomException(msg=f'删除失败,ID为{id}的数据不存在')
await CustomerCRUD(auth).delete_crud(ids=ids)
@classmethod
async def set_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
"""
批量设置状态
参数:
- auth (AuthSchema): 认证信息模型
- data (BatchSetAvailable): 批量设置状态模型
返回:
- None
"""
await CustomerCRUD(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': '名称',
'code': '编码',
'status': '状态',
'description': '备注',
'created_time': '创建时间',
'updated_time': '更新时间',
'creator': '创建者',
'code': '编码',
}
# 复制数据并转换状态
data = obj_list.copy()
for item in data:
# 处理状态
item['status'] = '启用' if item.get('status') == '0' else '停用'
# 处理创建者
creator_info = item.get('creator')
if isinstance(creator_info, dict):
item['creator'] = creator_info.get('name', '未知')
else:
item['creator'] = '未知'
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
@classmethod
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',
'状态': 'status',
'描述': 'description'
}
try:
# 读取Excel文件
contents = await file.read()
df = pd.read_excel(io.BytesIO(contents))
await file.close()
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', 'status']
for field in required_fields:
missing_rows = df[df[field].isnull()].index.tolist()
raise CustomException(msg=f"{[k for k,v in header_dict.items() if v == field][0]}不能为空,第{[i+1 for i in missing_rows]}行")
error_msgs = []
success_count = 0
count = 0
# 处理每一行数据
for index, row in df.iterrows():
count += 1
try:
# 数据转换前的类型检查
try:
status = True if row['status'] == '正常' else False
except ValueError:
error_msgs.append(f"第{count}行: 状态必须是'正常'或'停用'")
continue
# 构建用户数据
data = {
"name": str(row['name']),
"status": status,
"description": str(row['description']),
}
# 处理用户导入
exists_obj = await TenantCRUD(auth).get(name=data["name"])
if exists_obj:
if update_support:
await TenantCRUD(auth).update(id=exists_obj.id, data=data)
success_count += 1
else:
error_msgs.append(f"第{count}行: 对象 {data['name']} 已存在")
else:
await TenantCRUD(auth).create(data=data)
success_count += 1
except Exception as e:
error_msgs.append(f"第{count}行: {str(e)}")
continue
# 返回详细的导入结果
result = f"成功导入 {success_count} 条数据"
if error_msgs:
result += "\n错误信息:\n" + "\n".join(error_msgs)
return result
except Exception as e:
log.error(f"批量导入用户失败: {str(e)}")
raise CustomException(msg=f"导入失败: {str(e)}")
@classmethod
async def import_template_download_service(cls) -> bytes:
"""
下载导入模板
返回:
- bytes: Excel文件字节流
"""
header_list = ['名称', '状态', '描述']
selector_header_list = ['状态']
option_list = [{'状态': ['正常', '停用']}]
return ExcelUtil.get_excel_template(
header_list=header_list,
selector_header_list=selector_header_list,
option_list=option_list
)
@@ -18,9 +18,9 @@ class DeptModel(ModelMixin):
__tablename__: str = "sys_dept" __tablename__: str = "sys_dept"
__table_args__: dict[str, str] = ({'comment': '部门表'}) __table_args__: dict[str, str] = ({'comment': '部门表'})
name: Mapped[str] = mapped_column(String(40), nullable=False, comment="部门名称") name: Mapped[str] = mapped_column(String(64), nullable=False, comment="部门名称")
order: Mapped[int] = mapped_column(Integer, nullable=False, default=999, comment="显示排序") order: Mapped[int] = mapped_column(Integer, nullable=False, default=999, comment="显示排序")
code: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True, comment="部门编码") code: Mapped[str | None] = mapped_column(String(16), nullable=True, index=True, comment="部门编码")
leader: Mapped[str | None] = mapped_column(String(32), default=None, comment='部门负责人') leader: Mapped[str | None] = mapped_column(String(32), default=None, comment='部门负责人')
phone: Mapped[str | None] = mapped_column(String(11), default=None, comment='手机') phone: Mapped[str | None] = mapped_column(String(11), default=None, comment='手机')
email: Mapped[str | None] = mapped_column(String(64), default=None, comment='邮箱') email: Mapped[str | None] = mapped_column(String(64), default=None, comment='邮箱')
@@ -9,10 +9,10 @@ from app.core.base_schema import BaseSchema
class DeptCreateSchema(BaseModel): class DeptCreateSchema(BaseModel):
"""部门创建模型""" """部门创建模型"""
name: str = Field(..., max_length=40, description="部门名称") name: str = Field(..., max_length=64, description="部门名称")
order: int = Field(default=1, ge=0, description="显示顺序") order: int = Field(default=1, ge=0, description="显示顺序")
code: str | None = Field(default=None, max_length=60, description="部门编码") code: str | None = Field(default=None, max_length=16, description="部门编码")
leader: str | None = Field(default=None, max_length=20, description="部门负责人") leader: str | None = Field(default=None, max_length=32, description="部门负责人")
phone: str | None = Field(default=None, max_length=11, description="手机") phone: str | None = Field(default=None, max_length=11, description="手机")
email: str | None = Field(default=None, max_length=64, description="邮箱") email: str | None = Field(default=None, max_length=64, description="邮箱")
parent_id: int | None = Field(default=None, ge=0, description="父部门ID") parent_id: int | None = Field(default=None, ge=0, description="父部门ID")
@@ -13,7 +13,7 @@ class DictTypeModel(ModelMixin):
__tablename__: str = "sys_dict_type" __tablename__: str = "sys_dict_type"
__table_args__: dict[str, str] = ({'comment': '字典类型表'}) __table_args__: dict[str, str] = ({'comment': '字典类型表'})
dict_name: Mapped[str] = mapped_column(String(255), nullable=False, comment='字典名称') dict_name: Mapped[str] = mapped_column(String(64), nullable=False, comment='字典名称')
dict_type: Mapped[str] = mapped_column(String(255), nullable=False, unique=True, comment='字典类型') dict_type: Mapped[str] = mapped_column(String(255), nullable=False, unique=True, comment='字典类型')
# 关系定义 # 关系定义
@@ -14,7 +14,7 @@ class DictTypeCreateSchema(BaseModel):
""" """
dict_name: str = Field(..., min_length=1, max_length=64, description='字典名称') dict_name: str = Field(..., min_length=1, max_length=64, description='字典名称')
dict_type: str = Field(..., min_length=1, max_length=100, description='字典类型') dict_type: str = Field(..., min_length=1, max_length=64, description='字典类型')
status: str = Field(default='0', description='状态(0正常 1停用)') status: str = Field(default='0', description='状态(0正常 1停用)')
description: str | None = Field(default=None, max_length=255, description="描述") description: str | None = Field(default=None, max_length=255, description="描述")
+17 -7
View File
@@ -4,8 +4,8 @@ import re
from pydantic import BaseModel, ConfigDict, Field, field_validator from pydantic import BaseModel, ConfigDict, Field, field_validator
from fastapi import Query from fastapi import Query
from app.core.validator import DateTimeStr
from app.core.base_schema import BaseSchema, UserBySchema from app.core.base_schema import BaseSchema, UserBySchema
from app.core.validator import DateTimeStr
class OperationLogCreateSchema(BaseModel): class OperationLogCreateSchema(BaseModel):
@@ -72,26 +72,36 @@ class OperationLogQueryParam:
request_method: str | None = Query(None, description="请求方法"), request_method: str | None = Query(None, description="请求方法"),
request_ip: str | None = Query(None, description="请求IP"), request_ip: str | None = Query(None, description="请求IP"),
response_code: int | None = Query(None, description="响应状态码"), response_code: int | None = Query(None, description="响应状态码"),
description: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]), updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"), created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人"), updated_id: int | None = Query(None, description="更新人")
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.request_path = ("like", f"%{request_path}%") if request_path else None self.request_path = ("like", f"%{request_path}%") if request_path else None
# 精确查询字段 # 精确查询字段
self.created_id = created_id
self.updated_id = updated_id
self.request_method = request_method self.request_method = request_method
self.request_ip = request_ip self.request_ip = request_ip
self.response_code = response_code self.response_code = response_code
self.type = type self.type = type
# 模糊查询字段
if description:
self.description = ("like", description)
# 时间范围查询 - 增加对单个时间参数的处理 # 精确查询字段
if status:
self.status = ("eq", status)
# 时间范围查询
if created_time and len(created_time) == 2: if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1])) self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2: if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1])) self.updated_time = ("between", (updated_time[0], updated_time[1]))
# 关联查询字段
if created_id:
self.created_id = ("eq", created_id)
if updated_id:
self.updated_id = ("eq", updated_id)
@@ -4,8 +4,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator from pydantic import BaseModel, ConfigDict, Field, model_validator
from fastapi import Query from fastapi import Query
from app.core.validator import DateTimeStr from app.core.validator import DateTimeStr, menu_request_validator
from app.core.validator import menu_request_validator
from app.core.base_schema import BaseSchema from app.core.base_schema import BaseSchema
@@ -83,20 +82,36 @@ class MenuQueryParam:
component_path: str | None = Query(None, description="组件路径"), component_path: str | None = Query(None, description="组件路径"),
type: Literal[1,2,3,4] | None = Query(None, description="菜单类型(1:目录 2:菜单 3:按钮 4:外链)"), type: Literal[1,2,3,4] | None = Query(None, description="菜单类型(1:目录 2:菜单 3:按钮 4:外链)"),
permission: str | None = Query(None, description="权限标识"), permission: str | None = Query(None, description="权限标识"),
status: str | None = Query(None, description="菜单状态(0:启用 1:禁用)"), description: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人")
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.name = ("like", name) self.name = ("like", name)
self.route_path = ("like", route_path) self.route_path = ("like", route_path)
self.component_path = ("like", component_path) self.component_path = ("like", component_path)
self.permission = ("like", permission) self.permission = ("like", permission)
# 精确查询字段 # 精确查询字段
self.type = type self.type = type
self.status = status # 模糊查询字段
if description:
self.description = ("like", description)
# 精确查询字段
if status:
self.status = ("eq", status)
# 时间范围查询 # 时间范围查询
if created_time and len(created_time) == 2: if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1])) self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1]))
# 关联查询字段
if created_id:
self.created_id = ("eq", created_id)
if updated_id:
self.updated_id = ("eq", updated_id)
@@ -14,6 +14,6 @@ class NoticeModel(ModelMixin, UserMixin):
__table_args__: dict[str, str] = ({'comment': '通知公告表'}) __table_args__: dict[str, str] = ({'comment': '通知公告表'})
__loader_options__: list[str] = ["created_by", "updated_by"] __loader_options__: list[str] = ["created_by", "updated_by"]
notice_title: Mapped[str] = mapped_column(String(50), nullable=False, comment='公告标题') notice_title: Mapped[str] = mapped_column(String(64), nullable=False, comment='公告标题')
notice_type: Mapped[str] = mapped_column(String(50), nullable=False, comment='公告类型(1通知 2公告)') notice_type: Mapped[str] = mapped_column(String(1), nullable=False, comment='公告类型(1通知 2公告)')
notice_content: Mapped[str | None] = mapped_column(Text, nullable=True, comment='公告内容') notice_content: Mapped[str | None] = mapped_column(Text, nullable=True, comment='公告内容')
@@ -3,8 +3,8 @@
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from fastapi import Query from fastapi import Query
from app.core.validator import DateTimeStr
from app.core.base_schema import BaseSchema, UserBySchema from app.core.base_schema import BaseSchema, UserBySchema
from app.core.validator import DateTimeStr
class NoticeCreateSchema(BaseModel): class NoticeCreateSchema(BaseModel):
@@ -48,21 +48,24 @@ class NoticeQueryParam:
self, self,
notice_title: str | None = Query(None, description="公告标题"), notice_title: str | None = Query(None, description="公告标题"),
notice_type: str | None = Query(None, description="公告类型"), notice_type: str | None = Query(None, description="公告类型"),
status: str | None = Query(None, description="是否可用"), description: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]), updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"), created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人"), updated_id: int | None = Query(None, description="更新人")
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.notice_title = ("like", notice_title) self.notice_title = ("like", notice_title)
# 精确查询字段
self.notice_type = notice_type
# 模糊查询字段
if description:
self.description = ("like", description)
# 精确查询字段 # 精确查询字段
self.created_id = created_id if status:
self.updated_id = updated_id self.status = ("eq", status)
self.status = status
self.notice_type = notice_type
# 时间范围查询 # 时间范围查询
if created_time and len(created_time) == 2: if created_time and len(created_time) == 2:
@@ -70,3 +73,9 @@ class NoticeQueryParam:
if updated_time and len(updated_time) == 2: if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1])) self.updated_time = ("between", (updated_time[0], updated_time[1]))
# 关联查询字段
if created_id:
self.created_id = ("eq", created_id)
if updated_id:
self.updated_id = ("eq", updated_id)
@@ -13,7 +13,7 @@ class ParamsModel(ModelMixin):
__tablename__: str = "sys_param" __tablename__: str = "sys_param"
__table_args__: dict[str, str] = ({'comment': '系统参数表'}) __table_args__: dict[str, str] = ({'comment': '系统参数表'})
config_name: Mapped[str] = mapped_column(String(500), nullable=False, comment='参数名称') config_name: Mapped[str] = mapped_column(String(64), nullable=False, comment='参数名称')
config_key: Mapped[str] = mapped_column(String(500), nullable=False, comment='参数键名') config_key: Mapped[str] = mapped_column(String(500), nullable=False, comment='参数键名')
config_value: Mapped[str | None] = mapped_column(String(500), comment='参数键值') config_value: Mapped[str | None] = mapped_column(String(500), comment='参数键值')
config_type: Mapped[bool] = mapped_column(Boolean, default=False, nullable=True, comment="系统内置(True:是 False:否)") config_type: Mapped[bool] = mapped_column(Boolean, default=False, nullable=True, comment="系统内置(True:是 False:否)")
@@ -3,8 +3,8 @@
from pydantic import BaseModel, ConfigDict, Field, field_validator from pydantic import BaseModel, ConfigDict, Field, field_validator
from fastapi import Query from fastapi import Query
from app.core.validator import DateTimeStr
from app.core.base_schema import BaseSchema from app.core.base_schema import BaseSchema
from app.core.validator import DateTimeStr
class ParamsCreateSchema(BaseModel): class ParamsCreateSchema(BaseModel):
@@ -44,16 +44,23 @@ class ParamsQueryParam:
config_name: str | None = Query(None, description="配置名称"), config_name: str | None = Query(None, description="配置名称"),
config_key: str | None = Query(None, description="配置键名"), config_key: str | None = Query(None, description="配置键名"),
config_type: bool | None = Query(None, description="系统内置((True:是 False:否))"), config_type: bool | None = Query(None, description="系统内置((True:是 False:否))"),
description: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]), updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"])
) -> None: ) -> None:
# 模糊查询字段
# 模糊查询字段 # 模糊查询字段
self.config_name = ("like", config_name) self.config_name = ("like", config_name)
self.config_key = ("like", config_key) self.config_key = ("like", config_key)
# 精确查询字段 # 精确查询字段
self.config_type = config_type self.config_type = config_type
if description:
self.description = ("like", description)
# 精确查询字段
if status:
self.status = ("eq", status)
# 时间范围查询 # 时间范围查询
if created_time and len(created_time) == 2: if created_time and len(created_time) == 2:
@@ -19,7 +19,7 @@ class PositionModel(ModelMixin, UserMixin):
__table_args__: dict[str, str] = ({'comment': '岗位表'}) __table_args__: dict[str, str] = ({'comment': '岗位表'})
__loader_options__: list[str] = ["users", "created_by", "updated_by"] __loader_options__: list[str] = ["users", "created_by", "updated_by"]
name: Mapped[str] = mapped_column(String(40), nullable=False, comment="岗位名称") name: Mapped[str] = mapped_column(String(64), nullable=False, comment="岗位名称")
order: Mapped[int] = mapped_column(Integer, nullable=False, default=1, comment="显示排序") order: Mapped[int] = mapped_column(Integer, nullable=False, default=1, comment="显示排序")
# 关联关系 # 关联关系
@@ -41,20 +41,21 @@ class PositionQueryParam:
def __init__( def __init__(
self, self,
name: Optional[str] = Query(None, description="岗位名称"), name: Optional[str] = Query(None, description="岗位名称"),
status: Optional[str] = Query(None, description="是否可用"), description: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]), updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"), created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人"), updated_id: int | None = Query(None, description="更新人")
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.name = ("like", name) self.name = ("like", name)
if description:
self.description = ("like", description)
# 精确查询字段 # 精确查询字段
self.created_id = created_id if status:
self.updated_id = updated_id self.status = ("eq", status)
self.status = status
# 时间范围查询 # 时间范围查询
if created_time and len(created_time) == 2: if created_time and len(created_time) == 2:
@@ -62,3 +63,8 @@ class PositionQueryParam:
if updated_time and len(updated_time) == 2: if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1])) self.updated_time = ("between", (updated_time[0], updated_time[1]))
# 关联查询字段
if created_id:
self.created_id = ("eq", created_id)
if updated_id:
self.updated_id = ("eq", updated_id)
@@ -4,7 +4,7 @@ from typing import TYPE_CHECKING
from sqlalchemy import String, Integer, ForeignKey from sqlalchemy import String, Integer, ForeignKey
from sqlalchemy.orm import relationship, Mapped, mapped_column from sqlalchemy.orm import relationship, Mapped, mapped_column
from app.core.base_model import MappedBase, ModelMixin, UserMixin from app.core.base_model import MappedBase, ModelMixin
if TYPE_CHECKING: if TYPE_CHECKING:
from app.api.v1.module_system.menu.model import MenuModel from app.api.v1.module_system.menu.model import MenuModel
@@ -67,8 +67,8 @@ class RoleModel(ModelMixin):
__table_args__: dict[str, str] = ({'comment': '角色表'}) __table_args__: dict[str, str] = ({'comment': '角色表'})
__loader_options__: list[str] = ["menus", "depts"] __loader_options__: list[str] = ["menus", "depts"]
name: Mapped[str] = mapped_column(String(40), nullable=False, comment="角色名称") name: Mapped[str] = mapped_column(String(64), nullable=False, comment="角色名称")
code: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True, comment="角色编码") code: Mapped[str | None] = mapped_column(String(16), nullable=True, index=True, comment="角色编码")
order: Mapped[int] = mapped_column(Integer, nullable=False, default=999, comment="显示排序") order: Mapped[int] = mapped_column(Integer, nullable=False, default=999, comment="显示排序")
data_scope: Mapped[int] = mapped_column(Integer, default=1, nullable=False, comment="数据权限范围(1:仅本人 2:本部门 3:本部门及以下 4:全部 5:自定义)") data_scope: Mapped[int] = mapped_column(Integer, default=1, nullable=False, comment="数据权限范围(1:仅本人 2:本部门 3:本部门及以下 4:全部 5:自定义)")
+11 -17
View File
@@ -3,9 +3,8 @@
from fastapi import Query from fastapi import Query
from pydantic import BaseModel, ConfigDict, Field, model_validator, field_validator from pydantic import BaseModel, ConfigDict, Field, model_validator, field_validator
from app.core.validator import DateTimeStr
from app.core.base_schema import BaseSchema from app.core.base_schema import BaseSchema
from app.core.validator import role_permission_request_validator from app.core.validator import DateTimeStr, code_validator, role_permission_request_validator
from ..dept.schema import DeptOutSchema from ..dept.schema import DeptOutSchema
from ..menu.schema import MenuOutSchema from ..menu.schema import MenuOutSchema
@@ -13,8 +12,8 @@ from ..menu.schema import MenuOutSchema
class RoleCreateSchema(BaseModel): class RoleCreateSchema(BaseModel):
"""角色创建模型""" """角色创建模型"""
name: str = Field(..., max_length=40, description="角色名称") name: str = Field(..., max_length=64, description="角色名称")
code: str | None = Field(default=None, max_length=40, description="角色编码") code: str | None = Field(default=None, max_length=16, description="角色编码")
order: int | None = Field(default=1, ge=1, description='显示排序') order: int | None = Field(default=1, ge=1, description='显示排序')
data_scope: int | None = Field(default=1, description='数据权限范围(1:仅本人 2:本部门 3:本部门及以下 4:全部 5:自定义)') data_scope: int | None = Field(default=1, description='数据权限范围(1:仅本人 2:本部门 3:本部门及以下 4:全部 5:自定义)')
status: str = Field(default="0", description="是否启用") status: str = Field(default="0", description="是否启用")
@@ -23,13 +22,7 @@ class RoleCreateSchema(BaseModel):
@field_validator("code") @field_validator("code")
@classmethod @classmethod
def validate_code(cls, value: str | None): def validate_code(cls, value: str | None):
if value is None: return code_validator(value)
return value
import re
v = value.strip()
if not re.match(r"^[A-Za-z][A-Za-z0-9_]{1,39}$", v):
raise ValueError("角色编码需字母开头,允许字母/数字/下划线,长度2-40")
return v
class RolePermissionSettingSchema(BaseModel): class RolePermissionSettingSchema(BaseModel):
@@ -64,21 +57,22 @@ class RoleQueryParam:
def __init__( def __init__(
self, self,
name: str | None = Query(None, description="角色名称"), name: str | None = Query(None, description="角色名称"),
status: str | None = Query(None, description="是否可用"), description: 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"]), created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]), updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"])
) -> None: ) -> None:
# 模糊查询字段 # 模糊查询字段
self.name = ("like", name) self.name = ("like", name)
if description:
self.description = ("like", description)
# 精确查询字段 # 精确查询字段
self.status = status if status:
self.status = ("eq", status)
# 时间范围查询 # 时间范围查询
if created_time and len(created_time) == 2: if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1])) self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2: if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1])) self.updated_time = ("between", (updated_time[0], updated_time[1]))
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
@@ -0,0 +1,215 @@
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Body, Depends, Path, UploadFile
from fastapi.responses import JSONResponse, StreamingResponse
import urllib.parse
from app.common.response import StreamResponse, SuccessResponse
from app.utils.common_util import bytes2file_response
from app.core.base_params import PaginationQueryParam
from app.core.dependencies import AuthPermission
from app.core.router_class import OperationLogRoute
from app.core.base_schema import BatchSetAvailable
from app.core.logger import log
from app.api.v1.module_system.auth.schema import AuthSchema
from .service import TenantService
from .schema import (
TenantCreateSchema,
TenantUpdateSchema,
TenantQueryParam
)
TenantRouter = APIRouter(route_class=OperationLogRoute, prefix="/tenant", tags=["租户模块"])
@TenantRouter.get("/detail/{id}", summary="获取租户详情", description="获取租户详情")
async def get_obj_detail_controller(
id: int = Path(..., description="租户ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:query"]))
) -> JSONResponse:
"""
获取租户详情
参数:
- id (int): 租户ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含租户详情的JSON响应
"""
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="查询租户列表")
async def get_obj_list_controller(
page: PaginationQueryParam = Depends(),
search: TenantQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:query"]))
) -> 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,
order_by=page.order_by
)
log.info("查询租户列表成功")
return SuccessResponse(data=result_dict, msg="查询租户列表成功")
@TenantRouter.post("/create", summary="创建租户", description="创建租户")
async def create_obj_controller(
data: TenantCreateSchema,
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:create"]))
) -> JSONResponse:
"""
创建租户
参数:
- data (TenantCreateSchema): 租户创建模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含创建租户详情的JSON响应
"""
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="修改租户")
async def update_obj_controller(
data: TenantUpdateSchema,
id: int = Path(..., description="租户ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:update"]))
) -> JSONResponse:
"""
修改租户
参数:
- data (TenantUpdateSchema): 租户更新模型
- id (int): 租户ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含修改租户详情的JSON响应
"""
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: list[int] = Body(..., description="ID列表"),
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:delete"]))
) -> JSONResponse:
"""
删除租户
参数:
- ids (list[int]): 租户ID列表
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含删除租户详情的JSON响应
"""
await TenantService.delete_service(auth=auth, ids=ids)
log.info(f"删除租户成功: {ids}")
return SuccessResponse(msg="删除租户成功")
@TenantRouter.patch("/available/setting", summary="批量修改租户状态", description="批量修改租户状态")
async def batch_set_available_obj_controller(
data: BatchSetAvailable,
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:patch"]))
) -> JSONResponse:
"""
批量修改租户状态
参数:
- data (BatchSetAvailable): 批量修改租户状态模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含批量修改租户状态详情的JSON响应
"""
await TenantService.set_available_service(auth=auth, data=data)
log.info(f"批量修改租户状态成功: {data.ids}")
return SuccessResponse(msg="批量修改租户状态成功")
@TenantRouter.post('/export', summary="导出租户", description="导出租户")
async def export_obj_list_controller(
search: TenantQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:export"]))
) -> StreamingResponse:
"""
导出租户
参数:
- search (TenantQueryParam): 查询参数
- auth (AuthSchema): 认证信息模型
返回:
- StreamingResponse: 包含租户列表的Excel文件流响应
"""
result_dict_list = await TenantService.list_service(search=search, auth=auth)
export_result = await TenantService.batch_export_service(obj_list=result_dict_list)
log.info('导出租户成功')
return StreamResponse(
data=bytes2file_response(export_result),
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={
'Content-Disposition': 'attachment; filename=example.xlsx'
}
)
@TenantRouter.post('/import', summary="导入租户", description="导入租户")
async def import_obj_list_controller(
file: UploadFile,
auth: AuthSchema = Depends(AuthPermission(["module_system:tenant:import"]))
) -> JSONResponse:
"""
导入租户
参数:
- file (UploadFile): 导入的Excel文件
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含导入租户详情的JSON响应
"""
batch_import_result = await TenantService.batch_import_service(file=file, auth=auth, update_support=True)
log.info(f"导入租户成功: {batch_import_result}")
return SuccessResponse(data=batch_import_result, msg="导入租户成功")
@TenantRouter.post('/download/template', summary="获取租户导入模板", description="获取租户导入模板", dependencies=[Depends(AuthPermission(["module_system:tenant:download"]))])
async def export_obj_template_controller() -> StreamingResponse:
"""
获取租户导入模板
返回:
- StreamingResponse: 包含租户导入模板的Excel文件流响应
"""
example_import_template_result = await TenantService.import_template_download_service()
log.info('获取租户导入模板成功')
return StreamResponse(
data=bytes2file_response(example_import_template_result),
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={
'Content-Disposition': f'attachment; filename={urllib.parse.quote("租户导入模板.xlsx")}',
'Access-Control-Expose-Headers': 'Content-Disposition'
}
)
@@ -0,0 +1,125 @@
# -*- coding: utf-8 -*-
from typing import Dict, List, Optional, Sequence, Union, Any
from app.core.base_crud import CRUDBase
from app.api.v1.module_system.auth.schema import AuthSchema
from .model import TenantModel
from .schema import TenantCreateSchema, TenantUpdateSchema, TenantOutSchema
class TenantCRUD(CRUDBase[TenantModel, TenantCreateSchema, TenantUpdateSchema]):
"""租户数据层"""
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,
order_by=order_by_list,
search=search_dict,
out_schema=TenantOutSchema,
preload=preload
)
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, validates
from app.core.base_model import ModelMixin
class TenantModel(ModelMixin):
"""
租户模型
"""
__tablename__: str = 'sys_tenant'
__table_args__: dict[str, str] = {'comment': '租户表'}
name: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, comment='租户名称')
code: Mapped[str] = mapped_column(String(20), nullable=False, unique=True, 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
@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
from typing import Optional
from fastapi import Query
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from app.core.base_schema import BaseSchema
from app.core.validator import DateTimeStr
class TenantCreateSchema(BaseModel):
"""新增模型"""
name: str = Field(..., description='租户名称')
code: Optional[str] = Field(default=None, description='租户编码')
status: str = Field(default="0", description="是否启用(0:启用 1:禁用)")
description: Optional[str] = Field(default=None, description="描述")
@field_validator('name')
@classmethod
def _validate_name(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError('名称不能为空')
return v
@model_validator(mode='after')
def _after_validation(self):
"""
核心业务规则校验
"""
# 长度校验:名称最小长度
if len(self.name) < 2 or len(self.name) > 64:
raise ValueError('名称长度必须在2-50个字符之间')
# 格式校验:名称只能包含字母、数字、下划线和中划线
if not self.name.isalnum() and not all(c in '-_' for c in self.name):
raise ValueError('名称只能包含字母、数字、下划线和中划线')
return self
class TenantUpdateSchema(TenantCreateSchema):
"""更新模型"""
...
class TenantOutSchema(TenantCreateSchema, BaseSchema):
"""响应模型"""
model_config = ConfigDict(from_attributes=True)
class TenantQueryParam:
"""租户查询参数"""
def __init__(
self,
name: str | None = Query(None, description="名称"),
description: 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"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人")
) -> None:
# 模糊查询字段
self.name = ("like", name)
if description:
self.description = ("like", description)
# 精确查询字段
if status:
self.status = ("eq", status)
# 时间范围查询
if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1]))
@@ -0,0 +1,479 @@
# -*- coding: utf-8 -*-
import io
import random
import string
from typing import Any, List, Dict, Optional
from fastapi import UploadFile
import pandas as pd
from app.core.base_schema import BatchSetAvailable
from app.core.exceptions import CustomException
from app.utils.excel_util import ExcelUtil
from app.core.logger import log
from app.utils.hash_bcrpy_util import PwdUtil
from app.api.v1.module_system.auth.schema import AuthSchema
from app.api.v1.module_system.user.crud import UserCRUD
from .schema import TenantCreateSchema, TenantUpdateSchema, TenantOutSchema, TenantQueryParam
from .crud import TenantCRUD
class TenantService:
"""
租户管理模块服务层
"""
@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,
order_by=order_by_list,
search=search_dict
)
return result
@classmethod
async def create_service(cls, auth: AuthSchema, data: TenantCreateSchema) -> Dict:
"""
创建
参数:
- auth (AuthSchema): 认证信息模型
- data (TenantCreateSchema): 租户创建模型
返回:
- Dict: 租户模型实例字典
"""
obj = await TenantCRUD(auth).get(name=data.name)
if obj:
raise CustomException(msg='创建失败,名称已存在')
obj = await TenantCRUD(auth).get(code=data.code)
if obj:
raise CustomException(msg='创建失败,编码已存在')
# 创建租户
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,
"password": PwdUtil.set_password_hash(password=password),
"name": f"{tenant_obj.name}管理员",
"tenant_id": tenant_obj.id,
"user_type": "1", # 租户管理员类型
"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: 租户模型实例字典
"""
# 系统租户特殊处理
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': '名称',
'code': '编码',
'status': '状态',
'description': '备注',
'start_time': '开始时间',
'end_time': '结束时间',
'created_time': '创建时间',
'updated_time': '更新时间',
'created_id': '创建者',
}
# 复制数据并转换状态
data = obj_list.copy()
for item in data:
# 系统租户特殊标记
if item.get('id') == 1:
item['name'] = f"{item.get('name')} [系统租户]"
# 处理状态
item['status'] = '启用' if item.get('status') == '0' 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:
data = data[:max_export_count]
log.warning(f'导出数据超过{max_export_count}条限制,仅导出前{max_export_count}条')
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
@classmethod
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',
'状态': 'status',
'描述': 'description',
'开始时间': 'start_time',
'结束时间': 'end_time'
}
try:
# 读取Excel文件
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:
missing_rows = df[df[field].isnull()].index.tolist()
if missing_rows:
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
try:
# 数据转换前的类型检查
try:
status = True if str(row['status']).strip() == '正常' else False
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,
"code": code,
"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:
# 系统租户保护
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
else:
error_msgs.append(f"第{count}行: 租户 {data['name']} 已存在")
else:
# 检查编码是否已存在
exists_code = await TenantCRUD(auth).get(code=data["code"])
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
# 返回详细的导入结果
result = f"成功导入 {success_count} 条数据"
if error_msgs:
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:
log.error(f"批量导入租户失败: {str(e)}")
raise CustomException(msg=f"导入失败: {str(e)}")
@classmethod
async def import_template_download_service(cls) -> bytes:
"""
下载导入模板
返回:
- bytes: Excel文件字节流
"""
header_list = ['名称', '编码', '状态', '描述', '开始时间', '结束时间']
selector_header_list = ['状态']
option_list = [{'状态': ['正常', '停用']}]
# 添加示例数据和说明
sample_data = [
['测试租户1', 'TEST001', '正常', '这是一个测试租户', '', ''],
['测试租户2', 'TEST002', '正常', '这是另一个测试租户', '', '']
]
# 添加说明文本
description = """导入说明:
1. 名称和编码为必填项,名称长度2-64个字符
2. 编码如果不填写,系统会自动生成
3. 状态只能选择'正常'或'停用'
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
)
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
@@ -0,0 +1,148 @@
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Body, Depends, Path, UploadFile
from fastapi.responses import JSONResponse, StreamingResponse
import urllib.parse
from app.common.response import StreamResponse, SuccessResponse
from app.core.router_class import OperationLogRoute
from app.utils.common_util import bytes2file_response
from app.core.base_params import PaginationQueryParam
from app.core.dependencies import AuthPermission
from app.core.base_schema import BatchSetAvailable
from app.core.logger import log
from app.api.v1.module_system.auth.schema import AuthSchema
from .service import TokenService
from .schema import (
TokenCreateSchema,
TokenUpdateSchema,
TokenQueryParam
)
TokenRouter = APIRouter(route_class=OperationLogRoute, prefix="/token", tags=["令牌模块"])
@TokenRouter.get("/detail/{id}", summary="获取令牌详情", description="获取令牌详情")
async def get_obj_detail_controller(
id: int = Path(..., description="令牌ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:demo:query"]))
) -> JSONResponse:
"""
获取示例详情
参数:
- id (int): 示例ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含示例详情的JSON响应
"""
result_dict = await TokenService.detail_service(id=id, auth=auth)
log.info(f"获取令牌详情成功 {id}")
return SuccessResponse(data=result_dict, msg="获取令牌详情成功")
@TokenRouter.get("/list", summary="查询令牌列表", description="查询令牌列表")
async def get_obj_list_controller(
page: PaginationQueryParam = Depends(),
search: TokenQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:token:query"]))
) -> JSONResponse:
"""
查询令牌列表
参数:
- page (PaginationQueryParam): 分页查询参数
- search (TokenQueryParam): 查询参数
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含令牌列表分页信息的JSON响应
"""
# 使用数据库分页而不是应用层分页
result_dict = await TokenService.page_service(
auth=auth,
page_no=page.page_no,
page_size=page.page_size,
search=search,
order_by=page.order_by
)
log.info("查询令牌列表成功")
return SuccessResponse(data=result_dict, msg="查询令牌列表成功")
@TokenRouter.post("/create", summary="创建令牌", description="创建令牌")
async def create_obj_controller(
data: TokenCreateSchema,
auth: AuthSchema = Depends(AuthPermission(["module_system:token:create"]))
) -> JSONResponse:
"""
创建令牌
参数:
- data (TokenCreateSchema): 令牌创建模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含创建令牌详情的JSON响应
"""
result_dict = await TokenService.create_service(auth=auth, data=data)
log.info(f"创建令牌成功: {result_dict.get('name')}")
return SuccessResponse(data=result_dict, msg="创建令牌成功")
@TokenRouter.put("/update/{id}", summary="修改令牌", description="修改令牌")
async def update_obj_controller(
data: TokenUpdateSchema,
id: int = Path(..., description="令牌ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:token:update"]))
) -> JSONResponse:
"""
修改令牌
参数:
- data (TokenUpdateSchema): 令牌更新模型
- id (int): 令牌ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含修改令牌详情的JSON响应
"""
result_dict = await TokenService.update_service(auth=auth, id=id, data=data)
log.info(f"修改令牌成功: {result_dict.get('name')}")
return SuccessResponse(data=result_dict, msg="修改令牌成功")
@TokenRouter.delete("/delete", summary="删除令牌", description="删除令牌")
async def delete_obj_controller(
ids: list[int] = Body(..., description="ID列表"),
auth: AuthSchema = Depends(AuthPermission(["module_system:token:delete"]))
) -> JSONResponse:
"""
删除令牌
参数:
- ids (list[int]): 令牌ID列表
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含删除令牌详情的JSON响应
"""
await TokenService.delete_service(auth=auth, ids=ids)
log.info(f"删除令牌成功: {ids}")
return SuccessResponse(msg="删除令牌成功")
@TokenRouter.patch("/available/setting", summary="批量修改令牌状态", description="批量修改令牌状态")
async def batch_set_available_obj_controller(
data: BatchSetAvailable,
auth: AuthSchema = Depends(AuthPermission(["module_system:token:patch"]))
) -> JSONResponse:
"""
批量修改令牌状态
参数:
- data (BatchSetAvailable): 批量修改令牌状态模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含批量修改令牌状态详情的JSON响应
"""
await TokenService.set_available_service(auth=auth, data=data)
log.info(f"批量修改令牌状态成功: {data.ids}")
return SuccessResponse(msg="批量修改令牌状态成功")
@@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
from collections.abc import Sequence
from app.core.base_crud import CRUDBase
from app.api.v1.module_system.auth.schema import AuthSchema
from .model import TokenModel
from .schema import TokenCreateSchema, TokenUpdateSchema, TokenOutSchema
class TokenCRUD(CRUDBase[TokenModel, TokenCreateSchema, TokenUpdateSchema]):
"""令牌数据层"""
def __init__(self, auth: AuthSchema) -> None:
"""
初始化CRUD数据层
参数:
- auth (AuthSchema): 认证信息模型
"""
super().__init__(model=TokenModel, auth=auth)
async def get_by_id_crud(self, id: int, preload: list[str] | None = None) -> TokenModel | None:
"""
详情
参数:
- id (int): 令牌ID
- preload (list[str] | None): 预加载关系,未提供时使用模型默认项
返回:
- TokenModel | None: 令牌模型实例或None
"""
return await self.get(id=id, preload=preload)
async def list_crud(self, search: dict | None = None, order_by: list[dict] | None = None, preload: list[str] | None = None) -> Sequence[TokenModel]:
"""
列表查询
参数:
- search (dict | None): 查询参数
- order_by (list[dict] | None): 排序参数
- preload (list[str] | None): 预加载关系,未提供时使用模型默认项
返回:
- Sequence[DemoModel]: 示例模型实例序列
"""
return await self.list(search=search, order_by=order_by, preload=preload)
async def create_crud(self, data: TokenCreateSchema) -> TokenModel | None:
"""
创建
参数:
- data (TokenCreateSchema): 令牌创建模型
返回:
- TokenModel | None: 令牌模型实例或None
"""
return await self.create(data=data)
async def update_crud(self, id: int, data: TokenUpdateSchema) -> TokenModel | None:
"""
更新
参数:
- id (int): 令牌ID
- data (TokenUpdateSchema): 令牌更新模型
返回:
- TokenModel | None: 令牌模型实例或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 (str): 可用状态
返回:
- None
"""
return await self.set(ids=ids, status=status)
async def page_crud(self, offset: int, limit: int, order_by: list[dict] | None = None, search: dict | None = None, preload: list | None = None) -> dict:
"""
分页查询
参数:
- offset (int): 偏移量
- limit (int): 每页数量
- order_by (list[dict] | None): 排序参数
- search (dict | None): 查询参数
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- dict: 分页数据
"""
order_by_list = order_by or [{'id': 'asc'}]
search_dict = search or {}
return await self.page(
offset=offset,
limit=limit,
order_by=order_by_list,
search=search_dict,
out_schema=TokenOutSchema,
preload=preload
)
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
from app.core.base_model import ModelMixin, UserMixin
class TokenModel(ModelMixin, UserMixin):
"""
令牌表
"""
__tablename__: str = 'sys_token'
__table_args__: dict[str, str] = ({'comment': '令牌表'})
__loader_options__: list[str] = ["created_by", "updated_by"]
name: Mapped[str | None] = mapped_column(String(64), nullable=True, default='', comment='名称')
@@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from fastapi import Query
from app.core.base_schema import BaseSchema, UserBySchema
from app.core.validator import DateTimeStr
class TokenCreateSchema(BaseModel):
"""新增模型"""
name: str = Field(..., description='名称')
status: str = Field(default="0", description="是否启用(0:启用 1:禁用)")
description: str | None = Field(default=None, description="描述")
@field_validator('name')
@classmethod
def validate_name(cls, v: str) -> str:
"""验证名称字段的格式和内容"""
# 去除首尾空格
v = v.strip()
if not v:
raise ValueError('名称不能为空')
return v
@model_validator(mode='after')
def _after_validation(self):
"""
核心业务规则校验
"""
# 长度校验:名称最小长度
if len(self.name) < 2 or len(self.name) > 50:
raise ValueError('名称长度必须在2-50个字符之间')
# 格式校验:名称只能包含字母、数字、下划线和中划线
if not self.name.isalnum() and not all(c in '-_' for c in self.name):
raise ValueError('名称只能包含字母、数字、下划线和中划线')
if self.status not in ["0", "1"]:
raise ValueError('是否启用必须为0或1')
# 描述校验:描述最大长度
if self.description and len(self.description) > 255:
raise ValueError('描述长度不能超过255个字符')
return self
class TokenUpdateSchema(TokenCreateSchema):
"""更新模型"""
...
class TokenOutSchema(TokenCreateSchema, BaseSchema, UserBySchema):
"""响应模型"""
model_config = ConfigDict(from_attributes=True)
class TokenQueryParam:
"""令牌查询参数"""
def __init__(
self,
name: str | None = Query(None, description="名称"),
description: 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"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人")
) -> None:
# 模糊查询字段
self.name = ("like", name)
if description:
self.description = ("like", description)
# 精确查询字段
if status:
self.status = ("eq", status)
# 时间范围查询
if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1]))
@@ -0,0 +1,312 @@
# -*- coding: utf-8 -*-
import io
from typing import Any
from fastapi import UploadFile
import pandas as pd
from app.core.base_schema import BatchSetAvailable
from app.core.exceptions import CustomException
from app.utils.excel_util import ExcelUtil
from app.core.logger import log
from app.api.v1.module_system.auth.schema import AuthSchema
from .schema import TokenCreateSchema, TokenUpdateSchema, TokenOutSchema, TokenQueryParam
from .crud import TokenCRUD
class TokenService:
"""
令牌管理模块服务层
"""
@classmethod
async def detail_service(cls, auth: AuthSchema, id: int) -> dict:
"""
详情
参数:
- auth (AuthSchema): 认证信息模型
- id (int): 令牌ID
返回:
- dict: 令牌模型实例字典
"""
obj = await TokenCRUD(auth).get_by_id_crud(id=id)
if not obj:
raise CustomException(msg="该数据不存在")
return TokenOutSchema.model_validate(obj).model_dump()
@classmethod
async def list_service(cls, auth: AuthSchema, search: TokenQueryParam | None = None, order_by: list[dict[str, str]] | None = None) -> list[dict]:
"""
列表查询
参数:
- auth (AuthSchema): 认证信息模型
- search (TokenQueryParam | None): 查询参数
- order_by (list[dict[str, str]] | None): 排序参数
返回:
- list[dict]: 令牌模型实例字典列表
"""
search_dict = search.__dict__ if search else None
obj_list = await TokenCRUD(auth).list_crud(search=search_dict, order_by=order_by)
return [TokenOutSchema.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: TokenQueryParam | None = None, order_by: list[dict[str, str]] | None = None) -> dict:
"""
分页查询
参数:
- auth (AuthSchema): 认证信息模型
- page_no (int): 页码
- page_size (int): 每页数量
- search (TokenQueryParam | None): 查询参数
- order_by (list[dict[str, str]] | None): 排序参数
返回:
- dict: 分页数据
"""
search_dict = search.__dict__ if search else {}
order_by_list = order_by or [{'id': 'asc'}]
offset = (page_no - 1) * page_size
result = await TokenCRUD(auth).page_crud(
offset=offset,
limit=page_size,
order_by=order_by_list,
search=search_dict
)
return result
@classmethod
async def create_service(cls, auth: AuthSchema, data: TokenCreateSchema) -> dict:
"""
创建
参数:
- auth (AuthSchema): 认证信息模型
- data (TokenCreateSchema): 令牌创建模型
返回:
- dict: 令牌模型实例字典
"""
obj = await TokenCRUD(auth).get(name=data.name)
if obj:
raise CustomException(msg='创建失败,名称已存在')
obj = await TokenCRUD(auth).create_crud(data=data)
return TokenOutSchema.model_validate(obj).model_dump()
@classmethod
async def update_service(cls, auth: AuthSchema, id: int, data: TokenUpdateSchema) -> dict:
"""
更新
参数:
- auth (AuthSchema): 认证信息模型
- id (int): 令牌ID
- data (TokenUpdateSchema): 令牌更新模型
返回:
- dict: 令牌模型实例字典
"""
# 检查数据是否存在
obj = await TokenCRUD(auth).get_by_id_crud(id=id)
if not obj:
raise CustomException(msg='更新失败,该数据不存在')
# 检查名称是否重复
exist_obj = await TokenCRUD(auth).get(name=data.name)
if exist_obj and exist_obj.id != id:
raise CustomException(msg='更新失败,名称重复')
obj = await TokenCRUD(auth).update_crud(id=id, data=data)
return TokenOutSchema.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='删除失败,删除对象不能为空')
# 检查所有要删除的数据是否存在
for id in ids:
obj = await TokenCRUD(auth).get_by_id_crud(id=id)
if not obj:
raise CustomException(msg=f'删除失败,ID为{id}的数据不存在')
await TokenCRUD(auth).delete_crud(ids=ids)
@classmethod
async def set_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
"""
批量设置状态
参数:
- auth (AuthSchema): 认证信息模型
- data (BatchSetAvailable): 批量设置状态模型
返回:
- None
"""
await TokenCRUD(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': '名称',
'status': '状态',
'description': '备注',
'created_time': '创建时间',
'updated_time': '更新时间',
'created_id': '创建者',
}
# 复制数据并转换状态
data = obj_list.copy()
for item in data:
# 处理状态
item['status'] = '启用' if item.get('status') == '0' else '停用'
# 处理创建者
creator_info = item.get('created_id')
if isinstance(creator_info, dict):
item['created_id'] = creator_info.get('name', '未知')
else:
item['created_id'] = '未知'
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
@classmethod
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',
'状态': 'status',
'描述': 'description'
}
try:
# 读取Excel文件
contents = await file.read()
df = pd.read_excel(io.BytesIO(contents))
await file.close()
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', 'status']
errors = []
for field in required_fields:
missing_rows = df[df[field].isnull()].index.tolist()
if missing_rows:
field_name = [k for k,v in header_dict.items() if v == field][0]
rows_str = "、".join([str(i+1) for i in missing_rows])
errors.append(f"{field_name}不能为空,第{rows_str}行")
if errors:
raise CustomException(msg=f"导入失败,以下行缺少必要字段:\n{'; '.join(errors)}")
error_msgs = []
success_count = 0
count = 0
# 处理每一行数据
for index, row in df.iterrows():
count += 1
try:
# 数据转换前的类型检查
try:
status = True if row['status'] == '正常' else False
except ValueError:
error_msgs.append(f"第{count}行: 状态必须是'正常'或'停用'")
continue
# 构建用户数据
data = {
"name": str(row['name']),
"status": status,
"description": str(row['description']),
}
# 处理用户导入
exists_obj = await TokenCRUD(auth).get(name=data["name"])
if exists_obj:
if update_support:
await TokenCRUD(auth).update(id=exists_obj.id, data=data)
success_count += 1
else:
error_msgs.append(f"第{count}行: 对象 {data['name']} 已存在")
else:
await TokenCRUD(auth).create(data=data)
success_count += 1
except Exception as e:
error_msgs.append(f"第{count}行: {str(e)}")
continue
# 返回详细的导入结果
result = f"成功导入 {success_count} 条数据"
if error_msgs:
result += "\n错误信息:\n" + "\n".join(error_msgs)
return result
except Exception as e:
log.error(f"批量导入用户失败: {str(e)}")
raise CustomException(msg=f"导入失败: {str(e)}")
@classmethod
async def import_template_download_service(cls) -> bytes:
"""
下载导入模板
返回:
- bytes: Excel文件字节流
"""
header_list = ['名称', '状态', '描述']
selector_header_list = ['状态']
option_list = [{'状态': ['正常', '停用']}]
return ExcelUtil.get_excel_template(
header_list=header_list,
selector_header_list=selector_header_list,
option_list=option_list
)
@@ -67,7 +67,7 @@ class UserModel(ModelMixin, UserMixin):
__table_args__: dict[str, str] = ({'comment': '用户表'}) __table_args__: dict[str, str] = ({'comment': '用户表'})
__loader_options__: list[str] = ["dept", "roles", "positions", "created_by", "updated_by"] __loader_options__: list[str] = ["dept", "roles", "positions", "created_by", "updated_by"]
username: Mapped[str] = mapped_column(String(32), nullable=False, unique=True, comment="用户名/登录账号") username: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, comment="用户名/登录账号")
password: Mapped[str] = mapped_column(String(255), nullable=False, comment="密码哈希") password: Mapped[str] = mapped_column(String(255), nullable=False, comment="密码哈希")
name: Mapped[str] = mapped_column(String(32), nullable=False, comment="昵称") name: Mapped[str] = mapped_column(String(32), nullable=False, comment="昵称")
mobile: Mapped[str | None] = mapped_column(String(11), nullable=True, unique=True, comment="手机号") mobile: Mapped[str | None] = mapped_column(String(11), nullable=True, unique=True, comment="手机号")
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from fastapi import Query from fastapi import Query
from pydantic import BaseModel, ConfigDict, Field, EmailStr, field_validator from pydantic import BaseModel, ConfigDict, Field, EmailStr, field_validator, model_validator
from urllib.parse import urlparse from urllib.parse import urlparse
from app.core.validator import DateTimeStr, mobile_validator from app.core.validator import DateTimeStr, email_validator, mobile_validator
from app.core.base_schema import BaseSchema, CommonSchema, UserBySchema from app.core.base_schema import BaseSchema, CommonSchema, UserBySchema
from app.core.validator import DateTimeStr from app.core.validator import DateTimeStr
from app.api.v1.module_system.menu.schema import MenuOutSchema from app.api.v1.module_system.menu.schema import MenuOutSchema
@@ -13,7 +13,7 @@ from app.api.v1.module_system.role.schema import RoleOutSchema
class CurrentUserUpdateSchema(BaseModel): class CurrentUserUpdateSchema(BaseModel):
"""基础用户信息""" """基础用户信息"""
name: str | None = Field(default=None, max_length=32, description="名称") name: str | None = Field(default=None, description="名称")
mobile: str | None = Field(default=None, description="手机号") mobile: str | None = Field(default=None, description="手机号")
email: EmailStr | None = Field(default=None, description="邮箱") email: EmailStr | None = Field(default=None, description="邮箱")
gender: str | None = Field(default=None, description="性别") gender: str | None = Field(default=None, description="性别")
@@ -24,6 +24,13 @@ class CurrentUserUpdateSchema(BaseModel):
def validate_mobile(cls, value: str | None): def validate_mobile(cls, value: str | None):
return mobile_validator(value) return mobile_validator(value)
@field_validator("email")
@classmethod
def validate_email(cls, value: str | None):
if not value:
return value
return email_validator(value)
@field_validator("avatar") @field_validator("avatar")
@classmethod @classmethod
def validate_avatar(cls, value: str | None): def validate_avatar(cls, value: str | None):
@@ -34,13 +41,19 @@ class CurrentUserUpdateSchema(BaseModel):
return value return value
raise ValueError("头像地址需为有效的HTTP/HTTPS URL") raise ValueError("头像地址需为有效的HTTP/HTTPS URL")
@model_validator(mode="after")
def check_model(self):
if self.name and len(self.name) > 32:
raise ValueError("名称长度不能超过32个字符")
return self
class UserRegisterSchema(BaseModel): class UserRegisterSchema(BaseModel):
"""注册""" """注册"""
name: str | None = Field(default=None, max_length=32, description="名称") name: str | None = Field(default=None, description="名称")
mobile: str | None = Field(default=None, description="手机号") mobile: str | None = Field(default=None, description="手机号")
username: str = Field(..., max_length=32, description="账号") username: str = Field(..., description="账号")
password: str = Field(..., max_length=128, description="密码哈希值") password: str = Field(..., description="密码哈希值")
role_ids: list[int] | None = Field(default=[1], description='角色ID') role_ids: list[int] | None = Field(default=[1], description='角色ID')
created_id: int | None = Field(default=1, description='创建人ID') created_id: int | None = Field(default=1, description='创建人ID')
description: str | None = Field(default=None, max_length=255, description="备注") description: str | None = Field(default=None, max_length=255, description="备注")
@@ -62,6 +75,18 @@ class UserRegisterSchema(BaseModel):
raise ValueError("账号需字母开头,3-32位,仅含字母/数字/_ . -") raise ValueError("账号需字母开头,3-32位,仅含字母/数字/_ . -")
return v return v
@model_validator(mode="after")
def check_model(self):
if self.name and len(self.name) > 32:
raise ValueError("名称长度不能超过32个字符")
if self.username and len(self.username) > 32:
raise ValueError("账号长度不能超过32个字符")
if self.description and len(self.description) > 255:
raise ValueError("备注长度不能超过255个字符")
if self.password and len(self.password) > 128:
raise ValueError("密码长度不能超过128个字符")
return self
class UserForgetPasswordSchema(BaseModel): class UserForgetPasswordSchema(BaseModel):
"""忘记密码""" """忘记密码"""
@@ -505,9 +505,16 @@ class UserService:
# 验证必填字段 # 验证必填字段
required_fields = ['username', 'name', 'dept_id'] required_fields = ['username', 'name', 'dept_id']
errors = []
for field in required_fields: for field in required_fields:
missing_rows = df[df[field].isnull()].index.tolist() missing_rows = df[df[field].isnull()].index.tolist()
raise CustomException(msg=f"{[k for k,v in header_dict.items() if v == field][0]}不能为空,第{[i+1 for i in missing_rows]}行") if missing_rows:
field_name = [k for k,v in header_dict.items() if v == field][0]
rows_str = "、".join([str(i+1) for i in missing_rows])
errors.append(f"{field_name}不能为空,第{rows_str}行")
if errors:
raise CustomException(msg=";".join(errors))
error_msgs = [] error_msgs = []
success_count = 0 success_count = 0
+6 -8
View File
@@ -49,7 +49,7 @@ class Settings(BaseSettings):
CORS_ORIGIN_ENABLE: bool = True # 是否启用跨域 CORS_ORIGIN_ENABLE: bool = True # 是否启用跨域
# ALLOW_ORIGINS: List[str] = ["*"] # 允许的域名列表 # ALLOW_ORIGINS: List[str] = ["*"] # 允许的域名列表
ALLOW_ORIGINS: List[str] = [ ALLOW_ORIGINS: List[str] = [
'http://127.0.0.1:8001', 'http://localhost:8001',
'http://localhost:5180', 'http://localhost:5180',
] # 允许的域名列表 ] # 允许的域名列表
ALLOW_METHODS: List[str] = ["*"] # 允许的HTTP方法 ALLOW_METHODS: List[str] = ["*"] # 允许的HTTP方法
@@ -87,7 +87,7 @@ class Settings(BaseSettings):
EXPIRE_ON_COMMIT: bool = False # 是否在提交时过期 EXPIRE_ON_COMMIT: bool = False # 是否在提交时过期
# 数据库类型 # 数据库类型
DATABASE_TYPE: Literal['mysql', 'postgres'] = 'mysql' DATABASE_TYPE: Literal['mysql', 'postgres', 'sqlite', 'dm'] = 'mysql'
# MySQL/PostgreSQL数据库连接 # MySQL/PostgreSQL数据库连接
@@ -197,11 +197,9 @@ class Settings(BaseSettings):
elif self.DATABASE_TYPE == "postgres": elif self.DATABASE_TYPE == "postgres":
return f"postgresql+asyncpg://{self.DATABASE_USER}:{quote_plus(self.DATABASE_PASSWORD)}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}" return f"postgresql+asyncpg://{self.DATABASE_USER}:{quote_plus(self.DATABASE_PASSWORD)}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
elif self.DATABASE_TYPE == "sqlite": elif self.DATABASE_TYPE == "sqlite":
return f"sqlite+aiosqlite:///{self.DATABASE_NAME}" return f"sqlite+aiosqlite:///{self.DATABASE_NAME}.db"
elif self.DATABASE_TYPE == "dm":
return f"dm+dmPython://{self.DATABASE_USER}:{quote_plus(self.DATABASE_PASSWORD)}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
else: else:
raise ValueError(f"数据库驱动不支持: {self.DATABASE_TYPE}, 请选择 请选择 mysql、postgres") raise ValueError(f"数据库驱动不支持: {self.DATABASE_TYPE}, 异步数据库请选择 mysql、postgres、sqlite")
@property @property
def DB_URI(self) -> str: def DB_URI(self) -> str:
@@ -211,11 +209,11 @@ class Settings(BaseSettings):
elif self.DATABASE_TYPE == "postgres": elif self.DATABASE_TYPE == "postgres":
return f"postgresql+psycopg2://{self.DATABASE_USER}:{quote_plus(self.DATABASE_PASSWORD)}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}" return f"postgresql+psycopg2://{self.DATABASE_USER}:{quote_plus(self.DATABASE_PASSWORD)}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
elif self.DATABASE_TYPE == "sqlite": elif self.DATABASE_TYPE == "sqlite":
return f"sqlite+pysqlite:///{self.DATABASE_NAME}" return f"sqlite+pysqlite:///{self.DATABASE_NAME}.db"
elif self.DATABASE_TYPE == "dm": elif self.DATABASE_TYPE == "dm":
return f"dm+dmPython://{self.DATABASE_USER}:{quote_plus(self.DATABASE_PASSWORD)}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}" return f"dm+dmPython://{self.DATABASE_USER}:{quote_plus(self.DATABASE_PASSWORD)}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
else: else:
raise ValueError(f"数据库驱动不支持: {self.DATABASE_TYPE}, 请选择 请选择 mysql、postgres") raise ValueError(f"数据库驱动不支持: {self.DATABASE_TYPE}, 同步数据库请选择 mysql、postgres、sqlite、dm")
@property @property
def REDIS_URI(self) -> str: def REDIS_URI(self) -> str:
+8 -32
View File
@@ -275,18 +275,6 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
- CustomException: 删除失败时抛出异常 - CustomException: 删除失败时抛出异常
""" """
try: try:
# 先查询确认权限,避免删除无权限的数据
objs = await self.list(search={"id": ("in", ids)})
accessible_ids = [obj.id for obj in objs]
# 检查是否所有ID都有权限访问
inaccessible_count = len(ids) - len(accessible_ids)
if inaccessible_count > 0:
raise CustomException(msg=f"无权限删除{inaccessible_count}条数据")
if not accessible_ids:
return # 没有可删除的数据
mapper = sa_inspect(self.model) mapper = sa_inspect(self.model)
pk_cols = list(getattr(mapper, "primary_key", [])) pk_cols = list(getattr(mapper, "primary_key", []))
if not pk_cols: if not pk_cols:
@@ -295,7 +283,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
raise CustomException(msg="暂不支持复合主键的批量删除") raise CustomException(msg="暂不支持复合主键的批量删除")
# 只删除有权限的数据 # 只删除有权限的数据
sql = delete(self.model).where(pk_cols[0].in_(accessible_ids)) sql = delete(self.model).where(pk_cols[0].in_(ids))
await self.auth.db.execute(sql) await self.auth.db.execute(sql)
await self.auth.db.flush() await self.auth.db.flush()
except Exception as e: except Exception as e:
@@ -327,18 +315,6 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
- CustomException: 更新失败时抛出异常 - CustomException: 更新失败时抛出异常
""" """
try: try:
# 先查询确认权限,避免更新无权限的数据
objs = await self.list(search={"id": ("in", ids)})
accessible_ids = [obj.id for obj in objs]
# 检查是否所有ID都有权限访问
inaccessible_count = len(ids) - len(accessible_ids)
if inaccessible_count > 0:
raise CustomException(msg=f"无权限更新{inaccessible_count}条数据")
if not accessible_ids:
return # 没有可更新的数据
mapper = sa_inspect(self.model) mapper = sa_inspect(self.model)
pk_cols = list(getattr(mapper, "primary_key", [])) pk_cols = list(getattr(mapper, "primary_key", []))
if not pk_cols: if not pk_cols:
@@ -347,7 +323,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
raise CustomException(msg="暂不支持复合主键的批量更新") raise CustomException(msg="暂不支持复合主键的批量更新")
# 只更新有权限的数据 # 只更新有权限的数据
sql = update(self.model).where(pk_cols[0].in_(accessible_ids)).values(**kwargs) sql = update(self.model).where(pk_cols[0].in_(ids)).values(**kwargs)
await self.auth.db.execute(sql) await self.auth.db.execute(sql)
await self.auth.db.flush() await self.auth.db.flush()
except CustomException: except CustomException:
@@ -400,17 +376,17 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
conditions.append(attr.in_(val)) conditions.append(attr.in_(val))
elif seq == "between" and isinstance(val, (list, tuple)) and len(val) == 2: elif seq == "between" and isinstance(val, (list, tuple)) and len(val) == 2:
conditions.append(attr.between(val[0], val[1])) conditions.append(attr.between(val[0], val[1]))
elif seq == "!=" and val: elif seq == "!=" or seq == "ne" and val:
conditions.append(attr != val) conditions.append(attr != val)
elif seq == ">" and val: elif seq == ">" or seq == "gt" and val:
conditions.append(attr > val) conditions.append(attr > val)
elif seq == ">=" and val: elif seq == ">=" or seq == "ge" and val:
conditions.append(attr >= val) conditions.append(attr >= val)
elif seq == "<" and val: elif seq == "<" or seq == "lt"and val:
conditions.append(attr < val) conditions.append(attr < val)
elif seq == "<=" and val: elif seq == "<=" or seq == "le" and val:
conditions.append(attr <= val) conditions.append(attr <= val)
elif seq == "==" and val: elif seq == "==" or seq == "eq" and val:
conditions.append(attr == val) conditions.append(attr == val)
else: else:
conditions.append(attr == value) conditions.append(attr == value)
+61
View File
@@ -9,6 +9,8 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from app.api.v1.module_system.user.model import UserModel from app.api.v1.module_system.user.model import UserModel
from app.api.v1.module_system.customer.model import CustomerModel
from app.api.v1.module_system.tenant.model import TenantModel
from app.utils.common_util import uuid4_str from app.utils.common_util import uuid4_str
@@ -116,3 +118,62 @@ class UserMixin(MappedBase):
foreign_keys=lambda: cls.updated_id, foreign_keys=lambda: cls.updated_id,
uselist=False uselist=False
) )
class TenantMixin(MappedBase):
"""
租户字段 Mixin
"""
__abstract__: bool = True
tenant_id: Mapped[int | None] = mapped_column(
Integer,
ForeignKey('sys_tenant.id', ondelete="CASCADE", onupdate="CASCADE"),
nullable=False,
index=True,
comment="所属租户ID"
)
@declared_attr
def tenant(cls) -> Mapped["TenantModel"]:
"""
租户关联关系(延迟加载,避免循环依赖)
"""
return relationship(
"TenantModel",
primaryjoin=f"{cls.__name__}.tenant_id == TenantModel.id",
lazy="selectin",
foreign_keys=lambda: [cls.tenant_id],
viewonly=True,
uselist=False
)
class CustomerMixin(MappedBase):
"""
客户隔离字段 Mixin
"""
__abstract__: bool = True
customer_id: Mapped[int | None] = mapped_column(
Integer,
ForeignKey('sys_customer.id', ondelete="CASCADE", onupdate="CASCADE"),
default=None,
nullable=True,
index=True,
comment="所属客户ID(NULL表示租户级数据,>0表示客户级数据)"
)
@declared_attr
def customer(cls) -> Mapped["CustomerModel"]:
"""
客户关联关系(延迟加载,避免循环依赖)
"""
return relationship(
"CustomerModel",
primaryjoin=f"{cls.__name__}.customer_id == CustomerModel.id",
lazy="selectin",
foreign_keys=lambda: [cls.customer_id],
viewonly=True,
uselist=False
)
+43 -6
View File
@@ -1,7 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import json
from fastapi import Query from fastapi import Query
from app.core.validator import DateTimeStr
class PaginationQueryParam: class PaginationQueryParam:
"""分页查询参数基类""" """分页查询参数基类"""
@@ -10,7 +13,7 @@ class PaginationQueryParam:
self, self,
page_no: int = Query(default=1, description="当前页码", ge=1), page_no: int = Query(default=1, description="当前页码", ge=1),
page_size: int = Query(default=10, description="每页数量", ge=1, le=100), page_size: int = Query(default=10, description="每页数量", ge=1, le=100),
order_by: str | None = Query(default=None, description="排序字段,格式:field1,asc;field2,desc"), order_by: str | None = Query(default=None, description="排序字段,格式:[{'field1': 'asc'}, {'field2': 'desc'}]"),
) -> None: ) -> None:
""" """
初始化分页查询参数。 初始化分页查询参数。
@@ -28,14 +31,48 @@ class PaginationQueryParam:
# 将字符串格式的order_by转换为服务层需要的List[Dict[str, str]]格式 # 将字符串格式的order_by转换为服务层需要的List[Dict[str, str]]格式
if order_by: if order_by:
try: try:
self.order_by = [] self.order_by = json.loads(order_by)
for item in order_by.split(';'):
if item.strip():
field, direction = item.split(',', 1)
self.order_by.append({field.strip(): direction.strip().lower()})
except ValueError: except ValueError:
# 如果解析失败,使用默认排序 # 如果解析失败,使用默认排序
self.order_by = [{'updated_time': 'desc'}] self.order_by = [{'updated_time': 'desc'}]
else: else:
self.order_by = [{'updated_time': 'desc'}] self.order_by = [{'updated_time': 'desc'}]
class BaseQueryParam:
"""公共查询参数"""
def __init__(
self,
description: 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"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
*args,
**kwargs
) -> None:
# 模糊查询字段
if description:
self.description = ("like", description)
# 精确查询字段
if status:
self.status = ("eq", status)
# 时间范围查询
if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1]))
class CommonQueryParam:
"""根据用户查询参数"""
def __init__(
self,
created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人")
) -> None:
if created_id:
self.created_id = ("eq", created_id)
if updated_id:
self.updated_id = ("eq", updated_id)
+18 -11
View File
@@ -5,15 +5,6 @@ from pydantic import BaseModel, ConfigDict, Field
from app.core.validator import DateTimeStr from app.core.validator import DateTimeStr
class UserInfoSchema(BaseModel):
"""用户信息模型"""
model_config = ConfigDict(from_attributes=True)
id: int | None = Field(default=None, description="用户ID")
name: str | None = Field(default=None, description="用户姓名")
username: str | None = Field(default=None, description="用户名")
class CommonSchema(BaseModel): class CommonSchema(BaseModel):
"""通用信息模型""" """通用信息模型"""
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
@@ -39,9 +30,25 @@ class UserBySchema(BaseModel):
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
created_id: int | None = Field(default=None, description="创建人ID") created_id: int | None = Field(default=None, description="创建人ID")
created_by: UserInfoSchema | None = Field(default=None, description="创建人信息") created_by: CommonSchema | None = Field(default=None, description="创建人信息")
updated_id: int | None = Field(default=None, description="更新人ID") updated_id: int | None = Field(default=None, description="更新人ID")
updated_by: UserInfoSchema | None = Field(default=None, description="更新人信息") updated_by: CommonSchema | None = Field(default=None, description="更新人信息")
class TenantSchema(BaseModel):
"""租户模型"""
model_config = ConfigDict(from_attributes=True)
tenant_id: int | None = Field(default=None, description="所属租户ID")
tenant: CommonSchema | None = Field(default=None, description="租户信息")
class CustomerSchema(BaseModel):
"""客户模型"""
model_config = ConfigDict(from_attributes=True)
customer_id: int | None = Field(default=None, description="所属客户ID")
customer: CommonSchema | None = Field(default=None, description="客户信息")
class BatchSetAvailable(BaseModel): class BatchSetAvailable(BaseModel):
+22 -12
View File
@@ -55,18 +55,28 @@ def create_async_engine_and_session(
if not settings.SQL_DB_ENABLE: if not settings.SQL_DB_ENABLE:
raise CustomException(msg="请先开启数据库连接", data="请启用 app/config/setting.py: SQL_DB_ENABLE") raise CustomException(msg="请先开启数据库连接", data="请启用 app/config/setting.py: SQL_DB_ENABLE")
# 异步数据库引擎 # 异步数据库引擎
async_engine: AsyncEngine = create_async_engine( if settings.DATABASE_TYPE == 'sqlite':
url=db_url, async_engine = create_async_engine(
echo=settings.DATABASE_ECHO, url=db_url,
echo_pool=settings.ECHO_POOL, echo=settings.DATABASE_ECHO,
pool_pre_ping=settings.POOL_PRE_PING, echo_pool=settings.ECHO_POOL,
future=settings.FUTURE, pool_pre_ping=settings.POOL_PRE_PING,
pool_recycle=settings.POOL_RECYCLE, future=settings.FUTURE,
pool_size=settings.POOL_SIZE, pool_recycle=settings.POOL_RECYCLE,
max_overflow=settings.MAX_OVERFLOW, )
pool_timeout=settings.POOL_TIMEOUT, else:
pool_use_lifo=settings.POOL_USE_LIFO, async_engine = create_async_engine(
) url=db_url,
echo=settings.DATABASE_ECHO,
echo_pool=settings.ECHO_POOL,
pool_pre_ping=settings.POOL_PRE_PING,
future=settings.FUTURE,
pool_recycle=settings.POOL_RECYCLE,
pool_size=settings.POOL_SIZE,
max_overflow=settings.MAX_OVERFLOW,
pool_timeout=settings.POOL_TIMEOUT,
pool_use_lifo=settings.POOL_USE_LIFO,
)
except Exception as e: except Exception as e:
log.error(f'❌ 数据库连接失败 {e}') log.error(f'❌ 数据库连接失败 {e}')
raise raise
+21
View File
@@ -107,6 +107,27 @@ def mobile_validator(value: str | None) -> str | None:
return value return value
def code_validator(value: str | None) -> str | None:
"""
编码验证器。
参数:
- value (str | None): 编码。
返回:
- str | None: 验证后的编码。
异常:
- CustomException: 编码格式无效时抛出。
"""
if not value:
return value
v = value.strip()
if not re.match(r"^[A-Za-z][A-Za-z0-9_]{1,15}$", v):
raise CustomException(code=RET.ERROR.code, msg="编码需字母开头,允许字母/数字/下划线,长度2-16")
return v
def menu_request_validator(data): def menu_request_validator(data):
""" """
菜单请求数据验证器。 菜单请求数据验证器。
+1 -1
View File
@@ -22,7 +22,7 @@ DESCRIPTION = "该项目是一个基于python的web服务框架,基于fastapi
DEMO_ENABLE = False DEMO_ENABLE = False
# 数据库配置 # 数据库配置
DATABASE_TYPE = "mysql" # mysql、postgres、[qlite、dm这俩种不支持代码生成] DATABASE_TYPE = "sqlite" # mysql、postgres、[qlite、dm这俩种不支持代码生成]
# 数据库配置 # 数据库配置
DATABASE_HOST = "localhost" DATABASE_HOST = "localhost"
+1 -1
View File
@@ -5,7 +5,7 @@ VITE_APP_ENV=development
VITE_APP_TITLE=fastapiadmin VITE_APP_TITLE=fastapiadmin
# 网络请求公用地址 # 网络请求公用地址
VITE_API_BASE_URL=http://127.0.0.1:8001 VITE_API_BASE_URL=https://service.fastapiadmin.com
# 代理前缀 # 代理前缀
VITE_APP_BASE_API=/api/v1 VITE_APP_BASE_API=/api/v1
+2
View File
@@ -63,6 +63,8 @@
}, },
"dependencies": { "dependencies": {
"@element-plus/icons-vue": "^2.3.1", "@element-plus/icons-vue": "^2.3.1",
"@logicflow/core": "2.2.0-alpha.3",
"@logicflow/extension": "2.2.0-alpha.3",
"@vueuse/core": "^13.5.0", "@vueuse/core": "^13.5.0",
"@wangeditor-next/editor": "^5.6.49", "@wangeditor-next/editor": "^5.6.49",
"@wangeditor-next/editor-for-vue": "^5.1.14", "@wangeditor-next/editor-for-vue": "^5.1.14",
+2 -2
View File
@@ -164,8 +164,8 @@ export interface JobTable extends BaseType {
trigger_args?: string; trigger_args?: string;
start_date?: string; start_date?: string;
end_date?: string; end_date?: string;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
export interface JobForm extends BaseFormType { export interface JobForm extends BaseFormType {
+2 -2
View File
@@ -97,8 +97,8 @@ export interface ApplicationInfo extends BaseType {
name?: string; name?: string;
access_url?: string; access_url?: string;
icon_url?: string; icon_url?: string;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
/** /**
+2 -2
View File
@@ -92,8 +92,8 @@ export interface DemoPageQuery extends PageQuery {
export interface DemoTable extends BaseType { export interface DemoTable extends BaseType {
name?: string; name?: string;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
export interface DemoForm extends BaseFormType { export interface DemoForm extends BaseFormType {
+4 -4
View File
@@ -166,8 +166,8 @@ export interface GenTableSchema extends BaseType {
sub_table?: GenTableSchema; sub_table?: GenTableSchema;
/** 是否为子表 */ /** 是否为子表 */
sub?: boolean; sub?: boolean;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
/** 代码生成业务表列模型 */ /** 代码生成业务表列模型 */
@@ -212,6 +212,6 @@ export interface GenTableColumnSchema extends BaseType {
dict_type?: string; dict_type?: string;
/** 排序 */ /** 排序 */
sort?: number; sort?: number;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
+101
View File
@@ -0,0 +1,101 @@
import request from "@/utils/request";
const API_PATH = "/system/customer";
const CustomerAPI = {
listCustomer(query: CustomerPageQuery) {
return request<ApiResponse<PageResult<CustomerTable[]>>>({
url: `${API_PATH}/list`,
method: "get",
params: query,
});
},
detailCustomer(query: number) {
return request<ApiResponse<CustomerTable>>({
url: `${API_PATH}/detail/${query}`,
method: "get",
});
},
createCustomer(body: CustomerForm) {
return request<ApiResponse>({
url: `${API_PATH}/create`,
method: "post",
data: body,
});
},
updateCustomer(id: number, body: CustomerForm) {
return request<ApiResponse>({
url: `${API_PATH}/update/${id}`,
method: "put",
data: body,
});
},
deleteCustomer(body: number[]) {
return request<ApiResponse>({
url: `${API_PATH}/delete`,
method: "delete",
data: body,
});
},
batchCustomer(body: BatchType) {
return request<ApiResponse>({
url: `${API_PATH}/available/setting`,
method: "patch",
data: body,
});
},
exportCustomer(body: CustomerPageQuery) {
return request<Blob>({
url: `${API_PATH}/export`,
method: "post",
data: body,
responseType: "blob",
});
},
downloadCustomer() {
return request<ApiResponse>({
url: `${API_PATH}/download/template`,
method: "post",
responseType: "blob",
});
},
importCustomer(body: FormData) {
return request<ApiResponse>({
url: `${API_PATH}/import`,
method: "post",
data: body,
headers: {
"Content-Type": "multipart/form-data",
},
});
},
};
export default CustomerAPI;
export interface CustomerPageQuery extends PageQuery {
name?: string;
status?: string;
created_time?: string[];
}
export interface CustomerTable extends BaseType {
name?: string;
code?: string;
created_by?: CommonType;
updated_by?: CommonType;
tenant?: CommonType;
}
export interface CustomerForm extends BaseFormType {
name?: string;
code?: string;
}
+2 -2
View File
@@ -60,6 +60,6 @@ export interface LogTable extends BaseType {
request_payload?: string; request_payload?: string;
response_json?: string; response_json?: string;
process_time?: string; process_time?: string;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
+2 -2
View File
@@ -83,8 +83,8 @@ export interface NoticeTable extends BaseType {
notice_title?: string; notice_title?: string;
notice_type?: string; notice_type?: string;
notice_content?: string; notice_content?: string;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
export interface NoticeForm extends BaseFormType { export interface NoticeForm extends BaseFormType {
+2 -2
View File
@@ -73,8 +73,8 @@ export interface PositionPageQuery extends PageQuery {
export interface PositionTable extends BaseType { export interface PositionTable extends BaseType {
name?: string; name?: string;
order?: number; order?: number;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
export interface PositionForm extends BaseFormType { export interface PositionForm extends BaseFormType {
+102
View File
@@ -0,0 +1,102 @@
import request from "@/utils/request";
const API_PATH = "/system/tenant";
const TenantAPI = {
listTenant(query: TenantPageQuery) {
return request<ApiResponse<PageResult<TenantTable[]>>>({
url: `${API_PATH}/list`,
method: "get",
params: query,
});
},
detailTenant(query: number) {
return request<ApiResponse<TenantTable>>({
url: `${API_PATH}/detail/${query}`,
method: "get",
});
},
createTenant(body: TenantForm) {
return request<ApiResponse>({
url: `${API_PATH}/create`,
method: "post",
data: body,
});
},
updateTenant(id: number, body: TenantForm) {
return request<ApiResponse>({
url: `${API_PATH}/update/${id}`,
method: "put",
data: body,
});
},
deleteTenant(body: number[]) {
return request<ApiResponse>({
url: `${API_PATH}/delete`,
method: "delete",
data: body,
});
},
batchTenant(body: BatchType) {
return request<ApiResponse>({
url: `${API_PATH}/available/setting`,
method: "patch",
data: body,
});
},
exportTenant(body: TenantPageQuery) {
return request<Blob>({
url: `${API_PATH}/export`,
method: "post",
data: body,
responseType: "blob",
});
},
downloadTenant() {
return request<ApiResponse>({
url: `${API_PATH}/download/template`,
method: "post",
responseType: "blob",
});
},
importTenant(body: FormData) {
return request<ApiResponse>({
url: `${API_PATH}/import`,
method: "post",
data: body,
headers: {
"Content-Type": "multipart/form-data",
},
});
},
};
export default TenantAPI;
export interface TenantPageQuery extends PageQuery {
name?: string;
status?: string;
created_time?: string[];
}
export interface TenantTable extends BaseType {
name?: string;
code?: string;
start_time?: string;
end_time?: string;
}
export interface TenantForm extends BaseFormType {
name?: string;
code?: string;
start_time?: string;
end_time?: string;
}
+101
View File
@@ -0,0 +1,101 @@
import request from "@/utils/request";
const API_PATH = "/system/token";
const TokenAPI = {
getTokenList(query: TokenPageQuery) {
return request<ApiResponse<PageResult<TokenTable[]>>>({
url: `${API_PATH}/list`,
method: "get",
params: query,
});
},
getTokenDetail(query: number) {
return request<ApiResponse<TokenTable>>({
url: `${API_PATH}/detail/${query}`,
method: "get",
});
},
createToken(body: TokenForm) {
return request<ApiResponse>({
url: `${API_PATH}/create`,
method: "post",
data: body,
});
},
updateToken(id: number, body: TokenForm) {
return request<ApiResponse>({
url: `${API_PATH}/update/${id}`,
method: "put",
data: body,
});
},
deleteToken(body: number[]) {
return request<ApiResponse>({
url: `${API_PATH}/delete`,
method: "delete",
data: body,
});
},
batchToken(body: BatchType) {
return request<ApiResponse>({
url: `${API_PATH}/available/setting`,
method: "patch",
data: body,
});
},
exportToken(body: TokenPageQuery) {
return request<Blob>({
url: `${API_PATH}/export`,
method: "post",
data: body,
responseType: "blob",
});
},
downloadTemplateToken() {
return request<ApiResponse>({
url: `${API_PATH}/download/template`,
method: "post",
responseType: "blob",
});
},
importToken(body: FormData) {
return request<ApiResponse>({
url: `${API_PATH}/import`,
method: "post",
data: body,
headers: {
"Content-Type": "multipart/form-data",
},
});
},
};
export default TokenAPI;
export interface TokenPageQuery extends PageQuery {
name?: string;
status?: string;
created_time?: string[];
updated_time?: string[];
created_id?: number;
updated_id?: number;
}
export interface TokenTable extends BaseType {
name?: string;
created_by?: CommonType;
updated_by?: CommonType;
}
export interface TokenForm extends BaseFormType {
name?: string;
}
+2 -2
View File
@@ -188,8 +188,8 @@ export interface UserInfo extends BaseType {
position_ids?: positionSelectorType["id"][]; position_ids?: positionSelectorType["id"][];
is_superuser?: boolean; is_superuser?: boolean;
last_login?: string; last_login?: string;
created_by?: creatorType; created_by?: CommonType;
updated_by?: updatorType; updated_by?: CommonType;
} }
export interface deptTreeType { export interface deptTreeType {
@@ -67,7 +67,7 @@
<el-icon> <el-icon>
<User /> <User />
</el-icon> </el-icon>
{{ noticeDetail.created_by?.username }} {{ noticeDetail.created_by?.name }}
</span> </span>
<span class="ml-2 flex-y-center"> <span class="ml-2 flex-y-center">
<el-icon> <el-icon>
-18
View File
@@ -136,24 +136,6 @@ declare global {
name?: string; name?: string;
} }
/**
* 创建人
*/
interface creatorType {
id?: number;
name?: string;
username?: string;
}
/**
* 更新人
*/
interface updatorType {
id?: number;
name?: string;
username?: string;
}
/** /**
* 基础类型 * 基础类型
*/ */
@@ -1,15 +1,882 @@
<!-- 演示示例 -->
<template> <template>
<div class="app-container"> <div class="app-container">
<p>工作流--开发中...</p> <!-- 顶部操作栏 -->
<div class="workflow-header">
<h2>流程编排</h2>
<div class="header-actions">
<ElButton type="primary" @click="handleSave">保存流程</ElButton>
<ElButton type="warning" @click="handleValidate">验证流程</ElButton>
<ElButton @click="handleClear">清空画布</ElButton>
<ElButton @click="handleLoadExample">加载示例</ElButton>
</div>
</div>
<!-- 主要内容区域 -->
<div class="workflow-main">
<!-- 左侧节点库 -->
<div class="node-library">
<div class="node-library-title">节点库</div>
<div class="node-library-search">
<ElInput
v-model="searchKeyword"
placeholder="搜索节点"
prefix-icon="el-icon-search"
size="small"
@input="handleSearch"
/>
</div>
<div id="dnd-panel" class="dnd-panel-container"></div>
</div>
<!-- 中央画布区域 -->
<div class="canvas-wrapper">
<div id="logicflow-canvas"></div>
</div>
<!-- 右侧属性面板 -->
<div v-if="selectedNode" class="property-panel">
<div class="property-panel-title">节点属性</div>
<div class="property-panel-content">
<ElForm :model="nodeProperties" label-width="80px">
<ElFormItem label="节点名称">
<ElInput v-model="nodeProperties.text" placeholder="请输入节点名称"></ElInput>
</ElFormItem>
<ElFormItem label="节点ID">
<ElInput v-model="nodeProperties.id" disabled placeholder="节点ID"></ElInput>
</ElFormItem>
<ElFormItem label="节点类型">
<ElInput v-model="nodeProperties.type" disabled placeholder="节点类型"></ElInput>
</ElFormItem>
<ElFormItem label="X坐标">
<ElInputNumber v-model="nodeProperties.x" :min="0" :precision="0"></ElInputNumber>
</ElFormItem>
<ElFormItem label="Y坐标">
<ElInputNumber v-model="nodeProperties.y" :min="0" :precision="0"></ElInputNumber>
</ElFormItem>
<ElFormItem>
<ElButton type="primary" @click="saveNodeProperties">保存属性</ElButton>
<ElButton @click="cancelEdit">取消</ElButton>
</ElFormItem>
</ElForm>
</div>
</div>
</div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from "vue";
import LogicFlow from "@logicflow/core";
import { Control, Menu, DndPanel, SelectionSelect } from "@logicflow/extension";
import { ElMessage, ElForm, ElFormItem, ElInput, ElInputNumber, ElButton } from "element-plus";
import "@logicflow/core/lib/style/index.css";
import "@logicflow/extension/lib/style/index.css";
defineOptions({ defineOptions({
name: "Workflow", name: "Workflow",
inheritAttrs: false, inheritAttrs: false,
}); });
//图方法
// 放大或缩小画布
// lf.zoom(isZoomIn);
// // 将图形移动到画布中心
// lf.focusOn(focusOnArgs);
// 监听事件
// lf.on(evt, callback);
// // 撤销
// lf.undo();
// // 获取画布数据
// lf.getGraphData();
// // 节点方法
// // 添加节点
// lf.addNode(nodeConfig);
// // 删除节点
// lf.deleteNode(nodeId);
// // 克隆节点
// lf.cloneNode(nodeId);
// // 获取节点的model数据
// lf.getNodeModel(nodeId);
// 连线方法
// 创建边
// lf.createEdge(edgeConfig);
// // 根据连线Id来删除边
// lf.deleteEdge(edgeId);
// // 根据连线两端节点的Id来删除边
// lf.removeEdge(sourceNodeId, targetNodeId);
// // 获取边的model数据
// lf.getEdge(config);
// // 获取边的数据属性
// lf.getEdgeData(edgeId);
// // 设置边的数据属性
// lf.setEdgeData(edgeAttribute);
// LogicFlow实例
let lf: LogicFlow | null = null;
// 选中的节点
const selectedNode = ref<any>(null);
// 节点属性
const nodeProperties = reactive({
id: "",
type: "",
text: "",
x: 0,
y: 0,
});
// 搜索关键字
const searchKeyword = ref("");
// 搜索处理函数(暂时保留,可用于后续搜索功能扩展)
const handleSearch = () => {
console.log("搜索节点:", searchKeyword.value);
};
// 节点类型定义可以在setPatternItems中配置
// 事件处理函数
const bindEvents = () => {
if (!lf) return;
// 节点添加事件
lf.on("node:add", (params: any) => {
console.log("节点添加:", params);
});
// DndPanel会自动处理拖拽事件,无需手动监听drop事件
// 节点删除事件
lf.on("node:remove", (params: any) => {
console.log("节点删除:", params);
if (selectedNode.value && selectedNode.value.id === params.data.id) {
selectedNode.value = null;
}
});
// 连线添加事件
lf.on("edge:add", (params: any) => {
console.log("连线添加:", params);
});
// 连线删除事件
lf.on("edge:remove", (params: any) => {
console.log("连线删除:", params);
});
// 节点选中事件
lf.on("node:select", (params: any) => {
console.log("节点选中:", params);
selectedNode.value = params.data;
// 填充属性表单
nodeProperties.id = params.data.id;
nodeProperties.type = params.data.type;
nodeProperties.text = params.data.text || "";
nodeProperties.x = params.data.x;
nodeProperties.y = params.data.y;
});
// 连线选中事件
lf.on("edge:select", (params: any) => {
console.log("连线选中:", params);
selectedNode.value = null; // 选中连线时隐藏属性面板
});
// 画布点击事件
lf.on("canvas:click", (params: any) => {
console.log("画布点击:", params);
selectedNode.value = null; // 点击画布空白处隐藏属性面板
});
};
// 保存节点属性
const saveNodeProperties = () => {
if (!lf || !selectedNode.value) return;
// 更新节点属性
lf.updateNode({ ...nodeProperties });
ElMessage.success("节点属性保存成功");
};
// 取消编辑
const cancelEdit = () => {
if (selectedNode.value) {
// 恢复原始属性
nodeProperties.id = selectedNode.value.id;
nodeProperties.type = selectedNode.value.type;
nodeProperties.text = selectedNode.value.text || "";
nodeProperties.x = selectedNode.value.x;
nodeProperties.y = selectedNode.value.y;
}
};
// 定义节点配置,接近参考demo的实现方式
const nodeConfigs = {
startNode: {
extendsNode: "rect",
getShape() {
return {
type: "rect",
attr: {
width: 80,
height: 40,
fill: "#e6f7ff",
stroke: "#1890ff",
radius: 20,
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#1890ff",
};
},
},
endNode: {
extendsNode: "rect",
getShape() {
return {
type: "rect",
attr: {
width: 80,
height: 40,
fill: "#fff2f0",
stroke: "#ff4d4f",
radius: 20,
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#ff4d4f",
};
},
},
taskNode: {
extendsNode: "rect",
getShape() {
return {
type: "rect",
attr: {
width: 100,
height: 60,
fill: "#ffffff",
stroke: "#1890ff",
radius: 4,
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#333333",
};
},
},
conditionNode: {
extendsNode: "diamond",
getShape() {
return {
type: "diamond",
attr: {
width: 80,
height: 80,
fill: "#fffbe6",
stroke: "#faad14",
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#333333",
};
},
},
approvalNode: {
extendsNode: "rect",
getShape() {
return {
type: "rect",
attr: {
width: 100,
height: 60,
fill: "#f6ffed",
stroke: "#722ed1",
radius: 4,
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#333333",
};
},
},
parallelNode: {
extendsNode: "rect",
getShape() {
return {
type: "rect",
attr: {
width: 100,
height: 60,
fill: "#e6fffb",
stroke: "#13c2c2",
radius: 4,
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#333333",
};
},
},
subprocessNode: {
extendsNode: "rect",
getShape() {
return {
type: "rect",
attr: {
width: 100,
height: 60,
fill: "#fff0f6",
stroke: "#eb2f96",
radius: 4,
strokeDasharray: "5,5",
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#333333",
};
},
},
timerNode: {
extendsNode: "circle",
getShape() {
return {
type: "circle",
attr: {
r: 30,
fill: "#fff7e6",
stroke: "#fa8c16",
},
};
},
getTextStyle() {
return {
fontSize: 14,
fill: "#333333",
};
},
},
};
// 注册自定义节点,参考demo的实现方式
const registerCustomNodes = () => {
if (!lf) return;
// 注册所有节点配置
Object.entries(nodeConfigs).forEach(([type, config]) => {
lf.register(type, config);
});
};
// 功能按钮处理函数
const handleSave = () => {
if (!lf) return;
const graphData = lf.getGraphData();
console.log("保存流程数据:", graphData);
ElMessage.success("流程保存成功");
};
const handleValidate = () => {
if (!lf) return;
const graphData = lf.getGraphData();
const { nodes, edges } = graphData;
const errors: string[] = [];
// 检查开始节点
const startNodes = nodes.filter((node) => node.type === "startNode");
if (startNodes.length === 0) {
errors.push("流程缺少开始节点");
} else if (startNodes.length > 1) {
errors.push("流程只能有一个开始节点");
}
// 检查结束节点
const endNodes = nodes.filter((node) => node.type === "endNode");
if (endNodes.length === 0) {
errors.push("流程缺少结束节点");
} else if (endNodes.length > 1) {
errors.push("流程只能有一个结束节点");
}
// 检查孤立节点
const nodeIds = new Set(nodes.map((node) => node.id));
const connectedNodeIds = new Set<string>();
edges.forEach((edge) => {
connectedNodeIds.add(edge.sourceNodeId);
connectedNodeIds.add(edge.targetNodeId);
});
nodeIds.forEach((nodeId) => {
if (!connectedNodeIds.has(nodeId)) {
const node = nodes.find((n) => n.id === nodeId);
if (node) {
errors.push(`节点 "${node.text || node.id}" 是孤立节点,没有任何连线`);
}
}
});
// 检查结束节点是否有出边
endNodes.forEach((endNode) => {
const endNodeEdges = edges.filter((edge) => edge.sourceNodeId === endNode.id);
if (endNodeEdges.length > 0) {
errors.push(`结束节点 "${endNode.text || endNode.id}" 不能有出边`);
}
});
// 检查开始节点是否有入边
startNodes.forEach((startNode) => {
const startNodeEdges = edges.filter((edge) => edge.targetNodeId === startNode.id);
if (startNodeEdges.length > 0) {
errors.push(`开始节点 "${startNode.text || startNode.id}" 不能有入边`);
}
});
// 检查循环路径
const hasCycle = checkCycle(nodes, edges);
if (hasCycle) {
errors.push("流程中存在循环路径");
}
// 显示验证结果
if (errors.length > 0) {
ElMessage.error({
message: `流程验证失败,发现 ${errors.length} 个问题:\n${errors.join("\n")}`,
duration: 5000,
showClose: true,
});
} else {
ElMessage.success("流程验证通过!");
}
};
// 检查是否有循环路径
const checkCycle = (nodes: any[], edges: any[]) => {
const nodeMap = new Map(nodes.map((node) => [node.id, []]));
const visited = new Set<string>();
const recStack = new Set<string>();
// 构建邻接表
edges.forEach((edge) => {
const neighbors = nodeMap.get(edge.sourceNodeId) || [];
neighbors.push(edge.targetNodeId);
nodeMap.set(edge.sourceNodeId, neighbors);
});
// DFS 检测循环
const dfs = (nodeId: string): boolean => {
if (!visited.has(nodeId)) {
visited.add(nodeId);
recStack.add(nodeId);
const neighbors = nodeMap.get(nodeId) || [];
for (const neighbor of neighbors) {
if (!visited.has(neighbor) && dfs(neighbor)) {
return true;
} else if (recStack.has(neighbor)) {
return true;
}
}
}
recStack.delete(nodeId);
return false;
};
// 对每个未访问的节点执行 DFS
for (const node of nodes) {
if (dfs(node.id)) {
return true;
}
}
return false;
};
const handleClear = () => {
if (!lf) return;
lf.clear();
ElMessage.info("画布已清空");
};
const handleLoadExample = () => {
if (!lf) return;
const exampleData = {
nodes: [
{
id: "start1",
type: "startNode",
x: 200,
y: 100,
text: "开始",
},
{
id: "task1",
type: "taskNode",
x: 200,
y: 200,
text: "任务1",
},
{
id: "condition1",
type: "conditionNode",
x: 200,
y: 300,
text: "条件",
},
{
id: "approval1",
type: "approvalNode",
x: 100,
y: 400,
text: "审批",
},
{
id: "task2",
type: "taskNode",
x: 300,
y: 400,
text: "任务2",
},
{
id: "end1",
type: "endNode",
x: 200,
y: 500,
text: "结束",
},
],
edges: [
{
id: "edge1",
sourceNodeId: "start1",
targetNodeId: "task1",
},
{
id: "edge2",
sourceNodeId: "task1",
targetNodeId: "condition1",
},
{
id: "edge3",
sourceNodeId: "condition1",
targetNodeId: "approval1",
text: "是",
},
{
id: "edge4",
sourceNodeId: "condition1",
targetNodeId: "task2",
text: "否",
},
{
id: "edge5",
sourceNodeId: "approval1",
targetNodeId: "end1",
},
{
id: "edge6",
sourceNodeId: "task2",
targetNodeId: "end1",
},
],
};
lf.render(exampleData);
ElMessage.success("示例流程加载成功");
};
// 窗口大小变化处理
const handleResize = () => {
if (lf) {
lf.resize(window.innerWidth - 350 - 300, window.innerHeight - 100);
}
};
// 初始化LogicFlow
const initLogicFlow = () => {
if (lf) return;
lf = new LogicFlow({
container: document.querySelector("#logicflow-canvas"),
// 画布配置
width: window.innerWidth - 350 - 300,
height: window.innerHeight - 100,
background: {
color: "#F0F0F0",
},
grid: {
type: "dot",
size: 20,
},
snapline: true,
textEdit: true,
isSilentMode: false,
edgeType: "line",
keyboard: {
enabled: true,
},
plugins: [Control, Menu, SelectionSelect],
});
// 注册自定义节点
registerCustomNodes();
// 增强节点和连线的视觉效果
enhanceVisuals();
// 绑定事件
bindEvents();
// 使用DndPanel的setPatternItems方法配置节点面板
lf.extension.dndPanel.setPatternItems([
{ type: "startNode", label: "开始节点" },
{ type: "endNode", label: "结束节点" },
{ type: "taskNode", label: "任务节点" },
{ type: "conditionNode", label: "条件节点" },
{ type: "approvalNode", label: "审批节点" },
{ type: "parallelNode", label: "并行节点" },
{ type: "subprocessNode", label: "子流程节点" },
{ type: "timerNode", label: "定时节点" },
]);
// 渲染 - 提供空的图数据
lf.render({ nodes: [], edges: [] });
};
// 增强节点和连线的视觉效果
const enhanceVisuals = () => {
if (!lf) return;
// 为节点添加鼠标悬停效果
lf.on("node:mouseenter", (params) => {
const node = params.data;
lf?.setNodeStyle(node.id, {
boxShadow: "0 0 10px rgba(0, 0, 0, 0.3)",
transition: "all 0.3s ease",
scale: 1.05,
});
});
lf.on("node:mouseleave", (params) => {
const node = params.data;
lf?.setNodeStyle(node.id, {
boxShadow: "none",
transition: "all 0.3s ease",
scale: 1,
});
});
// 节点选中效果
lf.on("node:select", (params) => {
const node = params.data;
lf?.setNodeStyle(node.id, {
strokeWidth: 3,
boxShadow: "0 0 15px rgba(24, 144, 255, 0.5)",
});
});
// 节点取消选中效果
lf.on("node:unselect", (params) => {
const node = params.data;
lf?.setNodeStyle(node.id, {
strokeWidth: 2,
boxShadow: "none",
});
});
// 连线样式增强
lf.on("edge:select", (params) => {
const edge = params.data;
lf?.setEdgeStyle(edge.id, {
strokeWidth: 3,
stroke: "#1890ff",
});
});
lf.on("edge:unselect", (params) => {
const edge = params.data;
lf?.setEdgeStyle(edge.id, {
strokeWidth: 2,
stroke: "#aaa",
});
});
// 连线鼠标悬停效果
lf.on("edge:mouseenter", (params) => {
const edge = params.data;
lf?.setEdgeStyle(edge.id, {
strokeWidth: 3,
stroke: "#1890ff",
});
});
lf.on("edge:mouseleave", (params) => {
const edge = params.data;
lf?.setEdgeStyle(edge.id, {
strokeWidth: 2,
stroke: edge.selected ? "#1890ff" : "#aaa",
});
});
};
// 生命周期钩子
onMounted(() => {
initLogicFlow();
window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
if (lf) {
lf.destroy();
lf = null;
}
window.removeEventListener("resize", handleResize);
});
</script> </script>
<style lang="scss" scoped></style> <style lang="scss" scoped>
.app-container {
.workflow-header {
height: 60px;
padding: 0 20px;
display: flex;
justify-content: space-between;
align-items: center;
h2 {
margin: 0;
font-size: 18px;
font-weight: 600;
}
.header-actions {
display: flex;
gap: 12px;
}
}
.workflow-main {
flex: 1;
display: flex;
overflow: hidden;
.node-library {
width: 350px;
display: flex;
flex-direction: column;
.node-library-title {
height: 40px;
line-height: 40px;
padding: 0 20px;
font-size: 16px;
font-weight: 500;
}
.node-library-search {
padding: 12px 20px;
}
#dnd-panel {
flex: 1;
padding: 16px;
overflow-y: auto;
.dnd-node-item {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
margin-bottom: 8px;
border-radius: 6px;
cursor: move;
transition: all 0.3s ease;
background-color: #ffffff;
border: 1px solid #e0e0e0;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
&:hover {
background-color: #f0f9ff;
border-color: #91d5ff;
box-shadow: 0 4px 8px rgba(24, 144, 255, 0.15);
}
}
}
}
.canvas-wrapper {
flex: 1;
position: relative;
#logicflow-canvas {
width: 100%;
height: 100%;
}
}
.property-panel {
width: 300px;
display: flex;
flex-direction: column;
.property-panel-title {
height: 40px;
line-height: 40px;
padding: 0 20px;
font-size: 16px;
font-weight: 500;
}
.property-panel-content {
flex: 1;
padding: 20px;
overflow-y: auto;
:deep(.el-form-item) {
margin-bottom: 20px;
}
:deep(.el-form-item__label) {
font-weight: 500;
}
}
}
}
}
</style>
@@ -0,0 +1,745 @@
<!-- 租户 -->
<template>
<div class="app-container">
<!-- 搜索区域 -->
<div v-show="visible" class="search-container">
<el-form
ref="queryFormRef"
:model="queryFormData"
label-suffix=":"
:inline="true"
@submit.prevent="handleQuery"
>
<el-form-item prop="name" label="名称">
<el-input v-model="queryFormData.name" placeholder="请输入名称" clearable />
</el-form-item>
<el-form-item prop="status" label="状态">
<el-select
v-model="queryFormData.status"
placeholder="请选择状态"
style="width: 170px"
clearable
>
<el-option value="true" label="启用" />
<el-option value="false" label="停用" />
</el-select>
</el-form-item>
<!-- 时间范围,收起状态下隐藏 -->
<el-form-item v-if="isExpand" prop="start_time" label="创建时间">
<DatePicker v-model="dateRange" @update:model-value="handleDateRangeChange" />
</el-form-item>
<!-- 查询、重置、展开/收起按钮 -->
<el-form-item>
<el-button
v-hasPerm="['module_system:customer:query']"
type="primary"
icon="search"
@click="handleQuery"
>
查询
</el-button>
<el-button
v-hasPerm="['module_system:customer:query']"
icon="refresh"
@click="handleResetQuery"
>
重置
</el-button>
<!-- 展开/收起 -->
<template v-if="isExpandable">
<el-link class="ml-3" type="primary" underline="never" @click="isExpand = !isExpand">
{{ isExpand ? "收起" : "展开" }}
<el-icon>
<template v-if="isExpand">
<ArrowUp />
</template>
<template v-else>
<ArrowDown />
</template>
</el-icon>
</el-link>
</template>
</el-form-item>
</el-form>
</div>
<!-- 内容区域 -->
<el-card class="data-table">
<template #header>
<div class="card-header">
<span>
租户列表
<el-tooltip content="租户列表">
<QuestionFilled class="w-4 h-4 mx-1" />
</el-tooltip>
</span>
</div>
</template>
<!-- 功能区域 -->
<div class="data-table__toolbar">
<div class="data-table__toolbar--left">
<el-row :gutter="10">
<el-col :span="1.5">
<el-button
v-hasPerm="['module_system:customer:create']"
type="success"
icon="plus"
@click="handleOpenDialog('create')"
>
新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
v-hasPerm="['module_system:customer:delete']"
type="danger"
icon="delete"
:disabled="selectIds.length === 0"
@click="handleDelete(selectIds)"
>
批量删除
</el-button>
</el-col>
<el-col :span="1.5">
<el-dropdown v-hasPerm="['module_system:customer:batch']" trigger="click">
<el-button type="default" :disabled="selectIds.length === 0" icon="ArrowDown">
更多
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item icon="Check" @click="handleMoreClick('0')">
批量启用
</el-dropdown-item>
<el-dropdown-item icon="CircleClose" @click="handleMoreClick('1')">
批量停用
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</el-col>
</el-row>
</div>
<div class="data-table__toolbar--right">
<el-row :gutter="10">
<el-col :span="1.5">
<el-tooltip content="导入">
<el-button
v-hasPerm="['module_system:customer:import']"
type="success"
icon="upload"
circle
@click="handleOpenImportDialog"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="导出">
<el-button
v-hasPerm="['module_system:customer:export']"
type="warning"
icon="download"
circle
@click="handleOpenExportsModal"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="搜索显示/隐藏">
<el-button
v-hasPerm="['*:*:*']"
type="info"
icon="search"
circle
@click="visible = !visible"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="刷新">
<el-button
v-hasPerm="['module_system:customer:query']"
type="primary"
icon="refresh"
circle
@click="handleRefresh"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-popover placement="bottom" trigger="click">
<template #reference>
<el-button type="danger" icon="operation" circle></el-button>
</template>
<el-scrollbar max-height="350px">
<template v-for="column in tableColumns" :key="column.prop">
<el-checkbox v-if="column.prop" v-model="column.show" :label="column.label" />
</template>
</el-scrollbar>
</el-popover>
</el-col>
</el-row>
</div>
</div>
<!-- 表格区域:系统配置列表 -->
<el-table
ref="tableRef"
v-loading="loading"
:data="pageTableData"
highlight-current-row
class="data-table__content"
:height="450"
border
stripe
@selection-change="handleSelectionChange"
>
<template #empty>
<el-empty :image-size="80" description="暂无数据" />
</template>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'selection')?.show"
type="selection"
min-width="55"
align="center"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'index')?.show"
fixed
label="序号"
min-width="60"
>
<template #default="scope">
{{ (queryFormData.page_no - 1) * queryFormData.page_size + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'name')?.show"
label="名称"
prop="name"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'code')?.show"
label="编码"
prop="code"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'status')?.show"
label="状态"
prop="status"
min-width="120"
>
<template #default="scope">
<el-tag :type="scope.row.status ? 'success' : 'info'">
{{ scope.row.status ? "启用" : "停用" }}
</el-tag>
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'description')?.show"
label="描述"
prop="description"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'created_time')?.show"
label="创建时间"
prop="created_time"
min-width="180"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'updated_time')?.show"
label="更新时间"
prop="updated_time"
min-width="180"
/>
<!-- <el-table-column v-if="tableColumns.find((col) => col.prop === 'creator')?.show" label="创建人" prop="creator" min-width="120">
<template #default="scope">
<el-tag>{{ scope.row.created_by?.name }}</el-tag>
</template>
</el-table-column> -->
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'operation')?.show"
fixed="right"
label="操作"
align="center"
min-width="180"
>
<template #default="scope">
<el-button
v-hasPerm="['module_system:customer:query']"
type="info"
size="small"
link
icon="document"
@click="handleOpenDialog('detail', scope.row.id)"
>
详情
</el-button>
<el-button
v-hasPerm="['module_system:customer:update']"
type="primary"
size="small"
link
icon="edit"
@click="handleOpenDialog('update', scope.row.id)"
>
编辑
</el-button>
<el-button
v-hasPerm="['module_system:customer:delete']"
type="danger"
size="small"
link
icon="delete"
@click="handleDelete([scope.row.id])"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页区域 -->
<template #footer>
<pagination
v-model:total="total"
v-model:page="queryFormData.page_no"
v-model:limit="queryFormData.page_size"
@pagination="loadingData"
/>
</template>
</el-card>
<!-- 弹窗区域 -->
<el-dialog
v-model="dialogVisible.visible"
:title="dialogVisible.title"
@close="handleCloseDialog"
>
<!-- 详情 -->
<template v-if="dialogVisible.type === 'detail'">
<el-descriptions :column="4" border>
<el-descriptions-item label="名称" :span="2">
{{ detailFormData.name }}
</el-descriptions-item>
<el-descriptions-item label="编码" :span="2">
{{ detailFormData.code }}
</el-descriptions-item>
<el-descriptions-item label="状态" :span="2">
<el-tag :type="detailFormData.status ? 'success' : 'danger'">
{{ detailFormData.status ? "启用" : "停用" }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="描述" :span="2">
{{ detailFormData.description }}
</el-descriptions-item>
<!-- <el-descriptions-item label="创建人" :span="2">
{{ detailFormData.created_by?.name }}
</el-descriptions-item> -->
<el-descriptions-item label="创建时间" :span="2">
{{ detailFormData.created_time }}
</el-descriptions-item>
<el-descriptions-item label="更新时间" :span="2">
{{ detailFormData.updated_time }}
</el-descriptions-item>
</el-descriptions>
</template>
<!-- 新增、编辑表单 -->
<template v-else>
<el-form
ref="dataFormRef"
:model="formData"
:rules="rules"
label-suffix=":"
label-width="auto"
label-position="right"
>
<el-form-item label="名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入名称" :maxlength="64" />
</el-form-item>
<el-form-item label="编码" prop="code">
<el-input v-model="formData.code" placeholder="请输入编码" :maxlength="20" />
</el-form-item>
<el-form-item label="状态" prop="status">
<el-radio-group v-model="formData.status">
<el-radio :value="0">启用</el-radio>
<el-radio :value="1">停用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input
v-model="formData.description"
:rows="4"
:maxlength="100"
show-word-limit
type="textarea"
placeholder="请输入描述"
/>
</el-form-item>
</el-form>
</template>
<template #footer>
<div class="dialog-footer">
<!-- 详情弹窗不需要确定按钮的提交逻辑 -->
<el-button @click="handleCloseDialog">取消</el-button>
<el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleSubmit">
确定
</el-button>
<el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
</div>
</template>
</el-dialog>
<!-- 导入弹窗 -->
<ImportModal
v-model="importDialogVisible"
:content-config="curdContentConfig"
@upload="handleUpload"
/>
<!-- 导出弹窗 -->
<ExportModal
v-model="exportsDialogVisible"
:content-config="curdContentConfig"
:query-params="queryFormData"
:page-data="pageTableData"
:selection-data="selectionRows"
/>
</div>
</template>
<script setup lang="ts">
defineOptions({
name: "Customer",
inheritAttrs: false,
});
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ResultEnum } from "@/enums/api/result.enum";
import ImportModal from "@/components/CURD/ImportModal.vue";
import ExportModal from "@/components/CURD/ExportModal.vue";
import DatePicker from "@/components/DatePicker/index.vue";
import type { IContentConfig } from "@/components/CURD/types";
import { QuestionFilled, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import { formatToDateTime } from "@/utils/dateUtil";
import CustomerAPI, { CustomerTable, CustomerForm, CustomerPageQuery } from "@/api/module_system/customer";
const visible = ref(true);
const queryFormRef = ref();
const dataFormRef = ref();
const total = ref(0);
const selectIds = ref<number[]>([]);
const selectionRows = ref<CustomerTable[]>([]);
const loading = ref(false);
const isExpand = ref(false);
const isExpandable = ref(true);
// 分页表单
const pageTableData = ref<CustomerTable[]>([]);
// 表格列配置
const tableColumns = ref([
{ prop: "selection", label: "选择框", show: true },
{ prop: "index", label: "序号", show: true },
{ prop: "name", label: "名称", show: true },
{ prop: "code", label: "编码", show: true },
{ prop: "status", label: "状态", show: true },
{ prop: "description", label: "描述", show: true },
{ prop: "created_time", label: "创建时间", show: true },
{ prop: "updated_time", label: "更新时间", show: true },
{ prop: "creator", label: "创建人", show: true },
{ prop: "operation", label: "操作", show: true },
]);
// 仅用于导出字段的列(排除非数据列及嵌套对象列)
const exportColumns = [
{ prop: "name", label: "名称" },
{ prop: "code", label: "编码" },
{ prop: "status", label: "状态" },
{ prop: "description", label: "描述" },
{ prop: "created_time", label: "创建时间" },
{ prop: "updated_time", label: "更新时间" },
];
// 导入/导出配置
const curdContentConfig = {
permPrefix: "module_system:customer",
cols: exportColumns as any,
importTemplate: () => CustomerAPI.downloadCustomer(),
exportsAction: async (params: any) => {
const query: any = { ...params };
if (typeof query.status === "string") {
query.status = query.status === "true";
}
query.page_no = 1;
query.page_size = 9999;
const all: any[] = [];
while (true) {
const res = await CustomerAPI.listCustomer(query);
const items = res.data?.data?.items || [];
const total = res.data?.data?.total || 0;
all.push(...items);
if (all.length >= total || items.length === 0) break;
query.page_no += 1;
}
return all;
},
} as unknown as IContentConfig;
// 详情表单
const detailFormData = ref<CustomerTable>({});
// 日期范围临时变量
const dateRange = ref<[Date, Date] | []>([]);
// 处理日期范围变化
function handleDateRangeChange(range: [Date, Date]) {
dateRange.value = range;
if (range && range.length === 2) {
queryFormData.created_time = [formatToDateTime(range[0]), formatToDateTime(range[1])];
} else {
queryFormData.created_time = undefined;
}
}
// 分页查询参数
const queryFormData = reactive<CustomerPageQuery>({
page_no: 1,
page_size: 10,
name: undefined,
status: undefined,
created_time: undefined,
});
// 编辑表单
const formData = reactive<CustomerForm>({
id: undefined,
name: "",
code: "",
status: "0",
description: undefined,
});
// 弹窗状态
const dialogVisible = reactive({
title: "",
visible: false,
type: "create" as "create" | "update" | "detail",
});
// 表单验证规则
const rules = reactive({
name: [{ required: true, message: "请输入名称", trigger: "blur" }],
code: [{ required: true, message: "请输入编码", trigger: "blur" }],
status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});
// 导入弹窗显示状态
const importDialogVisible = ref(false);
// 导出弹窗显示状态
const exportsDialogVisible = ref(false);
// 打开导入弹窗
function handleOpenImportDialog() {
importDialogVisible.value = true;
}
// 打开导出弹窗
function handleOpenExportsModal() {
exportsDialogVisible.value = true;
}
// 列表刷新
async function handleRefresh() {
await loadingData();
}
// 加载表格数据
async function loadingData() {
loading.value = true;
try {
const response = await CustomerAPI.listCustomer(queryFormData);
pageTableData.value = response.data.data.items;
total.value = response.data.data.total;
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
}
// 查询(重置页码后获取数据)
async function handleQuery() {
queryFormData.page_no = 1;
loadingData();
}
// 重置查询
async function handleResetQuery() {
queryFormRef.value.resetFields();
queryFormData.page_no = 1;
// 重置日期范围选择器
dateRange.value = [];
queryFormData.created_time = undefined;
loadingData();
}
// 定义初始表单数据常量
const initialFormData: CustomerForm = {
id: undefined,
name: "",
code: "",
status: "0",
description: "",
};
// 重置表单
async function resetForm() {
if (dataFormRef.value) {
dataFormRef.value.resetFields();
dataFormRef.value.clearValidate();
}
// 完全重置 formData 为初始状态
Object.assign(formData, initialFormData);
}
// 行复选框选中项变化
async function handleSelectionChange(selection: any) {
selectIds.value = selection.map((item: any) => item.id);
selectionRows.value = selection;
}
// 关闭弹窗
async function handleCloseDialog() {
dialogVisible.visible = false;
resetForm();
}
// 打开弹窗
async function handleOpenDialog(type: "create" | "update" | "detail", id?: number) {
dialogVisible.type = type;
if (id) {
const response = await CustomerAPI.detailCustomer(id);
if (type === "detail") {
dialogVisible.title = "详情";
Object.assign(detailFormData.value, response.data.data);
} else if (type === "update") {
dialogVisible.title = "修改";
Object.assign(formData, response.data.data);
}
} else {
dialogVisible.title = "新增客户";
formData.id = undefined;
}
dialogVisible.visible = true;
}
// 提交表单(防抖)
async function handleSubmit() {
// 表单校验
dataFormRef.value.validate(async (valid: any) => {
if (valid) {
loading.value = true;
// 根据弹窗传入的参数(deatil\create\update)判断走什么逻辑
const id = formData.id;
if (id) {
try {
await CustomerAPI.updateCustomer(id, { id, ...formData });
dialogVisible.visible = false;
resetForm();
handleCloseDialog();
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
} else {
try {
await CustomerAPI.createCustomer(formData);
dialogVisible.visible = false;
resetForm();
handleCloseDialog();
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
}
}
});
}
// 删除、批量删除
async function handleDelete(ids: number[]) {
ElMessageBox.confirm("确认删除该项数据?", "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
try {
loading.value = true;
await CustomerAPI.deleteCustomer(ids);
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
})
.catch(() => {
ElMessageBox.close();
});
}
// 批量启用/停用
async function handleMoreClick(status: string) {
if (selectIds.value.length) {
ElMessageBox.confirm(`确认${status === "0" ? "启用" : "停用"}该项数据?`, "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
try {
loading.value = true;
await CustomerAPI.batchCustomer({ ids: selectIds.value, status: status ? "1" : "0" });
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
})
.catch(() => {
ElMessageBox.close();
});
}
}
// 处理上传
const handleUpload = async (formData: FormData) => {
try {
const response = await CustomerAPI.importCustomer(formData);
if (response.data.code === ResultEnum.SUCCESS) {
ElMessage.success(`${response.data.msg},${response.data.data}`);
importDialogVisible.value = false;
await handleQuery();
}
} catch (error: any) {
console.error(error);
}
};
onMounted(() => {
loadingData();
});
</script>
<style lang="scss" scoped></style>
@@ -0,0 +1,757 @@
<!-- 租户 -->
<template>
<div class="app-container">
<!-- 搜索区域 -->
<div v-show="visible" class="search-container">
<el-form
ref="queryFormRef"
:model="queryFormData"
label-suffix=":"
:inline="true"
@submit.prevent="handleQuery"
>
<el-form-item prop="name" label="名称">
<el-input v-model="queryFormData.name" placeholder="请输入名称" clearable />
</el-form-item>
<el-form-item prop="status" label="状态">
<el-select
v-model="queryFormData.status"
placeholder="请选择状态"
style="width: 170px"
clearable
>
<el-option value="true" label="启用" />
<el-option value="false" label="停用" />
</el-select>
</el-form-item>
<el-form-item v-if="isExpand" prop="creator" label="创建人">
<UserTableSelect
v-model="queryFormData.created_id"
@confirm-click="handleConfirm"
@clear-click="handleQuery"
/>
</el-form-item>
<!-- 时间范围,收起状态下隐藏 -->
<el-form-item v-if="isExpand" prop="start_time" label="创建时间">
<DatePicker v-model="dateRange" @update:model-value="handleDateRangeChange" />
</el-form-item>
<!-- 查询、重置、展开/收起按钮 -->
<el-form-item>
<el-button
v-hasPerm="['module_system:tenant:query']"
type="primary"
icon="search"
@click="handleQuery"
>
查询
</el-button>
<el-button
v-hasPerm="['module_system:tenant:query']"
icon="refresh"
@click="handleResetQuery"
>
重置
</el-button>
<!-- 展开/收起 -->
<template v-if="isExpandable">
<el-link class="ml-3" type="primary" underline="never" @click="isExpand = !isExpand">
{{ isExpand ? "收起" : "展开" }}
<el-icon>
<template v-if="isExpand">
<ArrowUp />
</template>
<template v-else>
<ArrowDown />
</template>
</el-icon>
</el-link>
</template>
</el-form-item>
</el-form>
</div>
<!-- 内容区域 -->
<el-card class="data-table">
<template #header>
<div class="card-header">
<span>
租户列表
<el-tooltip content="租户列表">
<QuestionFilled class="w-4 h-4 mx-1" />
</el-tooltip>
</span>
</div>
</template>
<!-- 功能区域 -->
<div class="data-table__toolbar">
<div class="data-table__toolbar--left">
<el-row :gutter="10">
<el-col :span="1.5">
<el-button
v-hasPerm="['module_system:tenant:create']"
type="success"
icon="plus"
@click="handleOpenDialog('create')"
>
新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
v-hasPerm="['module_system:tenant:delete']"
type="danger"
icon="delete"
:disabled="selectIds.length === 0"
@click="handleDelete(selectIds)"
>
批量删除
</el-button>
</el-col>
<el-col :span="1.5">
<el-dropdown v-hasPerm="['module_system:tenant:batch']" trigger="click">
<el-button type="default" :disabled="selectIds.length === 0" icon="ArrowDown">
更多
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item icon="Check" @click="handleMoreClick('0')">
批量启用
</el-dropdown-item>
<el-dropdown-item icon="CircleClose" @click="handleMoreClick('1')">
批量停用
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</el-col>
</el-row>
</div>
<div class="data-table__toolbar--right">
<el-row :gutter="10">
<el-col :span="1.5">
<el-tooltip content="导入">
<el-button
v-hasPerm="['module_system:tenant:import']"
type="success"
icon="upload"
circle
@click="handleOpenImportDialog"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="导出">
<el-button
v-hasPerm="['module_system:tenant:export']"
type="warning"
icon="download"
circle
@click="handleOpenExportsModal"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="搜索显示/隐藏">
<el-button
v-hasPerm="['*:*:*']"
type="info"
icon="search"
circle
@click="visible = !visible"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="刷新">
<el-button
v-hasPerm="['module_system:tenant:query']"
type="primary"
icon="refresh"
circle
@click="handleRefresh"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-popover placement="bottom" trigger="click">
<template #reference>
<el-button type="danger" icon="operation" circle></el-button>
</template>
<el-scrollbar max-height="350px">
<template v-for="column in tableColumns" :key="column.prop">
<el-checkbox v-if="column.prop" v-model="column.show" :label="column.label" />
</template>
</el-scrollbar>
</el-popover>
</el-col>
</el-row>
</div>
</div>
<!-- 表格区域:系统配置列表 -->
<el-table
ref="tableRef"
v-loading="loading"
:data="pageTableData"
highlight-current-row
class="data-table__content"
:height="450"
border
stripe
@selection-change="handleSelectionChange"
>
<template #empty>
<el-empty :image-size="80" description="暂无数据" />
</template>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'selection')?.show"
type="selection"
min-width="55"
align="center"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'index')?.show"
fixed
label="序号"
min-width="60"
>
<template #default="scope">
{{ (queryFormData.page_no - 1) * queryFormData.page_size + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'name')?.show"
label="名称"
prop="name"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'code')?.show"
label="编码"
prop="code"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'status')?.show"
label="状态"
prop="status"
min-width="120"
>
<template #default="scope">
<el-tag :type="scope.row.status ? 'success' : 'info'">
{{ scope.row.status ? "启用" : "停用" }}
</el-tag>
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'description')?.show"
label="描述"
prop="description"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'created_time')?.show"
label="创建时间"
prop="created_time"
min-width="180"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'updated_time')?.show"
label="更新时间"
prop="updated_time"
min-width="180"
/>
<!-- <el-table-column v-if="tableColumns.find((col) => col.prop === 'creator')?.show" label="创建人" prop="creator" min-width="120">
<template #default="scope">
<el-tag>{{ scope.row.created_by?.name }}</el-tag>
</template>
</el-table-column> -->
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'operation')?.show"
fixed="right"
label="操作"
align="center"
min-width="180"
>
<template #default="scope">
<el-button
v-hasPerm="['module_system:tenant:query']"
type="info"
size="small"
link
icon="document"
@click="handleOpenDialog('detail', scope.row.id)"
>
详情
</el-button>
<el-button
v-hasPerm="['module_system:tenant:update']"
type="primary"
size="small"
link
icon="edit"
@click="handleOpenDialog('update', scope.row.id)"
>
编辑
</el-button>
<el-button
v-hasPerm="['module_system:tenant:delete']"
type="danger"
size="small"
link
icon="delete"
@click="handleDelete([scope.row.id])"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页区域 -->
<template #footer>
<pagination
v-model:total="total"
v-model:page="queryFormData.page_no"
v-model:limit="queryFormData.page_size"
@pagination="loadingData"
/>
</template>
</el-card>
<!-- 弹窗区域 -->
<el-dialog
v-model="dialogVisible.visible"
:title="dialogVisible.title"
@close="handleCloseDialog"
>
<!-- 详情 -->
<template v-if="dialogVisible.type === 'detail'">
<el-descriptions :column="4" border>
<el-descriptions-item label="名称" :span="2">
{{ detailFormData.name }}
</el-descriptions-item>
<el-descriptions-item label="编码" :span="2">
{{ detailFormData.code }}
</el-descriptions-item>
<el-descriptions-item label="状态" :span="2">
<el-tag :type="detailFormData.status ? 'success' : 'danger'">
{{ detailFormData.status ? "启用" : "停用" }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="描述" :span="2">
{{ detailFormData.description }}
</el-descriptions-item>
<!-- <el-descriptions-item label="创建人" :span="2">
{{ detailFormData.created_by?.name }}
</el-descriptions-item> -->
<el-descriptions-item label="创建时间" :span="2">
{{ detailFormData.created_time }}
</el-descriptions-item>
<el-descriptions-item label="更新时间" :span="2">
{{ detailFormData.updated_time }}
</el-descriptions-item>
</el-descriptions>
</template>
<!-- 新增、编辑表单 -->
<template v-else>
<el-form
ref="dataFormRef"
:model="formData"
:rules="rules"
label-suffix=":"
label-width="auto"
label-position="right"
>
<el-form-item label="名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入名称" :maxlength="64" />
</el-form-item>
<el-form-item label="编码" prop="code">
<el-input v-model="formData.code" placeholder="请输入编码" :maxlength="20" />
</el-form-item>
<el-form-item label="状态" prop="status">
<el-radio-group v-model="formData.status">
<el-radio :value="0">启用</el-radio>
<el-radio :value="1">停用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input
v-model="formData.description"
:rows="4"
:maxlength="100"
show-word-limit
type="textarea"
placeholder="请输入描述"
/>
</el-form-item>
</el-form>
</template>
<template #footer>
<div class="dialog-footer">
<!-- 详情弹窗不需要确定按钮的提交逻辑 -->
<el-button @click="handleCloseDialog">取消</el-button>
<el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleSubmit">
确定
</el-button>
<el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
</div>
</template>
</el-dialog>
<!-- 导入弹窗 -->
<ImportModal
v-model="importDialogVisible"
:content-config="curdContentConfig"
@upload="handleUpload"
/>
<!-- 导出弹窗 -->
<ExportModal
v-model="exportsDialogVisible"
:content-config="curdContentConfig"
:query-params="queryFormData"
:page-data="pageTableData"
:selection-data="selectionRows"
/>
</div>
</template>
<script setup lang="ts">
defineOptions({
name: "Tenant",
inheritAttrs: false,
});
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ResultEnum } from "@/enums/api/result.enum";
import ImportModal from "@/components/CURD/ImportModal.vue";
import ExportModal from "@/components/CURD/ExportModal.vue";
import DatePicker from "@/components/DatePicker/index.vue";
import type { IContentConfig } from "@/components/CURD/types";
import { QuestionFilled, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import { formatToDateTime } from "@/utils/dateUtil";
import TenantAPI, { TenantTable, TenantForm, TenantPageQuery } from "@/api/module_system/tenant";
const visible = ref(true);
const queryFormRef = ref();
const dataFormRef = ref();
const total = ref(0);
const selectIds = ref<number[]>([]);
const selectionRows = ref<TenantTable[]>([]);
const loading = ref(false);
const isExpand = ref(false);
const isExpandable = ref(true);
// 分页表单
const pageTableData = ref<TenantTable[]>([]);
// 表格列配置
const tableColumns = ref([
{ prop: "selection", label: "选择框", show: true },
{ prop: "index", label: "序号", show: true },
{ prop: "name", label: "名称", show: true },
{ prop: "code", label: "编码", show: true },
{ prop: "status", label: "状态", show: true },
{ prop: "description", label: "描述", show: true },
{ prop: "created_time", label: "创建时间", show: true },
{ prop: "updated_time", label: "更新时间", show: true },
{ prop: "creator", label: "创建人", show: true },
{ prop: "operation", label: "操作", show: true },
]);
// 仅用于导出字段的列(排除非数据列及嵌套对象列)
const exportColumns = [
{ prop: "name", label: "名称" },
{ prop: "code", label: "编码" },
{ prop: "status", label: "状态" },
{ prop: "description", label: "描述" },
{ prop: "created_time", label: "创建时间" },
{ prop: "updated_time", label: "更新时间" },
];
// 导入/导出配置
const curdContentConfig = {
permPrefix: "module_system:tenant",
cols: exportColumns as any,
importTemplate: () => TenantAPI.downloadTenant(),
exportsAction: async (params: any) => {
const query: any = { ...params };
if (typeof query.status === "string") {
query.status = query.status === "true";
}
query.page_no = 1;
query.page_size = 9999;
const all: any[] = [];
while (true) {
const res = await TenantAPI.listTenant(query);
const items = res.data?.data?.items || [];
const total = res.data?.data?.total || 0;
all.push(...items);
if (all.length >= total || items.length === 0) break;
query.page_no += 1;
}
return all;
},
} as unknown as IContentConfig;
// 详情表单
const detailFormData = ref<TenantTable>({});
// 日期范围临时变量
const dateRange = ref<[Date, Date] | []>([]);
// 处理日期范围变化
function handleDateRangeChange(range: [Date, Date]) {
dateRange.value = range;
if (range && range.length === 2) {
queryFormData.created_time = [formatToDateTime(range[0]), formatToDateTime(range[1])];
} else {
queryFormData.created_time = undefined;
}
}
// 分页查询参数
const queryFormData = reactive<TenantPageQuery>({
page_no: 1,
page_size: 10,
name: undefined,
status: undefined,
created_time: undefined, created_id: undefined,
});
// 编辑表单
const formData = reactive<TenantForm>({
id: undefined,
name: "",
code: "",
status: '0',
description: undefined,
});
// 弹窗状态
const dialogVisible = reactive({
title: "",
visible: false,
type: "create" as "create" | "update" | "detail",
});
// 表单验证规则
const rules = reactive({
name: [{ required: true, message: "请输入名称", trigger: "blur" }],
code: [{ required: true, message: "请输入编码", trigger: "blur" }],
status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});
// 导入弹窗显示状态
const importDialogVisible = ref(false);
// 导出弹窗显示状态
const exportsDialogVisible = ref(false);
// 打开导入弹窗
function handleOpenImportDialog() {
importDialogVisible.value = true;
}
// 打开导出弹窗
function handleOpenExportsModal() {
exportsDialogVisible.value = true;
}
// 列表刷新
async function handleRefresh() {
await loadingData();
}
// 加载表格数据
async function loadingData() {
loading.value = true;
try {
const response = await TenantAPI.listTenant(queryFormData);
pageTableData.value = response.data.data.items;
total.value = response.data.data.total;
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
}
// 查询(重置页码后获取数据)
async function handleQuery() {
queryFormData.page_no = 1;
loadingData();
}
// 选择创建人后触发查询
function handleConfirm() {
handleQuery();
}
// 重置查询
async function handleResetQuery() {
queryFormRef.value.resetFields();
queryFormData.page_no = 1;
// 重置日期范围选择器
dateRange.value = [];
queryFormData.created_time = undefined;
loadingData();
}
// 定义初始表单数据常量
const initialFormData: TenantForm = {
id: undefined,
name: "",
code: "",
status: '0',
description: "",
};
// 重置表单
async function resetForm() {
if (dataFormRef.value) {
dataFormRef.value.resetFields();
dataFormRef.value.clearValidate();
}
// 完全重置 formData 为初始状态
Object.assign(formData, initialFormData);
}
// 行复选框选中项变化
async function handleSelectionChange(selection: any) {
selectIds.value = selection.map((item: any) => item.id);
selectionRows.value = selection;
}
// 关闭弹窗
async function handleCloseDialog() {
dialogVisible.visible = false;
resetForm();
}
// 打开弹窗
async function handleOpenDialog(type: "create" | "update" | "detail", id?: number) {
dialogVisible.type = type;
if (id) {
const response = await TenantAPI.detailTenant(id);
if (type === "detail") {
dialogVisible.title = "详情";
Object.assign(detailFormData.value, response.data.data);
} else if (type === "update") {
dialogVisible.title = "修改";
Object.assign(formData, response.data.data);
}
} else {
dialogVisible.title = "新增租户";
formData.id = undefined;
}
dialogVisible.visible = true;
}
// 提交表单(防抖)
async function handleSubmit() {
// 表单校验
dataFormRef.value.validate(async (valid: any) => {
if (valid) {
loading.value = true;
// 根据弹窗传入的参数(deatil\create\update)判断走什么逻辑
const id = formData.id;
if (id) {
try {
await TenantAPI.updateTenant(id, { id, ...formData });
dialogVisible.visible = false;
resetForm();
handleCloseDialog();
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
} else {
try {
await TenantAPI.createTenant(formData);
dialogVisible.visible = false;
resetForm();
handleCloseDialog();
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
}
}
});
}
// 删除、批量删除
async function handleDelete(ids: number[]) {
ElMessageBox.confirm("确认删除该项数据?", "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
try {
loading.value = true;
await TenantAPI.deleteTenant(ids);
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
})
.catch(() => {
ElMessageBox.close();
});
}
// 批量启用/停用
async function handleMoreClick(status: string) {
if (selectIds.value.length) {
ElMessageBox.confirm(`确认${status === "0" ? "启用" : "停用"}该项数据?`, "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
try {
loading.value = true;
await TenantAPI.batchTenant({ ids: selectIds.value, status });
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
})
.catch(() => {
ElMessageBox.close();
});
}
}
// 处理上传
const handleUpload = async (formData: FormData) => {
try {
const response = await TenantAPI.importTenant(formData);
if (response.data.code === ResultEnum.SUCCESS) {
ElMessage.success(`${response.data.msg},${response.data.data}`);
importDialogVisible.value = false;
await handleQuery();
}
} catch (error: any) {
console.error(error);
}
};
onMounted(() => {
loadingData();
});
</script>
<style lang="scss" scoped></style>
@@ -0,0 +1,793 @@
<!-- 演示示例 -->
<template>
<div class="app-container">
<!-- 搜索区域 -->
<div v-show="visible" class="search-container">
<el-form
ref="queryFormRef"
:model="queryFormData"
label-suffix=":"
:inline="true"
@submit.prevent="handleQuery"
>
<el-form-item prop="name" label="名称">
<el-input v-model="queryFormData.name" placeholder="请输入名称" clearable />
</el-form-item>
<el-form-item prop="status" label="状态">
<el-select
v-model="queryFormData.status"
placeholder="请选择状态"
style="width: 170px"
clearable
>
<el-option value="0" label="启用" />
<el-option value="1" label="停用" />
</el-select>
</el-form-item>
<el-form-item v-if="isExpand" prop="created_id" label="创建人">
<UserTableSelect
v-model="queryFormData.created_id"
@confirm-click="handleConfirm"
@clear-click="handleQuery"
/>
</el-form-item>
<el-form-item v-if="isExpand" prop="updated_id" label="更新人">
<UserTableSelect
v-model="queryFormData.updated_id"
@confirm-click="handleConfirm"
@clear-click="handleQuery"
/>
</el-form-item>
<!-- 时间范围,收起状态下隐藏 -->
<el-form-item v-if="isExpand" prop="created_time" label="创建时间">
<DatePicker
v-model="createdDateRange"
@update:model-value="handleCreatedDateRangeChange"
/>
</el-form-item>
<el-form-item v-if="isExpand" prop="updated_time" label="更新时间">
<DatePicker
v-model="updatedDateRange"
@update:model-value="handleUpdatedDateRangeChange"
/>
</el-form-item>
<!-- 查询、重置、展开/收起按钮 -->
<el-form-item>
<el-button
v-hasPerm="['module_system:token:query']"
type="primary"
icon="search"
@click="handleQuery"
>
查询
</el-button>
<el-button
v-hasPerm="['module_system:token:query']"
icon="refresh"
@click="handleResetQuery"
>
重置
</el-button>
<!-- 展开/收起 -->
<template v-if="isExpandable">
<el-link class="ml-3" type="primary" underline="never" @click="isExpand = !isExpand">
{{ isExpand ? "收起" : "展开" }}
<el-icon>
<template v-if="isExpand">
<ArrowUp />
</template>
<template v-else>
<ArrowDown />
</template>
</el-icon>
</el-link>
</template>
</el-form-item>
</el-form>
</div>
<!-- 内容区域 -->
<el-card class="data-table">
<template #header>
<div class="card-header">
<span>
演示示例列表
<el-tooltip content="演示示例列表">
<QuestionFilled class="w-4 h-4 mx-1" />
</el-tooltip>
</span>
</div>
</template>
<!-- 功能区域 -->
<div class="data-table__toolbar">
<div class="data-table__toolbar--left">
<el-row :gutter="10">
<el-col :span="1.5">
<el-button
v-hasPerm="['module_system:token:create']"
type="success"
icon="plus"
@click="handleOpenDialog('create')"
>
新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
v-hasPerm="['module_system:token:delete']"
type="danger"
icon="delete"
:disabled="selectIds.length === 0"
@click="handleDelete(selectIds)"
>
批量删除
</el-button>
</el-col>
<el-col :span="1.5">
<el-dropdown v-hasPerm="['module_system:token:patch']" trigger="click">
<el-button type="default" :disabled="selectIds.length === 0" icon="ArrowDown">
更多
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item icon="Check" @click="handleMoreClick('0')">
批量启用
</el-dropdown-item>
<el-dropdown-item icon="CircleClose" @click="handleMoreClick('1')">
批量停用
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</el-col>
</el-row>
</div>
<div class="data-table__toolbar--right">
<el-row :gutter="10">
<el-col :span="1.5">
<el-tooltip content="导入">
<el-button
v-hasPerm="['module_system:token:import']"
type="success"
icon="upload"
circle
@click="handleOpenImportDialog"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="导出">
<el-button
v-hasPerm="['module_system:token:export']"
type="warning"
icon="download"
circle
@click="handleOpenExportsModal"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="搜索显示/隐藏">
<el-button
v-hasPerm="['*:*:*']"
type="info"
icon="search"
circle
@click="visible = !visible"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-tooltip content="刷新">
<el-button
v-hasPerm="['module_system:token:query']"
type="primary"
icon="refresh"
circle
@click="handleRefresh"
/>
</el-tooltip>
</el-col>
<el-col :span="1.5">
<el-popover placement="bottom" trigger="click">
<template #reference>
<el-button type="danger" icon="operation" circle></el-button>
</template>
<el-scrollbar max-height="350px">
<template v-for="column in tableColumns" :key="column.prop">
<el-checkbox v-if="column.prop" v-model="column.show" :label="column.label" />
</template>
</el-scrollbar>
</el-popover>
</el-col>
</el-row>
</div>
</div>
<!-- 表格区域:系统配置列表 -->
<el-table
ref="tableRef"
v-loading="loading"
:data="pageTableData"
highlight-current-row
class="data-table__content"
height="500"
max-height="500"
border
stripe
@selection-change="handleSelectionChange"
>
<template #empty>
<el-empty :image-size="80" description="暂无数据" />
</template>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'selection')?.show"
type="selection"
min-width="55"
align="center"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'index')?.show"
fixed
label="序号"
min-width="60"
>
<template #default="scope">
{{ (queryFormData.page_no - 1) * queryFormData.page_size + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'name')?.show"
label="名称"
prop="name"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'status')?.show"
label="状态"
prop="status"
min-width="120"
>
<template #default="scope">
<el-tag :type="scope.row.status ? 'success' : 'info'">
{{ scope.row.status ? "启用" : "停用" }}
</el-tag>
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'description')?.show"
label="描述"
prop="description"
min-width="140"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'created_time')?.show"
label="创建时间"
prop="created_time"
min-width="180"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'updated_time')?.show"
label="更新时间"
prop="updated_time"
min-width="180"
/>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'created_id')?.show"
label="创建人"
prop="created_id"
min-width="120"
>
<template #default="scope">
<el-tag>{{ scope.row.created_by?.name }}</el-tag>
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'updated_id')?.show"
label="更新人"
prop="updated_id"
min-width="120"
>
<template #default="scope">
<el-tag>{{ scope.row.updated_by?.name }}</el-tag>
</template>
</el-table-column>
<el-table-column
v-if="tableColumns.find((col) => col.prop === 'operation')?.show"
fixed="right"
label="操作"
align="center"
min-width="180"
>
<template #default="scope">
<el-button
v-hasPerm="['module_system:token:query']"
type="info"
size="small"
link
icon="document"
@click="handleOpenDialog('detail', scope.row.id)"
>
详情
</el-button>
<el-button
v-hasPerm="['module_system:token:update']"
type="primary"
size="small"
link
icon="edit"
@click="handleOpenDialog('update', scope.row.id)"
>
编辑
</el-button>
<el-button
v-hasPerm="['module_system:token:delete']"
type="danger"
size="small"
link
icon="delete"
@click="handleDelete([scope.row.id])"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页区域 -->
<template #footer>
<pagination
v-model:total="total"
v-model:page="queryFormData.page_no"
v-model:limit="queryFormData.page_size"
@pagination="loadingData"
/>
</template>
</el-card>
<!-- 弹窗区域 -->
<el-dialog
v-model="dialogVisible.visible"
:title="dialogVisible.title"
@close="handleCloseDialog"
>
<!-- 详情 -->
<template v-if="dialogVisible.type === 'detail'">
<el-descriptions :column="4" border>
<el-descriptions-item label="名称" :span="2">
{{ detailFormData.name }}
</el-descriptions-item>
<el-descriptions-item label="状态" :span="2">
<el-tag :type="detailFormData.status ? 'success' : 'danger'">
{{ detailFormData.status ? "启用" : "停用" }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="描述" :span="2">
{{ detailFormData.description }}
</el-descriptions-item>
<el-descriptions-item label="创建人" :span="2">
{{ detailFormData.created_by?.name }}
</el-descriptions-item>
<el-descriptions-item label="更新人" :span="2">
{{ detailFormData.updated_by?.name }}
</el-descriptions-item>
<el-descriptions-item label="创建时间" :span="2">
{{ detailFormData.created_time }}
</el-descriptions-item>
<el-descriptions-item label="更新时间" :span="2">
{{ detailFormData.updated_time }}
</el-descriptions-item>
</el-descriptions>
</template>
<!-- 新增、编辑表单 -->
<template v-else>
<el-form
ref="dataFormRef"
:model="formData"
:rules="rules"
label-suffix=":"
label-width="auto"
label-position="right"
>
<el-form-item label="名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入名称" :maxlength="50" />
</el-form-item>
<el-form-item label="状态" prop="status">
<el-radio-group v-model="formData.status">
<el-radio value="0">启用</el-radio>
<el-radio value="1">停用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input
v-model="formData.description"
:rows="4"
:maxlength="100"
show-word-limit
type="textarea"
placeholder="请输入描述"
/>
</el-form-item>
</el-form>
</template>
<template #footer>
<div class="dialog-footer">
<!-- 详情弹窗不需要确定按钮的提交逻辑 -->
<el-button @click="handleCloseDialog">取消</el-button>
<el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleSubmit">
确定
</el-button>
<el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
</div>
</template>
</el-dialog>
<!-- 导入弹窗 -->
<ImportModal
v-model="importDialogVisible"
:content-config="curdContentConfig"
@upload="handleUpload"
/>
<!-- 导出弹窗 -->
<ExportModal
v-model="exportsDialogVisible"
:content-config="curdContentConfig"
:query-params="queryFormData"
:page-data="pageTableData"
:selection-data="selectionRows"
/>
</div>
</template>
<script setup lang="ts">
defineOptions({
name: "Token",
inheritAttrs: false,
});
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ResultEnum } from "@/enums/api/result.enum";
import TokenAPI, { TokenTable, TokenForm, TokenPageQuery } from "@/api/module_system/token";
import ImportModal from "@/components/CURD/ImportModal.vue";
import ExportModal from "@/components/CURD/ExportModal.vue";
import DatePicker from "@/components/DatePicker/index.vue";
import type { IContentConfig } from "@/components/CURD/types";
import { QuestionFilled, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import { formatToDateTime } from "@/utils/dateUtil";
const visible = ref(true);
const queryFormRef = ref();
const dataFormRef = ref();
const total = ref(0);
const selectIds = ref<number[]>([]);
const selectionRows = ref<TokenTable[]>([]);
const loading = ref(false);
const isExpand = ref(false);
const isExpandable = ref(true);
// 分页表单
const pageTableData = ref<TokenTable[]>([]);
// 表格列配置
const tableColumns = ref([
{ prop: "selection", label: "选择框", show: true },
{ prop: "index", label: "序号", show: true },
{ prop: "name", label: "名称", show: true },
{ prop: "status", label: "状态", show: true },
{ prop: "description", label: "描述", show: true },
{ prop: "created_time", label: "创建时间", show: true },
{ prop: "updated_time", label: "更新时间", show: true },
{ prop: "created_id", label: "创建人", show: true },
{ prop: "updated_id", label: "更新人", show: true },
{ prop: "operation", label: "操作", show: true },
]);
// 仅用于导出字段的列(排除非数据列及嵌套对象列)
const exportColumns = [
{ prop: "name", label: "名称" },
{ prop: "status", label: "状态" },
{ prop: "description", label: "描述" },
{ prop: "created_time", label: "创建时间" },
{ prop: "updated_time", label: "更新时间" },
];
// 导入/导出配置
const curdContentConfig = {
permPrefix: "module_system:token",
cols: exportColumns as any,
importTemplate: () => TokenAPI.downloadTemplateToken(),
exportsAction: async (params: any) => {
const query: any = { ...params };
if (typeof query.status === "string") {
query.status = query.status === "true";
}
query.page_no = 1;
query.page_size = 9999;
const all: any[] = [];
while (true) {
const res = await TokenAPI.getTokenList(query);
const items = res.data?.data?.items || [];
const total = res.data?.data?.total || 0;
all.push(...items);
if (all.length >= total || items.length === 0) break;
query.page_no += 1;
}
return all;
},
} as unknown as IContentConfig;
// 详情表单
const detailFormData = ref<TokenTable>({});
// 日期范围临时变量
const createdDateRange = ref<[Date, Date] | []>([]);
// 更新时间范围临时变量
const updatedDateRange = ref<[Date, Date] | []>([]);
// 处理创建时间范围变化
function handleCreatedDateRangeChange(range: [Date, Date]) {
createdDateRange.value = range;
if (range && range.length === 2) {
queryFormData.created_time = [formatToDateTime(range[0]), formatToDateTime(range[1])];
} else {
queryFormData.created_time = undefined;
}
}
// 处理更新时间范围变化
function handleUpdatedDateRangeChange(range: [Date, Date]) {
updatedDateRange.value = range;
if (range && range.length === 2) {
queryFormData.updated_time = [formatToDateTime(range[0]), formatToDateTime(range[1])];
} else {
queryFormData.updated_time = undefined;
}
}
// 分页查询参数
const queryFormData = reactive<TokenPageQuery>({
page_no: 1,
page_size: 10,
name: undefined,
status: undefined,
created_time: undefined,
updated_time: undefined,
created_id: undefined,
updated_id: undefined,
});
// 编辑表单
const formData = reactive<TokenForm>({
id: undefined,
name: "",
status: "0",
description: undefined,
});
// 弹窗状态
const dialogVisible = reactive({
title: "",
visible: false,
type: "create" as "create" | "update" | "detail",
});
// 表单验证规则
const rules = reactive({
name: [{ required: true, message: "请输入名称", trigger: "blur" }],
status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});
// 导入弹窗显示状态
const importDialogVisible = ref(false);
// 导出弹窗显示状态
const exportsDialogVisible = ref(false);
// 打开导入弹窗
function handleOpenImportDialog() {
importDialogVisible.value = true;
}
// 打开导出弹窗
function handleOpenExportsModal() {
exportsDialogVisible.value = true;
}
// 列表刷新
async function handleRefresh() {
await loadingData();
}
// 加载表格数据
async function loadingData() {
loading.value = true;
try {
const response = await TokenAPI.getTokenList(queryFormData);
pageTableData.value = response.data.data.items;
total.value = response.data.data.total;
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
}
// 查询(重置页码后获取数据)
async function handleQuery() {
queryFormData.page_no = 1;
loadingData();
}
// 选择创建人后触发查询
function handleConfirm() {
handleQuery();
}
// 重置查询
async function handleResetQuery() {
queryFormRef.value.resetFields();
queryFormData.page_no = 1;
// 重置日期范围选择器
createdDateRange.value = [];
updatedDateRange.value = [];
queryFormData.created_time = undefined;
queryFormData.updated_time = undefined;
loadingData();
}
// 定义初始表单数据常量
const initialFormData: TokenForm = {
id: undefined,
name: "",
status: "0",
description: "",
};
// 重置表单
async function resetForm() {
if (dataFormRef.value) {
dataFormRef.value.resetFields();
dataFormRef.value.clearValidate();
}
// 完全重置 formData 为初始状态
Object.assign(formData, initialFormData);
}
// 行复选框选中项变化
async function handleSelectionChange(selection: any) {
selectIds.value = selection.map((item: any) => item.id);
selectionRows.value = selection;
}
// 关闭弹窗
async function handleCloseDialog() {
dialogVisible.visible = false;
resetForm();
}
// 打开弹窗
async function handleOpenDialog(type: "create" | "update" | "detail", id?: number) {
dialogVisible.type = type;
if (id) {
const response = await TokenAPI.getTokenDetail(id);
if (type === "detail") {
dialogVisible.title = "详情";
Object.assign(detailFormData.value, response.data.data);
} else if (type === "update") {
dialogVisible.title = "修改";
Object.assign(formData, response.data.data);
}
} else {
dialogVisible.title = "新增令牌";
formData.id = undefined;
}
dialogVisible.visible = true;
}
// 提交表单(防抖)
async function handleSubmit() {
// 表单校验
dataFormRef.value.validate(async (valid: any) => {
if (valid) {
loading.value = true;
// 根据弹窗传入的参数(deatil\create\update)判断走什么逻辑
const id = formData.id;
if (id) {
try {
await TokenAPI.updateToken(id, { id, ...formData });
dialogVisible.visible = false;
resetForm();
handleCloseDialog();
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
} else {
try {
await TokenAPI.createToken(formData);
dialogVisible.visible = false;
resetForm();
handleCloseDialog();
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
}
}
});
}
// 删除、批量删除
async function handleDelete(ids: number[]) {
ElMessageBox.confirm("确认删除该项数据?", "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
try {
loading.value = true;
await TokenAPI.deleteToken(ids);
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
})
.catch(() => {
ElMessageBox.close();
});
}
// 批量启用/停用
async function handleMoreClick(status: string) {
if (selectIds.value.length) {
ElMessageBox.confirm(`确认${status === "0" ? "启用" : "停用"}该项数据?`, "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(async () => {
try {
loading.value = true;
await TokenAPI.batchToken({ ids: selectIds.value, status });
handleResetQuery();
} catch (error: any) {
console.error(error);
} finally {
loading.value = false;
}
})
.catch(() => {
ElMessageBox.close();
});
}
}
// 处理上传
const handleUpload = async (formData: FormData) => {
try {
const response = await TokenAPI.importToken(formData);
if (response.data.code === ResultEnum.SUCCESS) {
ElMessage.success(`${response.data.msg},${response.data.data}`);
importDialogVisible.value = false;
await handleQuery();
}
} catch (error: any) {
console.error(error);
}
};
onMounted(() => {
loadingData();
});
</script>
<style lang="scss" scoped></style>