完善项目权限前置依赖保存校验
- 以接口权限定义中的 prerequisite_permissions 作为前置依赖单一事实源,生成运行时前置权限映射\n- 保存项目角色权限前预检缺失前置权限与受影响下游权限,未确认时返回 409 调整详情\n- 确认保存时自动合并补齐前置权限与取消下游权限,并提供有效权限矩阵读取接口\n- 前端角色权限编辑改为保存时执行依赖校验,弹窗展示需补充前置权限和受影响下游权限\n- 新增编辑权限取消按钮,清理权限选择即时确认弹窗残留\n- 补充后端接口测试、前端权限编辑测试与优化设计文档
This commit is contained in:
@@ -12,6 +12,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
from app.core.deps import get_current_user, get_db_session, is_system_admin, require_study_member, require_system_permission
|
from app.core.deps import get_current_user, get_db_session, is_system_admin, require_study_member, require_system_permission
|
||||||
from app.core.project_permissions import (
|
from app.core.project_permissions import (
|
||||||
get_api_endpoint_permissions,
|
get_api_endpoint_permissions,
|
||||||
|
get_effective_api_endpoint_permissions,
|
||||||
|
PrerequisitePermissionConfirmationRequired,
|
||||||
replace_api_endpoint_permissions,
|
replace_api_endpoint_permissions,
|
||||||
get_missing_prerequisites,
|
get_missing_prerequisites,
|
||||||
)
|
)
|
||||||
@@ -173,7 +175,7 @@ async def get_my_study_api_permissions(
|
|||||||
|
|
||||||
membership = await member_crud.get_member(db, study_id, current_user.id)
|
membership = await member_crud.get_member(db, study_id, current_user.id)
|
||||||
role = membership.role_in_study if membership and membership.is_active else ""
|
role = membership.role_in_study if membership and membership.is_active else ""
|
||||||
permissions = await get_api_endpoint_permissions(db, study_id)
|
permissions = await get_effective_api_endpoint_permissions(db, study_id)
|
||||||
role_permissions = permissions.get(role, {})
|
role_permissions = permissions.get(role, {})
|
||||||
return {
|
return {
|
||||||
role: {
|
role: {
|
||||||
@@ -232,6 +234,7 @@ async def get_study_api_permissions(
|
|||||||
async def update_study_api_permissions(
|
async def update_study_api_permissions(
|
||||||
study_id: uuid.UUID,
|
study_id: uuid.UUID,
|
||||||
payload: dict[str, dict[str, bool]],
|
payload: dict[str, dict[str, bool]],
|
||||||
|
confirm_prerequisite_adjustments: bool = False,
|
||||||
_=Depends(require_system_permission("system:permissions:project_config")),
|
_=Depends(require_system_permission("system:permissions:project_config")),
|
||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
||||||
@@ -259,7 +262,22 @@ async def update_study_api_permissions(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# 替换权限配置
|
# 替换权限配置
|
||||||
await replace_api_endpoint_permissions(db, study_id, payload)
|
try:
|
||||||
|
await replace_api_endpoint_permissions(
|
||||||
|
db,
|
||||||
|
study_id,
|
||||||
|
payload,
|
||||||
|
confirm_prerequisite_adjustments=confirm_prerequisite_adjustments,
|
||||||
|
)
|
||||||
|
except PrerequisitePermissionConfirmationRequired as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail={
|
||||||
|
"code": "PREREQUISITE_PERMISSION_CONFIRMATION_REQUIRED",
|
||||||
|
"message": "需要确认前置权限调整",
|
||||||
|
"adjustments": exc.adjustments,
|
||||||
|
},
|
||||||
|
) from exc
|
||||||
|
|
||||||
# 返回更新后的权限矩阵
|
# 返回更新后的权限矩阵
|
||||||
permissions = await get_api_endpoint_permissions(db, study_id)
|
permissions = await get_api_endpoint_permissions(db, study_id)
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ API_ENDPOINT_PERMISSIONS = {
|
|||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "创建参与者",
|
"description": "创建参与者",
|
||||||
"default_roles": ["PM", "CRA"],
|
"default_roles": ["PM", "CRA"],
|
||||||
"prerequisite_permissions": ["sites:read"],
|
"prerequisite_permissions": ["subjects:read", "sites:read"],
|
||||||
},
|
},
|
||||||
"subjects:read": {
|
"subjects:read": {
|
||||||
"module": "subjects",
|
"module": "subjects",
|
||||||
@@ -50,14 +50,14 @@ API_ENDPOINT_PERMISSIONS = {
|
|||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "更新参与者",
|
"description": "更新参与者",
|
||||||
"default_roles": ["PM", "CRA"],
|
"default_roles": ["PM", "CRA"],
|
||||||
"prerequisite_permissions": ["sites:read"],
|
"prerequisite_permissions": ["subjects:read", "sites:read"],
|
||||||
},
|
},
|
||||||
"subjects:delete": {
|
"subjects:delete": {
|
||||||
"module": "subjects",
|
"module": "subjects",
|
||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "删除参与者",
|
"description": "删除参与者",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
"prerequisite_permissions": ["sites:read"],
|
"prerequisite_permissions": ["subjects:read", "sites:read"],
|
||||||
},
|
},
|
||||||
# 访视管理 (visits)
|
# 访视管理 (visits)
|
||||||
"visits:create": {
|
"visits:create": {
|
||||||
@@ -94,7 +94,7 @@ API_ENDPOINT_PERMISSIONS = {
|
|||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "创建参与者AE",
|
"description": "创建参与者AE",
|
||||||
"default_roles": ["PM", "CRA", "PV", "QA"],
|
"default_roles": ["PM", "CRA", "PV", "QA"],
|
||||||
"prerequisite_permissions": ["subjects:read", "sites:read"],
|
"prerequisite_permissions": ["subject_aes:read", "subjects:read", "sites:read"],
|
||||||
},
|
},
|
||||||
"subject_aes:read": {
|
"subject_aes:read": {
|
||||||
"module": "subjects",
|
"module": "subjects",
|
||||||
@@ -123,7 +123,7 @@ API_ENDPOINT_PERMISSIONS = {
|
|||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "创建合同费用",
|
"description": "创建合同费用",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
"prerequisite_permissions": ["sites:read"],
|
"prerequisite_permissions": ["fees_contracts:read", "sites:read"],
|
||||||
},
|
},
|
||||||
"fees_contracts:read": {
|
"fees_contracts:read": {
|
||||||
"module": "fees",
|
"module": "fees",
|
||||||
@@ -137,14 +137,14 @@ API_ENDPOINT_PERMISSIONS = {
|
|||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "更新合同费用",
|
"description": "更新合同费用",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
"prerequisite_permissions": ["sites:read"],
|
"prerequisite_permissions": ["fees_contracts:read", "sites:read"],
|
||||||
},
|
},
|
||||||
"fees_contracts:delete": {
|
"fees_contracts:delete": {
|
||||||
"module": "fees",
|
"module": "fees",
|
||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "删除合同费用",
|
"description": "删除合同费用",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
"prerequisite_permissions": ["sites:read"],
|
"prerequisite_permissions": ["fees_contracts:read", "sites:read"],
|
||||||
},
|
},
|
||||||
# 项目成员管理
|
# 项目成员管理
|
||||||
"project_members:create": {
|
"project_members:create": {
|
||||||
@@ -384,30 +384,35 @@ API_ENDPOINT_PERMISSIONS = {
|
|||||||
"action": "read",
|
"action": "read",
|
||||||
"description": "查询立项配置",
|
"description": "查询立项配置",
|
||||||
"default_roles": ["PM", "CRA", "PV", "QA", "CTA"],
|
"default_roles": ["PM", "CRA", "PV", "QA", "CTA"],
|
||||||
|
"prerequisite_permissions": [],
|
||||||
},
|
},
|
||||||
"setup_config:update": {
|
"setup_config:update": {
|
||||||
"module": "setup_config",
|
"module": "setup_config",
|
||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "保存立项配置草稿",
|
"description": "保存立项配置草稿",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
|
"prerequisite_permissions": ["setup_config:read"],
|
||||||
},
|
},
|
||||||
"setup_config:publish": {
|
"setup_config:publish": {
|
||||||
"module": "setup_config",
|
"module": "setup_config",
|
||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "发布立项配置",
|
"description": "发布立项配置",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
|
"prerequisite_permissions": ["setup_config:read"],
|
||||||
},
|
},
|
||||||
"setup_config:rollback": {
|
"setup_config:rollback": {
|
||||||
"module": "setup_config",
|
"module": "setup_config",
|
||||||
"action": "write",
|
"action": "write",
|
||||||
"description": "回滚立项配置版本",
|
"description": "回滚立项配置版本",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
|
"prerequisite_permissions": ["setup_config:read"],
|
||||||
},
|
},
|
||||||
"setup_config:delete_version": {
|
"setup_config:delete_version": {
|
||||||
"module": "setup_config",
|
"module": "setup_config",
|
||||||
"action": "delete",
|
"action": "delete",
|
||||||
"description": "删除立项配置版本",
|
"description": "删除立项配置版本",
|
||||||
"default_roles": ["PM"],
|
"default_roles": ["PM"],
|
||||||
|
"prerequisite_permissions": ["setup_config:read"],
|
||||||
},
|
},
|
||||||
# 项目里程碑管理
|
# 项目里程碑管理
|
||||||
"project_milestones:read": {
|
"project_milestones:read": {
|
||||||
@@ -640,6 +645,36 @@ API_ENDPOINT_PERMISSIONS = {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def _operation_read_candidates(operation_key: str) -> list[str]:
|
||||||
|
prefix = operation_key.split(":", 1)[0]
|
||||||
|
candidates = []
|
||||||
|
for read_key in (f"{prefix}:read", f"{prefix}:list"):
|
||||||
|
canonical_key = canonical_permission_key(read_key)
|
||||||
|
if canonical_key in API_ENDPOINT_PERMISSIONS and canonical_key not in candidates:
|
||||||
|
candidates.append(canonical_key)
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
|
||||||
|
def _normalized_prerequisite_permissions(operation_key: str, config: dict) -> list[str]:
|
||||||
|
prerequisites = [
|
||||||
|
canonical_permission_key(key)
|
||||||
|
for key in config.get("prerequisite_permissions", [])
|
||||||
|
]
|
||||||
|
verb = operation_key.split(":")[-1]
|
||||||
|
if verb in {"create", "update", "delete", "export", "publish", "rollback", "delete_version"}:
|
||||||
|
for read_key in _operation_read_candidates(operation_key):
|
||||||
|
if read_key != operation_key and read_key not in prerequisites:
|
||||||
|
prerequisites.insert(0, read_key)
|
||||||
|
return list(dict.fromkeys(prerequisites))
|
||||||
|
|
||||||
|
|
||||||
|
for _operation_key, _operation_config in API_ENDPOINT_PERMISSIONS.items():
|
||||||
|
_operation_config["prerequisite_permissions"] = _normalized_prerequisite_permissions(
|
||||||
|
_operation_key,
|
||||||
|
_operation_config,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# 向后兼容:业务操作名到接口级权限的映射
|
# 向后兼容:业务操作名到接口级权限的映射
|
||||||
# 用于在接口级权限未配置时,回退到模块级权限
|
# 用于在接口级权限未配置时,回退到模块级权限
|
||||||
OPERATION_TO_ENDPOINTS: dict[str, dict[str, list[str]]] = {
|
OPERATION_TO_ENDPOINTS: dict[str, dict[str, list[str]]] = {
|
||||||
@@ -830,48 +865,11 @@ OPERATION_TO_ENDPOINTS: dict[str, dict[str, list[str]]] = {
|
|||||||
# 项目级权限角色列表
|
# 项目级权限角色列表
|
||||||
PROJECT_PERMISSION_ROLES = ["PM", "CRA", "PV", "QA", "CTA"]
|
PROJECT_PERMISSION_ROLES = ["PM", "CRA", "PV", "QA", "CTA"]
|
||||||
|
|
||||||
# 前置权限映射表(用于权限检查)
|
# 前置权限映射表(用于权限检查),由权限定义生成,避免展示与运行时不一致。
|
||||||
# 定义每个操作需要的前置权限
|
|
||||||
OPERATION_PREREQUISITES: dict[str, list[str]] = {
|
OPERATION_PREREQUISITES: dict[str, list[str]] = {
|
||||||
# 参与者管理
|
key: config["prerequisite_permissions"]
|
||||||
"subjects:create": ["sites:read"],
|
for key, config in API_ENDPOINT_PERMISSIONS.items()
|
||||||
"subjects:update": ["sites:read"],
|
if config["prerequisite_permissions"]
|
||||||
"subjects:delete": ["sites:read"],
|
|
||||||
|
|
||||||
# 访视管理
|
|
||||||
"visits:create": ["subjects:read", "sites:read"],
|
|
||||||
"visits:update": ["subjects:read", "sites:read"],
|
|
||||||
"visits:delete": ["subjects:read", "sites:read"],
|
|
||||||
|
|
||||||
# 参与者AE
|
|
||||||
"subject_aes:create": ["subjects:read", "sites:read"],
|
|
||||||
"subject_aes:update": ["subject_aes:read", "subjects:read", "sites:read"],
|
|
||||||
"subject_aes:delete": ["subject_aes:read", "subjects:read", "sites:read"],
|
|
||||||
|
|
||||||
# 合同费用
|
|
||||||
"fees_contracts:create": ["sites:read"],
|
|
||||||
"fees_contracts:update": ["sites:read"],
|
|
||||||
"fees_contracts:delete": ["sites:read"],
|
|
||||||
|
|
||||||
# 药物发货
|
|
||||||
"drug_shipments:create": ["sites:read"],
|
|
||||||
"drug_shipments:update": ["sites:read"],
|
|
||||||
"drug_shipments:delete": ["sites:read"],
|
|
||||||
|
|
||||||
# 参与者PD
|
|
||||||
"subject_pds:create": ["subjects:read", "sites:read"],
|
|
||||||
"subject_pds:update": ["subject_pds:list", "subjects:read", "sites:read"],
|
|
||||||
"subject_pds:delete": ["subject_pds:list", "subjects:read", "sites:read"],
|
|
||||||
|
|
||||||
# 病史记录
|
|
||||||
"subject_histories:create": ["subjects:read"],
|
|
||||||
"subject_histories:update": ["subjects:read"],
|
|
||||||
"subject_histories:delete": ["subjects:read"],
|
|
||||||
|
|
||||||
# 监查访视问题
|
|
||||||
"monitoring_issues:create": ["sites:read"],
|
|
||||||
"monitoring_issues:update": ["sites:read"],
|
|
||||||
"monitoring_issues:delete": ["sites:read"],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# 系统级权限定义
|
# 系统级权限定义
|
||||||
|
|||||||
@@ -16,6 +16,14 @@ from app.core.api_permissions import (
|
|||||||
from app.core.permission_cache import get_permission_cache
|
from app.core.permission_cache import get_permission_cache
|
||||||
|
|
||||||
|
|
||||||
|
class PrerequisitePermissionConfirmationRequired(ValueError):
|
||||||
|
"""权限调整需要授权人确认。"""
|
||||||
|
|
||||||
|
def __init__(self, adjustments: dict):
|
||||||
|
super().__init__("需要确认前置权限调整")
|
||||||
|
self.adjustments = adjustments
|
||||||
|
|
||||||
|
|
||||||
async def _get_project_permission_overrides(
|
async def _get_project_permission_overrides(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
study_id: uuid.UUID,
|
study_id: uuid.UUID,
|
||||||
@@ -48,6 +56,126 @@ async def _get_project_permission_overrides(
|
|||||||
return permissions
|
return permissions
|
||||||
|
|
||||||
|
|
||||||
|
def _empty_role_adjustment() -> dict[str, dict[str, list[str]]]:
|
||||||
|
return {"add": {}, "remove": {}}
|
||||||
|
|
||||||
|
|
||||||
|
def _flatten_role_permissions(
|
||||||
|
matrix: dict[str, dict[str, dict[str, bool]]],
|
||||||
|
role: str,
|
||||||
|
) -> dict[str, bool]:
|
||||||
|
permissions: dict[str, bool] = {
|
||||||
|
endpoint_key: False
|
||||||
|
for endpoint_key in API_ENDPOINT_PERMISSIONS.keys()
|
||||||
|
}
|
||||||
|
if role in matrix:
|
||||||
|
for endpoint_key, value in matrix[role].items():
|
||||||
|
endpoint_key = canonical_permission_key(endpoint_key)
|
||||||
|
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
|
||||||
|
continue
|
||||||
|
permissions[endpoint_key] = bool(value["allowed"] if isinstance(value, dict) else value)
|
||||||
|
return permissions
|
||||||
|
|
||||||
|
|
||||||
|
def _canonicalize_payload(payload: dict[str, dict[str, bool]]) -> dict[str, dict[str, bool]]:
|
||||||
|
normalized: dict[str, dict[str, bool]] = {}
|
||||||
|
for role, endpoints in payload.items():
|
||||||
|
normalized[role] = {}
|
||||||
|
for endpoint_key, allowed in endpoints.items():
|
||||||
|
endpoint_key = canonical_permission_key(endpoint_key)
|
||||||
|
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
|
||||||
|
continue
|
||||||
|
normalized[role][endpoint_key] = bool(allowed)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
def _add_adjustment(target: dict[str, list[str]], key: str, value: str) -> None:
|
||||||
|
values = target.setdefault(key, [])
|
||||||
|
if value not in values:
|
||||||
|
values.append(value)
|
||||||
|
|
||||||
|
|
||||||
|
async def preview_api_permission_prerequisite_adjustments(
|
||||||
|
db: AsyncSession,
|
||||||
|
study_id: uuid.UUID,
|
||||||
|
payload: dict[str, dict[str, bool]],
|
||||||
|
) -> dict:
|
||||||
|
"""预检权限草稿需要授权人确认的前置补齐和下游消除项。"""
|
||||||
|
normalized_payload = _canonicalize_payload(payload)
|
||||||
|
matrix = await get_api_endpoint_permissions(db, study_id)
|
||||||
|
roles: dict[str, dict[str, dict[str, list[str]]]] = {}
|
||||||
|
|
||||||
|
for role, endpoints in normalized_payload.items():
|
||||||
|
if role in ("ADMIN", "PM"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
candidate = _flatten_role_permissions(matrix, role)
|
||||||
|
explicitly_denied = {
|
||||||
|
endpoint_key
|
||||||
|
for endpoint_key, allowed in endpoints.items()
|
||||||
|
if not allowed
|
||||||
|
}
|
||||||
|
for endpoint_key, allowed in endpoints.items():
|
||||||
|
candidate[endpoint_key] = allowed
|
||||||
|
|
||||||
|
role_adjustment = _empty_role_adjustment()
|
||||||
|
denied_sources = set(explicitly_denied)
|
||||||
|
|
||||||
|
changed = True
|
||||||
|
while changed:
|
||||||
|
changed = False
|
||||||
|
for endpoint_key, allowed in list(candidate.items()):
|
||||||
|
if not allowed or endpoint_key in denied_sources:
|
||||||
|
continue
|
||||||
|
for prereq in OPERATION_PREREQUISITES.get(endpoint_key, []):
|
||||||
|
prereq = canonical_permission_key(prereq)
|
||||||
|
if prereq in denied_sources:
|
||||||
|
_add_adjustment(role_adjustment["remove"], prereq, endpoint_key)
|
||||||
|
candidate[endpoint_key] = False
|
||||||
|
denied_sources.add(endpoint_key)
|
||||||
|
changed = True
|
||||||
|
break
|
||||||
|
|
||||||
|
changed = True
|
||||||
|
while changed:
|
||||||
|
changed = False
|
||||||
|
for endpoint_key, allowed in list(candidate.items()):
|
||||||
|
if not allowed:
|
||||||
|
continue
|
||||||
|
for prereq in OPERATION_PREREQUISITES.get(endpoint_key, []):
|
||||||
|
prereq = canonical_permission_key(prereq)
|
||||||
|
if candidate.get(prereq, False):
|
||||||
|
continue
|
||||||
|
_add_adjustment(role_adjustment["add"], endpoint_key, prereq)
|
||||||
|
candidate[prereq] = True
|
||||||
|
changed = True
|
||||||
|
|
||||||
|
if role_adjustment["add"] or role_adjustment["remove"]:
|
||||||
|
roles[role] = role_adjustment
|
||||||
|
|
||||||
|
return {
|
||||||
|
"requires_confirmation": bool(roles),
|
||||||
|
"roles": roles,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def apply_prerequisite_adjustments_to_payload(
|
||||||
|
payload: dict[str, dict[str, bool]],
|
||||||
|
adjustments: dict,
|
||||||
|
) -> dict[str, dict[str, bool]]:
|
||||||
|
"""把已确认的补齐和消除项合并到待保存 payload。"""
|
||||||
|
normalized = _canonicalize_payload(payload)
|
||||||
|
for role, role_adjustment in adjustments.get("roles", {}).items():
|
||||||
|
role_payload = normalized.setdefault(role, {})
|
||||||
|
for prerequisites in role_adjustment.get("add", {}).values():
|
||||||
|
for prereq in prerequisites:
|
||||||
|
role_payload[canonical_permission_key(prereq)] = True
|
||||||
|
for dependents in role_adjustment.get("remove", {}).values():
|
||||||
|
for dependent in dependents:
|
||||||
|
role_payload[canonical_permission_key(dependent)] = False
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
async def role_has_api_permission(
|
async def role_has_api_permission(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
study_id: uuid.UUID,
|
study_id: uuid.UUID,
|
||||||
@@ -150,21 +278,58 @@ async def get_api_endpoint_permissions(
|
|||||||
return matrix
|
return matrix
|
||||||
|
|
||||||
|
|
||||||
|
async def get_effective_api_endpoint_permissions(
|
||||||
|
db: AsyncSession,
|
||||||
|
study_id: uuid.UUID,
|
||||||
|
) -> dict[str, dict[str, dict[str, bool]]]:
|
||||||
|
"""获取考虑前置权限后的有效权限矩阵。"""
|
||||||
|
matrix = await get_api_endpoint_permissions(db, study_id)
|
||||||
|
effective: dict[str, dict[str, dict[str, bool]]] = {}
|
||||||
|
for role, endpoints in matrix.items():
|
||||||
|
effective[role] = {}
|
||||||
|
for endpoint_key in endpoints.keys():
|
||||||
|
effective[role][endpoint_key] = {
|
||||||
|
"allowed": await role_has_api_permission(
|
||||||
|
db,
|
||||||
|
study_id,
|
||||||
|
role,
|
||||||
|
endpoint_key,
|
||||||
|
check_prerequisites=True,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return effective
|
||||||
|
|
||||||
|
|
||||||
async def replace_api_endpoint_permissions(
|
async def replace_api_endpoint_permissions(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
study_id: uuid.UUID,
|
study_id: uuid.UUID,
|
||||||
payload: dict[str, dict[str, bool]],
|
payload: dict[str, dict[str, bool]],
|
||||||
|
*,
|
||||||
|
confirm_prerequisite_adjustments: bool = False,
|
||||||
) -> dict[str, dict[str, dict[str, bool]]]:
|
) -> dict[str, dict[str, dict[str, bool]]]:
|
||||||
"""更新 payload 中指定的角色权限项。未提交的权限项保持不变。
|
"""更新 payload 中指定的角色权限项。未提交的权限项保持不变。
|
||||||
|
|
||||||
ADMIN 与 PM 权限不会被持久化:ADMIN 始终拥有全部权限,PM 默认拥有
|
ADMIN 与 PM 权限不会被持久化:ADMIN 始终拥有全部权限,PM 默认拥有
|
||||||
全部项目权限,应当通过专门的渠道而不是项目权限矩阵调整。
|
全部项目权限,应当通过专门的渠道而不是项目权限矩阵调整。
|
||||||
"""
|
"""
|
||||||
for role, endpoints in payload.items():
|
normalized_payload = _canonicalize_payload(payload)
|
||||||
|
adjustments = await preview_api_permission_prerequisite_adjustments(
|
||||||
|
db,
|
||||||
|
study_id,
|
||||||
|
normalized_payload,
|
||||||
|
)
|
||||||
|
if adjustments["requires_confirmation"]:
|
||||||
|
if not confirm_prerequisite_adjustments:
|
||||||
|
raise PrerequisitePermissionConfirmationRequired(adjustments)
|
||||||
|
normalized_payload = apply_prerequisite_adjustments_to_payload(
|
||||||
|
normalized_payload,
|
||||||
|
adjustments,
|
||||||
|
)
|
||||||
|
|
||||||
|
for role, endpoints in normalized_payload.items():
|
||||||
if role in ("ADMIN", "PM"):
|
if role in ("ADMIN", "PM"):
|
||||||
continue
|
continue
|
||||||
for endpoint_key, allowed in endpoints.items():
|
for endpoint_key, allowed in endpoints.items():
|
||||||
endpoint_key = canonical_permission_key(endpoint_key)
|
|
||||||
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
|
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
|
||||||
continue
|
continue
|
||||||
result = await db.execute(
|
result = await db.execute(
|
||||||
|
|||||||
@@ -99,6 +99,15 @@ def test_read_permissions_do_not_duplicate_list_and_detail_entries():
|
|||||||
assert expected_read_keys <= set(API_ENDPOINT_PERMISSIONS)
|
assert expected_read_keys <= set(API_ENDPOINT_PERMISSIONS)
|
||||||
|
|
||||||
|
|
||||||
|
def test_site_contact_display_source_permissions_cover_non_pm_roles():
|
||||||
|
"""负责人展示名来自中心列表,读取角色不应局限于 PM。"""
|
||||||
|
sites_read_roles = set(API_ENDPOINT_PERMISSIONS["sites:read"]["default_roles"])
|
||||||
|
startup_auth_read_roles = set(API_ENDPOINT_PERMISSIONS["startup_auth:read"]["default_roles"])
|
||||||
|
|
||||||
|
assert {"PM", "CRA", "PV", "QA", "CTA"} <= sites_read_roles
|
||||||
|
assert {"PM", "CRA", "PV", "CTA"} <= startup_auth_read_roles
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_legacy_read_permission_overrides_are_folded_into_canonical_read_key(db_session: AsyncSession):
|
async def test_legacy_read_permission_overrides_are_folded_into_canonical_read_key(db_session: AsyncSession):
|
||||||
"""历史项目权限中的列表读取 key 应继续作用到合并后的读取权限。"""
|
"""历史项目权限中的列表读取 key 应继续作用到合并后的读取权限。"""
|
||||||
@@ -623,10 +632,16 @@ async def test_full_permission_matrix_round_trips_to_backend_checks(db_session:
|
|||||||
for role_index, role in enumerate(configurable_roles)
|
for role_index, role in enumerate(configurable_roles)
|
||||||
}
|
}
|
||||||
|
|
||||||
matrix = await replace_api_endpoint_permissions(db_session, study_id, payload)
|
matrix = await replace_api_endpoint_permissions(
|
||||||
|
db_session,
|
||||||
|
study_id,
|
||||||
|
payload,
|
||||||
|
confirm_prerequisite_adjustments=True,
|
||||||
|
)
|
||||||
|
|
||||||
for role in configurable_roles:
|
for role in configurable_roles:
|
||||||
for endpoint_key, expected in payload[role].items():
|
for endpoint_key in payload[role].keys():
|
||||||
|
expected = matrix[role][endpoint_key]["allowed"]
|
||||||
assert matrix[role][endpoint_key]["allowed"] is expected
|
assert matrix[role][endpoint_key]["allowed"] is expected
|
||||||
allowed = await role_has_api_permission(
|
allowed = await role_has_api_permission(
|
||||||
db_session,
|
db_session,
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ import uuid
|
|||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.core.project_permissions import get_api_endpoint_permissions, replace_api_endpoint_permissions
|
from app.core.project_permissions import (
|
||||||
|
get_api_endpoint_permissions,
|
||||||
|
preview_api_permission_prerequisite_adjustments,
|
||||||
|
replace_api_endpoint_permissions,
|
||||||
|
)
|
||||||
from app.models.api_endpoint_permission import ApiEndpointPermission
|
from app.models.api_endpoint_permission import ApiEndpointPermission
|
||||||
|
|
||||||
|
|
||||||
@@ -105,6 +109,7 @@ async def test_replace_api_endpoint_permissions_accepts_legacy_read_alias_denial
|
|||||||
"subjects:list": False,
|
"subjects:list": False,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
confirm_prerequisite_adjustments=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
assert "subjects:list" not in result["CRA"]
|
assert "subjects:list" not in result["CRA"]
|
||||||
@@ -314,6 +319,84 @@ async def test_replace_api_endpoint_permissions_preserves_unsubmitted_roles(db_s
|
|||||||
assert result["PV"]["subjects:create"]["allowed"] is True
|
assert result["PV"]["subjects:create"]["allowed"] is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_preview_reports_prerequisites_to_add_for_custom_role(db_session: AsyncSession):
|
||||||
|
"""授权子权限前应提示需要补齐的前置权限。"""
|
||||||
|
study_id = uuid.uuid4()
|
||||||
|
|
||||||
|
preview = await preview_api_permission_prerequisite_adjustments(
|
||||||
|
db_session,
|
||||||
|
study_id,
|
||||||
|
{"DATA_MANAGER": {"subjects:create": True}},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert preview["requires_confirmation"] is True
|
||||||
|
assert preview["roles"]["DATA_MANAGER"]["add"] == {
|
||||||
|
"subjects:create": ["subjects:read", "sites:read"],
|
||||||
|
}
|
||||||
|
assert preview["roles"]["DATA_MANAGER"]["remove"] == {}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_replace_rejects_unconfirmed_missing_prerequisites(db_session: AsyncSession):
|
||||||
|
"""未确认时不应保存缺失前置权限的授权组合。"""
|
||||||
|
study_id = uuid.uuid4()
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="需要确认前置权限调整"):
|
||||||
|
await replace_api_endpoint_permissions(
|
||||||
|
db_session,
|
||||||
|
study_id,
|
||||||
|
{"DATA_MANAGER": {"subjects:create": True}},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_replace_confirmed_adds_missing_prerequisites(db_session: AsyncSession):
|
||||||
|
"""确认后应补齐授权子权限需要的前置权限。"""
|
||||||
|
study_id = uuid.uuid4()
|
||||||
|
|
||||||
|
result = await replace_api_endpoint_permissions(
|
||||||
|
db_session,
|
||||||
|
study_id,
|
||||||
|
{"DATA_MANAGER": {"subjects:create": True}},
|
||||||
|
confirm_prerequisite_adjustments=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["DATA_MANAGER"]["subjects:create"]["allowed"] is True
|
||||||
|
assert result["DATA_MANAGER"]["subjects:read"]["allowed"] is True
|
||||||
|
assert result["DATA_MANAGER"]["sites:read"]["allowed"] is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_replace_confirmed_removes_dependents_when_prerequisite_denied(db_session: AsyncSession):
|
||||||
|
"""确认取消前置权限时,应消除依赖它的下游权限。"""
|
||||||
|
study_id = uuid.uuid4()
|
||||||
|
|
||||||
|
await replace_api_endpoint_permissions(
|
||||||
|
db_session,
|
||||||
|
study_id,
|
||||||
|
{
|
||||||
|
"DATA_MANAGER": {
|
||||||
|
"subjects:read": True,
|
||||||
|
"sites:read": True,
|
||||||
|
"subjects:create": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirm_prerequisite_adjustments=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await replace_api_endpoint_permissions(
|
||||||
|
db_session,
|
||||||
|
study_id,
|
||||||
|
{"DATA_MANAGER": {"sites:read": False}},
|
||||||
|
confirm_prerequisite_adjustments=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["DATA_MANAGER"]["sites:read"]["allowed"] is False
|
||||||
|
assert result["DATA_MANAGER"]["subjects:create"]["allowed"] is False
|
||||||
|
assert result["DATA_MANAGER"]["subjects:read"]["allowed"] is True
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_get_api_endpoint_permissions_structure(db_session: AsyncSession):
|
async def test_get_api_endpoint_permissions_structure(db_session: AsyncSession):
|
||||||
"""测试权限矩阵的结构"""
|
"""测试权限矩阵的结构"""
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# 项目权限前置审查优化设计
|
||||||
|
|
||||||
|
## 目标
|
||||||
|
|
||||||
|
项目权限保存时必须先审查前置权限。授权子权限缺少前置权限时,系统提示授权人确认补齐;取消前置权限影响下游权限时,系统提示授权人确认消除。未经确认的不一致权限组合不能落库。
|
||||||
|
|
||||||
|
## 方案
|
||||||
|
|
||||||
|
- `API_ENDPOINT_PERMISSIONS[*].prerequisite_permissions` 作为前置权限单一事实源,运行时映射由它生成。
|
||||||
|
- 后端保存权限前合并当前矩阵和提交草稿,计算缺失前置权限与受影响下游权限。
|
||||||
|
- 未确认时如存在补齐或消除项,接口返回 `409 Conflict` 和调整详情。
|
||||||
|
- 确认后后端应用调整:授权子权限时补齐前置权限,取消前置权限时消除受影响下游权限。
|
||||||
|
- `/me` 返回有效权限,避免前端菜单或按钮展示运行时不可用的授权。
|
||||||
|
- 前端角色编辑器保存前本地预检,弹窗展示补齐/消除项,授权人确认后再提交确认标记。
|
||||||
|
|
||||||
|
## 测试范围
|
||||||
|
|
||||||
|
- 后端:预检结果、未确认拒绝、确认补齐、确认消除、有效权限矩阵。
|
||||||
|
- 前端:操作元数据包含前置权限、保存前提示确认、确认后提交确认标记。
|
||||||
|
|
||||||
|
## 约束
|
||||||
|
|
||||||
|
- 不做 git 分支、提交或推送。
|
||||||
|
- 不引入新权限抽象表,保持 KISS。
|
||||||
|
- 不静默修改授权人的草稿,所有补齐/消除必须经过确认。
|
||||||
@@ -2,6 +2,7 @@ import { apiGet, apiPut, apiPost, apiDelete, type ApiRequestConfig } from "./axi
|
|||||||
import type {
|
import type {
|
||||||
ApiEndpointPermissionsResponse,
|
ApiEndpointPermissionsResponse,
|
||||||
ApiEndpointPermissionsUpdate,
|
ApiEndpointPermissionsUpdate,
|
||||||
|
ApiOperation,
|
||||||
PermissionMetricsResponse,
|
PermissionMetricsResponse,
|
||||||
CacheStatsResponse,
|
CacheStatsResponse,
|
||||||
AlertsResponse,
|
AlertsResponse,
|
||||||
@@ -21,11 +22,17 @@ export const fetchApiEndpointPermissions = (studyId: string, config?: ApiRequest
|
|||||||
export const fetchMyApiEndpointPermissions = (studyId: string, config?: ApiRequestConfig) =>
|
export const fetchMyApiEndpointPermissions = (studyId: string, config?: ApiRequestConfig) =>
|
||||||
apiGet<ApiEndpointPermissionsResponse>(`/api/v1/studies/${studyId}/api-permissions/me`, config);
|
apiGet<ApiEndpointPermissionsResponse>(`/api/v1/studies/${studyId}/api-permissions/me`, config);
|
||||||
|
|
||||||
export const updateApiEndpointPermissions = (studyId: string, payload: ApiEndpointPermissionsUpdate) =>
|
export const updateApiEndpointPermissions = (
|
||||||
apiPut<ApiEndpointPermissionsResponse>(`/api/v1/studies/${studyId}/api-permissions`, payload);
|
studyId: string,
|
||||||
|
payload: ApiEndpointPermissionsUpdate,
|
||||||
|
options?: { confirm_prerequisite_adjustments?: boolean },
|
||||||
|
) =>
|
||||||
|
apiPut<ApiEndpointPermissionsResponse>(`/api/v1/studies/${studyId}/api-permissions`, payload, {
|
||||||
|
params: options?.confirm_prerequisite_adjustments ? { confirm_prerequisite_adjustments: true } : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
export const fetchApiOperations = () =>
|
export const fetchApiOperations = () =>
|
||||||
apiGet<{ operations: Array<{ operation_key: string; module: string; action: string; description: string; default_roles: string[] }> }>(`/api/v1/api-permissions/operations`);
|
apiGet<{ operations: ApiOperation[] }>(`/api/v1/api-permissions/operations`);
|
||||||
|
|
||||||
// 权限系统监控API
|
// 权限系统监控API
|
||||||
export const fetchPermissionMetrics = () =>
|
export const fetchPermissionMetrics = () =>
|
||||||
|
|||||||
@@ -10,11 +10,11 @@ vi.mock("@/api/projectPermissions", () => ({
|
|||||||
fetchApiOperations: vi.fn().mockResolvedValue({ data: { operations: [] } }),
|
fetchApiOperations: vi.fn().mockResolvedValue({ data: { operations: [] } }),
|
||||||
fetchPermissionTemplates: vi.fn().mockResolvedValue({
|
fetchPermissionTemplates: vi.fn().mockResolvedValue({
|
||||||
data: [
|
data: [
|
||||||
{ category: "PM", name: "PM", description: "项目负责人,统筹项目全局,协调进度、资源与关键决策。" },
|
|
||||||
{ category: "CRA", name: "CRA", description: "负责各中心临床监查执行,跟进现场质量、数据和问题闭环。" },
|
|
||||||
{ category: "CTA", name: "CTA", description: "负责合同、药品及相关项目事务管理,保障执行支持与物资协同。" },
|
|
||||||
{ category: "QA", name: "QA", description: "负责医学审核与稽查,关注质量风险、合规性和医学一致性。" },
|
|
||||||
{ category: "PV", name: "PV", description: "负责药物警戒相关工作,跟踪安全性事件并支持风险评估。" },
|
{ category: "PV", name: "PV", description: "负责药物警戒相关工作,跟踪安全性事件并支持风险评估。" },
|
||||||
|
{ category: "QA", name: "QA", description: "负责医学审核与稽查,关注质量风险、合规性和医学一致性。" },
|
||||||
|
{ category: "CTA", name: "CTA", description: "负责合同、药品及相关项目事务管理,保障执行支持与物资协同。" },
|
||||||
|
{ category: "CRA", name: "CRA", description: "负责各中心临床监查执行,跟进现场质量、数据和问题闭环。" },
|
||||||
|
{ category: "PM", name: "PM", description: "项目负责人,统筹项目全局,协调进度、资源与关键决策。" },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
}));
|
}));
|
||||||
@@ -96,7 +96,7 @@ describe("ApiEndpointPermissions.vue", () => {
|
|||||||
expect(source).not.toContain(':label="role"');
|
expect(source).not.toContain(':label="role"');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("sorts matrix role columns with the role list order", async () => {
|
it("pins PM first in matrix role columns even when templates return PM last", async () => {
|
||||||
const wrapper = mount(ApiEndpointPermissions, {
|
const wrapper = mount(ApiEndpointPermissions, {
|
||||||
props: {
|
props: {
|
||||||
project: { id: "test-id", name: "Test Project" },
|
project: { id: "test-id", name: "Test Project" },
|
||||||
@@ -117,7 +117,7 @@ describe("ApiEndpointPermissions.vue", () => {
|
|||||||
});
|
});
|
||||||
await vi.dynamicImportSettled();
|
await vi.dynamicImportSettled();
|
||||||
|
|
||||||
expect((wrapper.vm as any).roles).toEqual(["PM", "CRA", "CTA", "QA", "PV"]);
|
expect((wrapper.vm as any).roles).toEqual(["PM", "PV", "QA", "CTA", "CRA"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("sorts project permission modules by sidebar menu order", async () => {
|
it("sorts project permission modules by sidebar menu order", async () => {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ describe("PermissionTemplateSelector", () => {
|
|||||||
it("reads current project permissions by role key, not by role label", () => {
|
it("reads current project permissions by role key, not by role label", () => {
|
||||||
const source = readSource();
|
const source = readSource();
|
||||||
|
|
||||||
|
expect(source).toContain('v-for="template in sortedTemplates"');
|
||||||
expect(source).toContain('<span class="card-name">{{ template.name }}</span>');
|
expect(source).toContain('<span class="card-name">{{ template.name }}</span>');
|
||||||
expect(source).toContain("refreshKey?: number;");
|
expect(source).toContain("refreshKey?: number;");
|
||||||
expect(source).toContain("watch(() => props.refreshKey, loadTemplates);");
|
expect(source).toContain("watch(() => props.refreshKey, loadTemplates);");
|
||||||
@@ -32,6 +33,15 @@ describe("PermissionTemplateSelector", () => {
|
|||||||
expect(source).toContain("emit('edit-role', template.category!)");
|
expect(source).toContain("emit('edit-role', template.category!)");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("sorts role cards with the shared role template order", () => {
|
||||||
|
const source = readSource();
|
||||||
|
|
||||||
|
expect(source).toContain("useRoleTemplateMeta");
|
||||||
|
expect(source).toContain("compareRolesByTemplateOrder");
|
||||||
|
expect(source).toContain("const sortedTemplates = computed");
|
||||||
|
expect(source).toContain("compareRolesByTemplateOrder(a.category, b.category)");
|
||||||
|
});
|
||||||
|
|
||||||
it("does not keep hard-coded preset role labels or icons", () => {
|
it("does not keep hard-coded preset role labels or icons", () => {
|
||||||
const source = readSource();
|
const source = readSource();
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
<div class="template-grid">
|
<div class="template-grid">
|
||||||
<div
|
<div
|
||||||
v-for="template in templates"
|
v-for="template in sortedTemplates"
|
||||||
:key="template.id"
|
:key="template.id"
|
||||||
class="template-card"
|
class="template-card"
|
||||||
:class="{ inactive: template.category && !isRoleActive(template.category) }"
|
:class="{ inactive: template.category && !isRoleActive(template.category) }"
|
||||||
@@ -61,12 +61,13 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, onMounted, watch } from "vue";
|
import { computed, ref, onMounted, watch } from "vue";
|
||||||
import { ElMessage } from "element-plus";
|
import { ElMessage } from "element-plus";
|
||||||
import {
|
import {
|
||||||
fetchPermissionTemplates,
|
fetchPermissionTemplates,
|
||||||
type PermissionTemplate,
|
type PermissionTemplate,
|
||||||
} from "@/api/projectPermissions";
|
} from "@/api/projectPermissions";
|
||||||
|
import { useRoleTemplateMeta } from "@/composables/useRoleTemplateMeta";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
studyId: string;
|
studyId: string;
|
||||||
@@ -80,6 +81,16 @@ const emit = defineEmits<{
|
|||||||
}>();
|
}>();
|
||||||
|
|
||||||
const templates = ref<PermissionTemplate[]>([]);
|
const templates = ref<PermissionTemplate[]>([]);
|
||||||
|
const { compareRolesByTemplateOrder } = useRoleTemplateMeta();
|
||||||
|
|
||||||
|
const sortedTemplates = computed(() =>
|
||||||
|
[...templates.value].sort((a, b) => {
|
||||||
|
if (a.category && b.category) return compareRolesByTemplateOrder(a.category, b.category);
|
||||||
|
if (a.category) return -1;
|
||||||
|
if (b.category) return 1;
|
||||||
|
return 0;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
const roleIcon = (category: string | null) => {
|
const roleIcon = (category: string | null) => {
|
||||||
const icons: Record<string, string> = {
|
const icons: Record<string, string> = {
|
||||||
|
|||||||
@@ -124,6 +124,7 @@ export interface Site {
|
|||||||
pi_name?: string | null;
|
pi_name?: string | null;
|
||||||
phone?: string | null;
|
phone?: string | null;
|
||||||
contact?: string | null;
|
contact?: string | null;
|
||||||
|
contact_display?: string | null;
|
||||||
contact_phone?: string | null;
|
contact_phone?: string | null;
|
||||||
enrollment_target?: number | null;
|
enrollment_target?: number | null;
|
||||||
enrollment_plan_start_date?: string | null;
|
enrollment_plan_start_date?: string | null;
|
||||||
@@ -148,6 +149,15 @@ export interface ApiEndpointPermissionsUpdate {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ApiOperation {
|
||||||
|
operation_key: string;
|
||||||
|
module: string;
|
||||||
|
action: string;
|
||||||
|
description: string;
|
||||||
|
default_roles: string[];
|
||||||
|
prerequisite_permissions: string[];
|
||||||
|
}
|
||||||
|
|
||||||
// 监控指标
|
// 监控指标
|
||||||
export interface PermissionCheckMetrics {
|
export interface PermissionCheckMetrics {
|
||||||
total_checks: number;
|
total_checks: number;
|
||||||
|
|||||||
@@ -157,6 +157,28 @@ describe("permission management custom roles", () => {
|
|||||||
expect(source).toContain("compareRolesByTemplateOrder(a.key, b.key)");
|
expect(source).toContain("compareRolesByTemplateOrder(a.key, b.key)");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("pins PM first in role list active role management and role permission editor", () => {
|
||||||
|
const source = readSource();
|
||||||
|
const listTabStart = source.indexOf("<!-- 标签页:角色列表 -->");
|
||||||
|
const listTabEnd = source.indexOf("<!-- 标签页:生效管理 -->", listTabStart);
|
||||||
|
const listTabSource = source.slice(listTabStart, listTabEnd);
|
||||||
|
const activeTabStart = source.indexOf("<!-- 标签页:生效管理 -->");
|
||||||
|
const activeTabEnd = source.indexOf("<!-- 标签页:编辑权限 -->", activeTabStart);
|
||||||
|
const activeTabSource = source.slice(activeTabStart, activeTabEnd);
|
||||||
|
const editTabStart = source.indexOf("<!-- 标签页:编辑权限 -->");
|
||||||
|
const editTabEnd = source.indexOf("</el-tab-pane>", editTabStart);
|
||||||
|
const editTabSource = source.slice(editTabStart, editTabEnd);
|
||||||
|
|
||||||
|
expect(source).toContain("const { roleLabel, roleDescription, roleIcon, compareRolesByTemplateOrder, loadRoleTemplates } = useRoleTemplateMeta();");
|
||||||
|
expect(source).toContain("const sortedTemplates = computed");
|
||||||
|
expect(source).toContain("compareRolesByTemplateOrder(a.category, b.category)");
|
||||||
|
expect(listTabSource).toContain(':data="sortedTemplates"');
|
||||||
|
expect(activeTabSource).toContain("v-for=\"role in roleOptions\"");
|
||||||
|
expect(editTabSource).toContain("v-for=\"role in roleOptions\"");
|
||||||
|
expect(source).toContain("options.sort((a, b) => compareRolesByTemplateOrder(a.key, b.key));");
|
||||||
|
expect(source).not.toContain("compareRoleManagementRoles");
|
||||||
|
});
|
||||||
|
|
||||||
it("submits only the selected role from role editor saves", () => {
|
it("submits only the selected role from role editor saves", () => {
|
||||||
const source = readSource();
|
const source = readSource();
|
||||||
|
|
||||||
@@ -165,6 +187,61 @@ describe("permission management custom roles", () => {
|
|||||||
expect(source).not.toContain("const payload = flattenMatrix(apiMatrix.value, { includePm: isAdmin.value });");
|
expect(source).not.toContain("const payload = flattenMatrix(apiMatrix.value, { includePm: isAdmin.value });");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("provides a cancel action for unsaved role permission edits", () => {
|
||||||
|
const source = readSource();
|
||||||
|
const actionsStart = source.indexOf('<div class="drawer-tab-actions">');
|
||||||
|
const actionsEnd = source.indexOf("</div>", actionsStart);
|
||||||
|
const actionsSource = source.slice(actionsStart, actionsEnd);
|
||||||
|
|
||||||
|
expect(source).toContain("const cancelRoleEditor = () =>");
|
||||||
|
expect(actionsSource).toContain("@click=\"cancelRoleEditor\"");
|
||||||
|
expect(actionsSource).toContain("取消");
|
||||||
|
expect(source).toContain("roleEditorDirtyGuard.syncBaseline();");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("checks prerequisite permission dependencies only when saving role permission edits", () => {
|
||||||
|
const source = readSource();
|
||||||
|
|
||||||
|
expect(source).toContain("previewRolePrerequisiteAdjustments");
|
||||||
|
expect(source).toContain("handleRolePermissionChange");
|
||||||
|
expect(source).toContain('@change="(v: boolean) => handleRolePermissionChange(op, v)"');
|
||||||
|
expect(source).toContain("roleEditorDraft.value = { ...roleEditorDraft.value, [op.operation_key]: allowed };");
|
||||||
|
expect(source).toContain("openPrereqCheck");
|
||||||
|
expect(source).toContain("const passed = await openPrereqCheck();");
|
||||||
|
expect(source).toContain("if (!passed) return;");
|
||||||
|
expect(source).toContain("prereqCheckVisible");
|
||||||
|
expect(source).toContain("prereqAdjustments");
|
||||||
|
expect(source).toContain("prereqMissingItems");
|
||||||
|
expect(source).toContain("prereqRemoveItems");
|
||||||
|
expect(source).toContain("confirmPrereqAndSave");
|
||||||
|
expect(source).toContain("updateApiEndpointPermissions(selectedStudyId.value, payload, { confirm_prerequisite_adjustments: true })");
|
||||||
|
expect(source).toContain("权限依赖校验");
|
||||||
|
expect(source).toContain("依赖关系");
|
||||||
|
expect(source).toContain("需补充前置权限");
|
||||||
|
expect(source).toContain("一键授权全部前置");
|
||||||
|
expect(source).toContain("确认调整并保存");
|
||||||
|
expect(source).toContain("roleOperationActionLabel");
|
||||||
|
expect(source).toContain("rolePermissionDisplayLabel");
|
||||||
|
expect(source).toContain("${roleOperationActionLabel(operationKey)}|${roleOperationLabel(operationKey)}");
|
||||||
|
expect(source).not.toContain("renderPrerequisiteAdjustmentMessage");
|
||||||
|
expect(source).not.toContain("permission-prerequisite-dialog");
|
||||||
|
expect(source).not.toContain("permission-adjustment-row");
|
||||||
|
expect(source).not.toContain("permission-dependency-flow");
|
||||||
|
expect(source).not.toContain("permission-dependency-node--prerequisite");
|
||||||
|
expect(source).not.toContain("permission-dependency-node--dependent");
|
||||||
|
expect(source).not.toContain("prerequisiteAdjustmentMode");
|
||||||
|
expect(source).not.toContain("prerequisiteAdjustmentDialogCopy");
|
||||||
|
expect(source).not.toContain("roleEditorPrerequisiteConfirmed");
|
||||||
|
expect(source).not.toContain("同步授权依赖权限确认");
|
||||||
|
expect(source).not.toContain("取消权限影响确认");
|
||||||
|
expect(source).not.toContain("授权以下权限需要先授权其依赖权限");
|
||||||
|
expect(source).not.toContain("取消以下权限会影响依赖它的权限");
|
||||||
|
expect(source).not.toContain("确认后同步取消受影响权限。");
|
||||||
|
expect(source).not.toContain("permission-adjustment-summary");
|
||||||
|
expect(source).not.toContain("permission-adjustment-note");
|
||||||
|
expect(source).not.toContain("const confirmed = await confirmPrerequisiteAdjustmentsIfNeeded();");
|
||||||
|
});
|
||||||
|
|
||||||
it("submits only editable metadata when saving an existing role template", () => {
|
it("submits only editable metadata when saving an existing role template", () => {
|
||||||
const source = readSource();
|
const source = readSource();
|
||||||
const updateBuilderStart = source.indexOf("const buildTemplateUpdatePayload = () =>");
|
const updateBuilderStart = source.indexOf("const buildTemplateUpdatePayload = () =>");
|
||||||
|
|||||||
@@ -245,7 +245,7 @@
|
|||||||
|
|
||||||
<!-- 标签页:角色列表 -->
|
<!-- 标签页:角色列表 -->
|
||||||
<el-tab-pane label="角色列表" name="list">
|
<el-tab-pane label="角色列表" name="list">
|
||||||
<el-table :data="templates" v-loading="templatesLoading" stripe class="template-table">
|
<el-table :data="sortedTemplates" v-loading="templatesLoading" stripe class="template-table">
|
||||||
<el-table-column prop="name" label="角色名称" min-width="140">
|
<el-table-column prop="name" label="角色名称" min-width="140">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<span class="template-name">{{ roleDisplayName(row) }}</span>
|
<span class="template-name">{{ roleDisplayName(row) }}</span>
|
||||||
@@ -364,7 +364,7 @@
|
|||||||
<el-checkbox
|
<el-checkbox
|
||||||
:model-value="roleEditorDraft[op.operation_key] ?? false"
|
:model-value="roleEditorDraft[op.operation_key] ?? false"
|
||||||
:disabled="!canEditSelectedRole"
|
:disabled="!canEditSelectedRole"
|
||||||
@change="(v: boolean) => roleEditorDraft[op.operation_key] = v"
|
@change="(v: boolean) => handleRolePermissionChange(op, v)"
|
||||||
/>
|
/>
|
||||||
<el-tag :type="opTagType(op)" size="small" class="op-action-tag" effect="light">{{ opActionLabel(op) }}</el-tag>
|
<el-tag :type="opTagType(op)" size="small" class="op-action-tag" effect="light">{{ opActionLabel(op) }}</el-tag>
|
||||||
<span class="op-desc">{{ op.description || op.operation_key }}</span>
|
<span class="op-desc">{{ op.description || op.operation_key }}</span>
|
||||||
@@ -386,15 +386,17 @@
|
|||||||
<el-button v-else-if="templateDrawerTab === 'active'" type="primary" :loading="activeRolesSaving" @click="saveActiveRoles">
|
<el-button v-else-if="templateDrawerTab === 'active'" type="primary" :loading="activeRolesSaving" @click="saveActiveRoles">
|
||||||
保存
|
保存
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-button
|
<template v-else-if="templateDrawerTab === 'edit-role' && editingRole">
|
||||||
v-else-if="templateDrawerTab === 'edit-role' && editingRole"
|
<el-button @click="cancelRoleEditor">取消</el-button>
|
||||||
type="primary"
|
<el-button
|
||||||
:loading="roleEditorSaving"
|
type="primary"
|
||||||
:disabled="!canEditSelectedRole"
|
:loading="roleEditorSaving"
|
||||||
@click="saveRoleEditor"
|
:disabled="!canEditSelectedRole"
|
||||||
>
|
@click="saveRoleEditor"
|
||||||
保存 {{ roleLabel(editingRole) }} 权限
|
>
|
||||||
</el-button>
|
保存 {{ roleLabel(editingRole) }} 权限
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</el-drawer>
|
</el-drawer>
|
||||||
@@ -447,12 +449,132 @@
|
|||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- 权限校验 Dialog -->
|
||||||
|
<el-dialog
|
||||||
|
v-model="prereqCheckVisible"
|
||||||
|
width="520px"
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
:show-close="prereqCheckStep === 'failed'"
|
||||||
|
class="prereq-check-dialog"
|
||||||
|
title="权限依赖校验"
|
||||||
|
align-center
|
||||||
|
>
|
||||||
|
<!-- 校验步骤动画 -->
|
||||||
|
<div class="prereq-check-body">
|
||||||
|
<div class="prereq-check-steps">
|
||||||
|
<div
|
||||||
|
v-for="(item, i) in prereqCheckItems"
|
||||||
|
:key="i"
|
||||||
|
class="prereq-check-step"
|
||||||
|
:class="`prereq-check-step--${item.status}`"
|
||||||
|
>
|
||||||
|
<span class="prereq-step-icon">
|
||||||
|
<svg v-if="item.status === 'ok'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
|
||||||
|
<svg v-else-if="item.status === 'fail'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||||
|
<svg v-else-if="item.status === 'warn'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
|
||||||
|
<span v-else class="prereq-step-spinner" />
|
||||||
|
</span>
|
||||||
|
<span class="prereq-step-label">{{ item.label }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 通过状态 -->
|
||||||
|
<transition name="prereq-result">
|
||||||
|
<div v-if="prereqCheckStep === 'passed'" class="prereq-result prereq-result--pass">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
|
||||||
|
<span>所有权限依赖校验通过</span>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
|
||||||
|
<!-- 失败:缺少前置权限 -->
|
||||||
|
<transition name="prereq-result">
|
||||||
|
<div v-if="prereqCheckStep === 'failed'" class="prereq-issues">
|
||||||
|
<div class="prereq-issues-header">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
|
||||||
|
<span>发现 {{ prereqMissingItems.length + prereqRemoveItems.length }} 项依赖冲突,需要处理后才能保存</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 缺少前置权限 -->
|
||||||
|
<div v-if="prereqMissingItems.length" class="prereq-section">
|
||||||
|
<div class="prereq-section-title">
|
||||||
|
<span class="prereq-section-badge prereq-section-badge--add">需补充前置权限</span>
|
||||||
|
<el-button size="small" type="primary" @click="grantAllPrereqs" class="prereq-grant-all-btn">
|
||||||
|
一键授权全部前置
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
<div class="prereq-item-list">
|
||||||
|
<div v-for="(item, i) in prereqMissingItems" :key="i" class="prereq-item prereq-item--missing">
|
||||||
|
<div class="prereq-item-info">
|
||||||
|
<div class="prereq-item-row">
|
||||||
|
<span class="prereq-item-chip prereq-item-chip--enabled">已启用</span>
|
||||||
|
<span class="prereq-item-name">{{ rolePermissionDisplayLabel(item.dependentKey) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="prereq-item-arrow">依赖</div>
|
||||||
|
<div class="prereq-item-row">
|
||||||
|
<span class="prereq-item-chip prereq-item-chip--missing">缺少</span>
|
||||||
|
<span class="prereq-item-name">{{ rolePermissionDisplayLabel(item.prereqKey) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<el-button
|
||||||
|
size="small"
|
||||||
|
type="success"
|
||||||
|
:disabled="roleEditorDraft[item.prereqKey] === true"
|
||||||
|
@click="grantSinglePrereq(item.prereqKey)"
|
||||||
|
>授权</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 需取消的下游权限 -->
|
||||||
|
<div v-if="prereqRemoveItems.length" class="prereq-section">
|
||||||
|
<div class="prereq-section-title">
|
||||||
|
<span class="prereq-section-badge prereq-section-badge--remove">受影响的下游权限</span>
|
||||||
|
</div>
|
||||||
|
<div class="prereq-item-list">
|
||||||
|
<div v-for="(item, i) in prereqRemoveItems" :key="i" class="prereq-item prereq-item--remove">
|
||||||
|
<div class="prereq-item-info">
|
||||||
|
<div class="prereq-item-row">
|
||||||
|
<span class="prereq-item-chip prereq-item-chip--disabled">已禁用</span>
|
||||||
|
<span class="prereq-item-name">{{ rolePermissionDisplayLabel(item.prereqKey) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="prereq-item-arrow">影响</div>
|
||||||
|
<div class="prereq-item-row">
|
||||||
|
<span class="prereq-item-chip prereq-item-chip--will-remove">将同步取消</span>
|
||||||
|
<span class="prereq-item-name">{{ rolePermissionDisplayLabel(item.dependentKey) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template #footer>
|
||||||
|
<div v-if="prereqCheckStep === 'failed'" class="prereq-dialog-footer">
|
||||||
|
<el-button @click="prereqCheckVisible = false">取消保存</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="prereqRemoveItems.length && !prereqMissingItems.length"
|
||||||
|
type="primary"
|
||||||
|
:loading="prereqSaving"
|
||||||
|
@click="confirmPrereqAndSave"
|
||||||
|
>确认调整并保存</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="prereqMissingItems.length === 0 && prereqRemoveItems.length === 0"
|
||||||
|
type="primary"
|
||||||
|
:loading="prereqSaving"
|
||||||
|
@click="confirmPrereqAndSave"
|
||||||
|
>已处理,保存</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
<!-- 角色权限编辑抽屉已合并至角色管理抽屉 -->
|
<!-- 角色权限编辑抽屉已合并至角色管理抽屉 -->
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, onMounted, watch, reactive } from "vue";
|
import { ref, computed, onMounted, watch, reactive, nextTick } from "vue";
|
||||||
import { useRoute, useRouter } from "vue-router";
|
import { useRoute, useRouter } from "vue-router";
|
||||||
import { ElMessage, ElMessageBox } from "element-plus";
|
import { ElMessage, ElMessageBox } from "element-plus";
|
||||||
import { Files, Search, ArrowRight } from "@element-plus/icons-vue";
|
import { Files, Search, ArrowRight } from "@element-plus/icons-vue";
|
||||||
@@ -798,6 +920,15 @@ const activeRolesLoading = ref(false);
|
|||||||
const activeRolesSaving = ref(false);
|
const activeRolesSaving = ref(false);
|
||||||
const activeRolesDirtyGuard = useDrawerDirtyGuard(() => activeRolesDraft.value);
|
const activeRolesDirtyGuard = useDrawerDirtyGuard(() => activeRolesDraft.value);
|
||||||
|
|
||||||
|
const sortedTemplates = computed(() =>
|
||||||
|
[...templates.value].sort((a, b) => {
|
||||||
|
if (a.category && b.category) return compareRolesByTemplateOrder(a.category, b.category);
|
||||||
|
if (a.category) return -1;
|
||||||
|
if (b.category) return 1;
|
||||||
|
return 0;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
const roleOptions = computed(() => {
|
const roleOptions = computed(() => {
|
||||||
const options = templates.value.filter((template) => template.category).map((template) => ({
|
const options = templates.value.filter((template) => template.category).map((template) => ({
|
||||||
key: template.category!,
|
key: template.category!,
|
||||||
@@ -1046,6 +1177,7 @@ interface RoleEditorOp {
|
|||||||
module: string;
|
module: string;
|
||||||
action: string;
|
action: string;
|
||||||
description: string;
|
description: string;
|
||||||
|
prerequisite_permissions: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RoleEditorSection {
|
interface RoleEditorSection {
|
||||||
@@ -1053,6 +1185,11 @@ interface RoleEditorSection {
|
|||||||
ops: RoleEditorOp[];
|
ops: RoleEditorOp[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface RolePrerequisiteAdjustments {
|
||||||
|
add: Record<string, string[]>;
|
||||||
|
remove: Record<string, string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
const editingRole = ref("");
|
const editingRole = ref("");
|
||||||
const roleEditorSearch = ref("");
|
const roleEditorSearch = ref("");
|
||||||
const roleEditorDraft = ref<Record<string, boolean>>({});
|
const roleEditorDraft = ref<Record<string, boolean>>({});
|
||||||
@@ -1176,6 +1313,90 @@ const roleEditorModuleCount = (sections: RoleEditorSection[]): number =>
|
|||||||
const roleEditorEnabledCount = (ops: RoleEditorOp[]): number =>
|
const roleEditorEnabledCount = (ops: RoleEditorOp[]): number =>
|
||||||
ops.filter((op) => roleEditorDraft.value[op.operation_key]).length;
|
ops.filter((op) => roleEditorDraft.value[op.operation_key]).length;
|
||||||
|
|
||||||
|
const operationByKey = computed(() => {
|
||||||
|
const map: Record<string, RoleEditorOp> = {};
|
||||||
|
for (const op of allOperations.value) map[op.operation_key] = op;
|
||||||
|
return map;
|
||||||
|
});
|
||||||
|
|
||||||
|
const roleOperationLabel = (operationKey: string): string =>
|
||||||
|
operationByKey.value[operationKey]?.description || operationKey;
|
||||||
|
|
||||||
|
const roleOperationActionLabel = (operationKey: string): string => {
|
||||||
|
const op = operationByKey.value[operationKey];
|
||||||
|
if (!op) return "授权";
|
||||||
|
const verb = getOpVerb(op);
|
||||||
|
if (verb === "read") return "读取";
|
||||||
|
if (verb === "delete") return "删除";
|
||||||
|
return "写入";
|
||||||
|
};
|
||||||
|
|
||||||
|
const rolePermissionDisplayLabel = (operationKey: string): string =>
|
||||||
|
`${roleOperationActionLabel(operationKey)}|${roleOperationLabel(operationKey)}`;
|
||||||
|
|
||||||
|
const previewRolePrerequisiteAdjustments = (draft: Record<string, boolean>): RolePrerequisiteAdjustments => {
|
||||||
|
const add: Record<string, string[]> = {};
|
||||||
|
const remove: Record<string, string[]> = {};
|
||||||
|
const baseline: Record<string, boolean> = {};
|
||||||
|
const candidate = { ...draft };
|
||||||
|
const explicitlyDenied = new Set<string>();
|
||||||
|
|
||||||
|
const role = editingRole.value;
|
||||||
|
if (apiMatrix.value && apiMatrix.value[role]) {
|
||||||
|
for (const [key, val] of Object.entries(apiMatrix.value[role] as Record<string, any>)) {
|
||||||
|
baseline[key] = typeof val === "boolean" ? val : val.allowed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [key, allowed] of Object.entries(draft)) {
|
||||||
|
if (baseline[key] !== allowed && !allowed) explicitlyDenied.add(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 先补充缺失的前置权限(add 优先)
|
||||||
|
let changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (const op of allOperations.value) {
|
||||||
|
if (!candidate[op.operation_key]) continue;
|
||||||
|
for (const prereq of op.prerequisite_permissions) {
|
||||||
|
if (candidate[prereq]) continue;
|
||||||
|
const prerequisites = add[op.operation_key] || [];
|
||||||
|
if (!prerequisites.includes(prereq)) prerequisites.push(prereq);
|
||||||
|
add[op.operation_key] = prerequisites;
|
||||||
|
candidate[prereq] = true;
|
||||||
|
explicitlyDenied.delete(prereq); // 补回来的前置不再是"明确禁用"
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 再级联禁用受影响的下游权限(remove)
|
||||||
|
changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (const op of allOperations.value) {
|
||||||
|
if (!candidate[op.operation_key] || explicitlyDenied.has(op.operation_key)) continue;
|
||||||
|
const deniedPrereq = op.prerequisite_permissions.find((key) => explicitlyDenied.has(key));
|
||||||
|
if (!deniedPrereq) continue;
|
||||||
|
const dependents = remove[deniedPrereq] || [];
|
||||||
|
if (!dependents.includes(op.operation_key)) dependents.push(op.operation_key);
|
||||||
|
remove[deniedPrereq] = dependents;
|
||||||
|
candidate[op.operation_key] = false;
|
||||||
|
explicitlyDenied.add(op.operation_key);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { add, remove };
|
||||||
|
};
|
||||||
|
|
||||||
|
const hasPrerequisiteAdjustments = (adjustments: RolePrerequisiteAdjustments): boolean =>
|
||||||
|
Object.keys(adjustments.add).length > 0 || Object.keys(adjustments.remove).length > 0;
|
||||||
|
|
||||||
|
const handleRolePermissionChange = (op: RoleEditorOp, allowed: boolean) => {
|
||||||
|
roleEditorDraft.value = { ...roleEditorDraft.value, [op.operation_key]: allowed };
|
||||||
|
};
|
||||||
|
|
||||||
const canEditSelectedRole = computed(() => {
|
const canEditSelectedRole = computed(() => {
|
||||||
if (editingRole.value === "ADMIN") return false;
|
if (editingRole.value === "ADMIN") return false;
|
||||||
if (isAdmin.value) return true;
|
if (isAdmin.value) return true;
|
||||||
@@ -1221,12 +1442,131 @@ const initRoleEditor = () => {
|
|||||||
roleEditorDirtyGuard.syncBaseline();
|
roleEditorDirtyGuard.syncBaseline();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const cancelRoleEditor = () => {
|
||||||
|
editingRole.value = "";
|
||||||
|
roleEditorSearch.value = "";
|
||||||
|
roleEditorDraft.value = {};
|
||||||
|
roleEditorDirtyGuard.syncBaseline();
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── 权限校验 Dialog ──
|
||||||
|
const prereqCheckVisible = ref(false);
|
||||||
|
const prereqCheckStep = ref<"checking" | "passed" | "failed">("checking");
|
||||||
|
const prereqCheckItems = ref<Array<{ label: string; status: "checking" | "ok" | "fail" | "warn" }>>([]);
|
||||||
|
const prereqAdjustments = ref<RolePrerequisiteAdjustments>({ add: {}, remove: {} });
|
||||||
|
const prereqSaving = ref(false);
|
||||||
|
|
||||||
|
const prereqCheckLabels = [
|
||||||
|
"分析已启用权限依赖关系",
|
||||||
|
"检查前置权限完整性",
|
||||||
|
"检查下游权限一致性",
|
||||||
|
];
|
||||||
|
|
||||||
|
const openPrereqCheck = async (): Promise<boolean> => {
|
||||||
|
prereqCheckVisible.value = true;
|
||||||
|
prereqCheckStep.value = "checking";
|
||||||
|
prereqCheckItems.value = prereqCheckLabels.map((label) => ({ label, status: "checking" }));
|
||||||
|
prereqAdjustments.value = { add: {}, remove: {} };
|
||||||
|
|
||||||
|
// 逐步动画显示校验过程
|
||||||
|
for (let i = 0; i < prereqCheckLabels.length; i++) {
|
||||||
|
await new Promise((r) => setTimeout(r, 320 + i * 180));
|
||||||
|
prereqCheckItems.value[i].status = "ok";
|
||||||
|
}
|
||||||
|
|
||||||
|
const adjustments = previewRolePrerequisiteAdjustments(roleEditorDraft.value);
|
||||||
|
prereqAdjustments.value = adjustments;
|
||||||
|
|
||||||
|
if (!hasPrerequisiteAdjustments(adjustments)) {
|
||||||
|
prereqCheckStep.value = "passed";
|
||||||
|
await new Promise((r) => setTimeout(r, 600));
|
||||||
|
prereqCheckVisible.value = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 标记状态:有缺失前置 → 红叉;纯下游受影响 → 黄色警告
|
||||||
|
const hasAdd = Object.keys(adjustments.add).length > 0;
|
||||||
|
for (const item of prereqCheckItems.value) {
|
||||||
|
item.status = hasAdd ? "fail" : "warn";
|
||||||
|
}
|
||||||
|
prereqCheckStep.value = "failed";
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const prereqMissingItems = computed(() => {
|
||||||
|
const items: Array<{ dependentKey: string; prereqKey: string }> = [];
|
||||||
|
for (const [dependentKey, prereqs] of Object.entries(prereqAdjustments.value.add)) {
|
||||||
|
for (const prereqKey of prereqs) {
|
||||||
|
items.push({ dependentKey, prereqKey });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
});
|
||||||
|
|
||||||
|
const prereqRemoveItems = computed(() => {
|
||||||
|
const items: Array<{ prereqKey: string; dependentKey: string }> = [];
|
||||||
|
for (const [prereqKey, dependents] of Object.entries(prereqAdjustments.value.remove)) {
|
||||||
|
for (const dependentKey of dependents) {
|
||||||
|
items.push({ prereqKey, dependentKey });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
});
|
||||||
|
|
||||||
|
const markAllStepsOk = () => {
|
||||||
|
prereqCheckItems.value = prereqCheckItems.value.map((item) => ({ ...item, status: "ok" as const }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const grantSinglePrereq = (prereqKey: string) => {
|
||||||
|
roleEditorDraft.value = { ...roleEditorDraft.value, [prereqKey]: true };
|
||||||
|
prereqAdjustments.value = previewRolePrerequisiteAdjustments(roleEditorDraft.value);
|
||||||
|
if (!hasPrerequisiteAdjustments(prereqAdjustments.value)) {
|
||||||
|
markAllStepsOk();
|
||||||
|
prereqCheckStep.value = "passed";
|
||||||
|
setTimeout(() => confirmPrereqAndSave(), 800);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const grantAllPrereqs = () => {
|
||||||
|
const next = { ...roleEditorDraft.value };
|
||||||
|
for (const prereqs of Object.values(prereqAdjustments.value.add)) {
|
||||||
|
for (const p of prereqs) next[p] = true;
|
||||||
|
}
|
||||||
|
roleEditorDraft.value = next;
|
||||||
|
prereqAdjustments.value = previewRolePrerequisiteAdjustments(next);
|
||||||
|
markAllStepsOk();
|
||||||
|
prereqCheckStep.value = "passed";
|
||||||
|
setTimeout(() => confirmPrereqAndSave(), 800);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmPrereqAndSave = async () => {
|
||||||
|
prereqSaving.value = true;
|
||||||
|
try {
|
||||||
|
const payload = flattenRolePermissions(editingRole.value, roleEditorDraft.value);
|
||||||
|
const res = await updateApiEndpointPermissions(selectedStudyId.value, payload, { confirm_prerequisite_adjustments: true });
|
||||||
|
apiMatrix.value = res.data;
|
||||||
|
const savedRole = editingRole.value;
|
||||||
|
prereqCheckVisible.value = false;
|
||||||
|
editingRole.value = "";
|
||||||
|
roleEditorDirtyGuard.syncBaseline();
|
||||||
|
ElMessage.success(`${roleLabel(savedRole)} 权限已保存`);
|
||||||
|
} catch (error: any) {
|
||||||
|
ElMessage.error(error?.response?.data?.detail?.message || "保存失败");
|
||||||
|
} finally {
|
||||||
|
prereqSaving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const saveRoleEditor = async () => {
|
const saveRoleEditor = async () => {
|
||||||
if (!selectedStudyId.value || !apiMatrix.value) return;
|
if (!selectedStudyId.value || !apiMatrix.value) return;
|
||||||
if (!canEditSelectedRole.value) {
|
if (!canEditSelectedRole.value) {
|
||||||
ElMessage.warning("当前角色权限不可修改");
|
ElMessage.warning("当前角色权限不可修改");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const passed = await openPrereqCheck();
|
||||||
|
if (!passed) return; // Dialog 保持打开,等用户操作
|
||||||
|
|
||||||
|
// 校验通过,直接保存
|
||||||
roleEditorSaving.value = true;
|
roleEditorSaving.value = true;
|
||||||
try {
|
try {
|
||||||
const payload = flattenRolePermissions(editingRole.value, roleEditorDraft.value);
|
const payload = flattenRolePermissions(editingRole.value, roleEditorDraft.value);
|
||||||
@@ -1236,8 +1576,9 @@ const saveRoleEditor = async () => {
|
|||||||
editingRole.value = "";
|
editingRole.value = "";
|
||||||
roleEditorDirtyGuard.syncBaseline();
|
roleEditorDirtyGuard.syncBaseline();
|
||||||
ElMessage.success(`${roleLabel(savedRole)} 权限已保存`);
|
ElMessage.success(`${roleLabel(savedRole)} 权限已保存`);
|
||||||
} catch {
|
} catch (error: any) {
|
||||||
ElMessage.error("保存失败");
|
if (error === "cancel" || error === "close") return;
|
||||||
|
ElMessage.error(error?.response?.data?.detail?.message || "保存失败");
|
||||||
} finally {
|
} finally {
|
||||||
roleEditorSaving.value = false;
|
roleEditorSaving.value = false;
|
||||||
}
|
}
|
||||||
@@ -2020,3 +2361,252 @@ onMounted(async () => {
|
|||||||
color: #1e293b;
|
color: #1e293b;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
/* ══════════════════════════════════════
|
||||||
|
权限依赖校验 Dialog
|
||||||
|
══════════════════════════════════════ */
|
||||||
|
.prereq-check-body {
|
||||||
|
padding: 4px 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-check-steps {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-check-step {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #f8fafc;
|
||||||
|
border: 1px solid #e8edf3;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
font-size: 14px;
|
||||||
|
color: #64748b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-check-step--ok {
|
||||||
|
background: #f0fdf4;
|
||||||
|
border-color: #bbf7d0;
|
||||||
|
color: #15803d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-check-step--fail {
|
||||||
|
background: #fff7ed;
|
||||||
|
border-color: #fed7aa;
|
||||||
|
color: #c2410c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-check-step--warn {
|
||||||
|
background: #fefce8;
|
||||||
|
border-color: #fde68a;
|
||||||
|
color: #92400e;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-step-icon {
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-step-icon svg {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-check-step--ok .prereq-step-icon svg { stroke: #16a34a; }
|
||||||
|
.prereq-check-step--fail .prereq-step-icon svg { stroke: #dc2626; }
|
||||||
|
.prereq-check-step--warn .prereq-step-icon svg { stroke: #d97706; }
|
||||||
|
|
||||||
|
.prereq-step-spinner {
|
||||||
|
display: block;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
border: 2px solid #cbd5e1;
|
||||||
|
border-top-color: #6366f1;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: prereq-spin 0.7s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes prereq-spin {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-step-label {
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 通过结果 */
|
||||||
|
.prereq-result--pass {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 16px 18px;
|
||||||
|
background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
|
||||||
|
border: 1.5px solid #86efac;
|
||||||
|
border-radius: 10px;
|
||||||
|
color: #15803d;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-result--pass svg {
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
stroke: #16a34a;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 失败:问题列表 */
|
||||||
|
.prereq-issues {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-issues-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
background: #fff7ed;
|
||||||
|
border: 1px solid #fed7aa;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #9a3412;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-issues-header svg {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
stroke: #ea580c;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-section-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-section-badge {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 20px;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-section-badge--add {
|
||||||
|
background: #eff6ff;
|
||||||
|
color: #1d4ed8;
|
||||||
|
border: 1px solid #bfdbfe;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-section-badge--remove {
|
||||||
|
background: #fef2f2;
|
||||||
|
color: #b91c1c;
|
||||||
|
border: 1px solid #fecaca;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-grant-all-btn {
|
||||||
|
margin-left: auto;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item--missing {
|
||||||
|
background: #f8faff;
|
||||||
|
border-color: #c7d7fe;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item--remove {
|
||||||
|
background: #fff8f8;
|
||||||
|
border-color: #fecaca;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item-info {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item-arrow {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #94a3b8;
|
||||||
|
padding: 0 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item-chip {
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 1px 6px;
|
||||||
|
border-radius: 20px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-item-chip--enabled { background: #dcfce7; color: #15803d; }
|
||||||
|
.prereq-item-chip--missing { background: #fee2e2; color: #b91c1c; }
|
||||||
|
.prereq-item-chip--disabled { background: #f1f5f9; color: #64748b; }
|
||||||
|
.prereq-item-chip--will-remove { background: #fef9c3; color: #854d0e; }
|
||||||
|
|
||||||
|
.prereq-item-name {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #334155;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-dialog-footer {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 进入动画 */
|
||||||
|
.prereq-result-enter-active {
|
||||||
|
transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.prereq-result-enter-from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(8px) scale(0.98);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
Reference in New Issue
Block a user