feat: enforce required department and role codes with validation

- Updated DeptModel and RoleModel to make the `code` field mandatory and unique.
- Enhanced DeptCreateSchema and RoleCreateSchema to require a valid `code` format, ensuring it starts with a letter and is 2-16 characters long.
- Implemented validation logic in the backend to check for existing codes during updates, preventing duplicates.
- Adjusted frontend forms to reflect the required `code` field and added validation messages for user guidance.
This commit is contained in:
zhangtao
2026-04-04 02:16:53 +08:00
parent 8397c305bd
commit 1255729cd4
13 changed files with 103 additions and 43 deletions
@@ -74,8 +74,8 @@ class RoleModel(ModelMixin):
__permission_strategy__: PermissionFilterStrategy = PermissionFilterStrategy.USER_ROLE
name: Mapped[str] = mapped_column(String(64), nullable=False, comment="角色名称")
code: Mapped[str | None] = mapped_column(
String(16), nullable=True, index=True, comment="角色编码"
code: Mapped[str] = mapped_column(
String(16), nullable=False, unique=True, comment="角色编码"
)
order: Mapped[int] = mapped_column(Integer, nullable=False, default=999, comment="显示排序")
data_scope: Mapped[int] = mapped_column(
@@ -13,8 +13,8 @@ from app.common.enums import QueueEnum
from app.core.base_schema import BaseSchema
from app.core.validator import (
DateTimeStr,
code_validator,
role_permission_request_validator,
validate_required_code,
)
@@ -22,7 +22,7 @@ class RoleCreateSchema(BaseModel):
"""角色创建模型"""
name: str = Field(..., max_length=64, description="角色名称")
code: str | None = Field(default=None, max_length=16, description="角色编码")
code: str = Field(..., max_length=16, description="角色编码")
order: int | None = Field(default=1, ge=1, description="显示排序")
data_scope: int | None = Field(
default=1,
@@ -33,20 +33,20 @@ class RoleCreateSchema(BaseModel):
@field_validator("code")
@classmethod
def validate_code(cls, value: str | None):
def validate_code(cls, value: str):
"""
校验角色编码(委托到 `code_validator`)。
校验角色编码(与部门编码规则一致,见 `validate_required_code`)。
参数:
- value (str | None): 角色编码。
- value (str): 角色编码。
返回:
- str | None: 校验后的角色编码。
- str: 校验后的角色编码。
异常:
- CustomException: 不满足编码规则时抛出。
- ValueError: 不满足编码规则时抛出。
"""
return code_validator(value)
return validate_required_code(value)
class RolePermissionSettingSchema(BaseModel):
@@ -125,6 +125,9 @@ class RoleService:
exist_role = await RoleCRUD(auth).get(name=data.name)
if exist_role and exist_role.id != id:
raise CustomException(msg="更新失败,角色名称重复")
exist_code = await RoleCRUD(auth).get(code=data.code)
if exist_code and exist_code.id != id:
raise CustomException(msg="更新失败,角色编码已存在")
updated_role = await RoleCRUD(auth).update(id=id, data=data)
return RoleOutSchema.model_validate(updated_role).model_dump()